foreign key is required

form


class EventForm(ModelForm):
    class Meta:
        model = Event
        fields = [
            'topic',
            'short_description',
            'full_description',
            'date',
            'time',
            'place',
            'max_people',
            'creator',
        ]

        widgets = {
            'topic': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Topic',
                'autocomplete': 'disabled',
            }),

            'short_description': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Short description',
                'autocomplete': 'disabled',

            }),

            'full_description': Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'Full description',
                'autocomplete': 'disabled',

            }),

            'date': DateInput(
                attrs={
                    'class': 'form-control',
                    'type': 'date',
                    'placeholder': 'Event date',
                }
            ),

            'time': TimeInput(
                attrs={
                    'class': 'form-control',
                    'type': 'time',
                    'placeholder': 'Event time',
                }
            ),

            'place': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Event place',
                'autocomplete': 'disabled',

            }),

            'max_people': NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'Max people',
                'autocomplete': 'disabled',

            }),

        }

view


def events_create(request):
    error = ''

    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            print('----valid')
            event_instance = form.save(commit=False)
            event_instance.creator = request.user
            event_instance.save()

            return redirect('events_home')
        else:
            print(form.errors)
            error = 'Error in form'
    else:
        form = EventForm()

    data = {
        'form': form,
        'error': error,
    }

    return render(request, 'events/events_create.html', data)

and i have error

  • creator
    • This field is required.

how i can write authorizated user into creator?
My code not working

If you’re writing the creator field in the view, then it shouldn’t be in the form. Remove it from the fields list in your form definition.