简体   繁体   中英

Django instance in model form

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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM