Django instance in model form

Question:

There was a problem. I wanted to make a Django user object creation form, but it doesn’t work. Exactly the same view with a different model works fine. I think the problem is how I transmit the data and instance in form.

Views

@login_required(login_url='login')
def CreateRoom(request, pk):

    topic = Topic.objects.get(id=pk)
    form = RoomForm(data=request.POST, instance=room)

    if request.method == 'POST':
        if form.is_valid():

            room = form.save(commit=False)
            room.host=request.user
            room.topic=topic
            room.save()
            return redirect('home')


    context = {'form': form, 'topic': topic}
    return render(request, 'room_form.html', context)

Forms


class RoomForm(ModelForm):

    def __init__(self, *args, **kwargs):


        super(RoomForm, self).__init__(*args, **kwargs)

        self.fields['themes'].queryset = self.instance.themes.all()



    class Meta:

        model = Room

        fields = '__all__'
        exclude = ['topic', 'host', 'participants']
Asked By: kloskutov

||

Answers:

You are assigning a non-existing instance (room) to your form. You should change the view to something like:

topic = Topic.objects.get(id=pk)
room = Room.objects.create(topic=topic)
form = RoomForm(request.POST, instance=room)
if request.method == 'POST':
    if form.is_valid(): 
        room = form.save(commit=False)
        room.host=request.user
        room.save()
        return redirect('home')
Answered By: haduki
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.