Assuming that PostForm is a form for Post and notUser, this instance parameter is not correct. If this is creating a new Post, you don’t want to include the instance parameter at all.
This line that you already have:
will do the right thing here.
It appears that you are also making the assumption that a OneToOne relationship implies that the PK fields would all have the same value. This is not correct. There is no requirement that those values all remain the same. (In fact, you could even have different field types for the PKs of the related tables, which means they cannot even be the same.) You need to assign the references appropriately between Post and Snippet.
Finally:
This is probably not going to work for you. Python short-circuits boolean operators - this means that the second statement (snpt.save()) is only going to run if post.save() returns a “truthy” value. Unless you’ve overridden the save method within your Post object, this will fail.
Separate these two calls into two separate statements.
This is all I can see from what you’ve got posted. To provide any more specific or detailed information would require you to post the complete models and forms being used here.
class PostForm(forms.ModelForm):
add_code = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'checkbox', 'id': 'post-snippet'}), required=False)# attr. for JS addEvent or css styling
tag = forms.ModelChoiceField(queryset=Tag.objects.all(), widget=forms.Select())
genre = forms.ModelChoiceField(queryset=Genre.objects.all(), widget=forms.Select())
class Meta:
model = Post
#fields = '__all__'
#fields = ['title', 'tag', 'maintainer', 'post_img', 'content', 'snippet', 'genre', 'post_language', 'video', 'post_type', 'urls', 'views', 'status' ]
exclude = ('creator', 'snippet')
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = '__all__'
firstly i was trying everything cause i already was trying the view without instance=request.user secondly would you mean by changing the relation references appropriately between Post and Snippet, that i have to put ForeignKey relation in Post model ? Thirdly you were right about the short circuit and this is the second time i forget that okay i will try what you recommend and back to you bro
I’m assuming there’s no ForeignKey or OneToOneField in Snippet, so you can save snippet_form without the commit=False. (It’s not needed because there’s no reason to change anything in that model other than what’s in the form.)
This means that you now have snpt as an instance of Snippet. You then assign it to the snippet field of post (e.g. post.snippet = snpt) instead of snpt.id = post.id (this statement should be removed).
Then, you only need to do the post.save(), because that’s the only model changed.