Home > Net >  Django instance in model form
Django instance in model form

Time:09-26

There was a problem, I wanted to make an 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']

CodePudding user response:

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')
  • Related