I have these two blog models in models.py
class Snippet(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
...
class Post(models.Model):
# id = models.AutoField(primary_key=True) # the same field in comment model for multi-inheritance (post_id)
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True, editable=False) # add unique=True in slug (never repeat)
title = models.CharField(max_length=200, db_index=True, default='')
tag = models.ManyToManyField(Tag, blank=True, help_text="Select a tag for this post", related_name='post_tags')
snippet = models.OneToOneField(Snippet, on_delete=models.CASCADE, related_name='post_snippets')
...
and i have forms to add new post as follows
class PostModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "Post #%s) %s" % (obj.id, obj.title)
class SnippetForm(forms.ModelForm):
post = PostModelChoiceField(queryset=Post.objects.all())
class Meta:
model = Snippet
fields = '__all__'
class PostForm(forms.ModelForm):
class Meta:
model = Post
#fields = '__all__'
#fields = ['title', 'tag', 'maintainer', 'post_img', 'content', 'snippet', 'genre', 'language', 'video', 'post_type', 'urls', 'views', 'status' ]
labels = {'snippet': _('Add Code'),}
exclude = ('creator', 'slug',)
widgets = {
'snippet': forms.CheckboxInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'post-snippet'})
}
def clean(self):
snippet = self.cleaned_data.get('snippet')
if snippet:
self.fields_required(snippet.title, snippet.code, snippet.title, snippet.linenos, snippet.language, snippet.style, snippet.highlighted) # ['title', 'code', 'linenos', ....]
else:
self.cleaned_data['snippet'] = False
return self.cleaned_data
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.queryset = Post.objects.filter(snippet=True)
and views to render template
def add_post(request):
if request.method == 'POST':
post_form = PostForm(request.POST, request.FILES, instance=request.user)
snippet = post_form.cleaned_data['snippet']
if snippet:
#snpt = modelformset_factory(Snippet, fields=('title', 'code', 'linenos', 'language', 'style', 'highlighted'))
snpt = Snippet.objects.create(post = request.post, snippet_id = request.post.id)
snippet_form = SnippetForm(request.POST, instance=snpt)
if post_form.is_valid() and snippet_form.is_valid():
post = post_form.save(commit=False)
snpt = snippet_form.save(commit=False)
post.creator = request.user
post.snippet = snpt
post.slug = slugify(post_form.cleaned_data['title'])
post.save() and snpt.save()
obj = post_form.instance
alert = True
return redirect('blog:post_list')
#return render(request, "add_post.html",{'obj':obj, 'alert':alert})
#return HttpResponseRedirect('blog/post_list/success/')
else:
post_form = PostForm()
return render(request, 'blog/add_post.html', {'form': post_form})
Now i can’t get the snippet fields in my template when i tick the check box in the template
Here is the form
<form method='POST' class="form" enctype='multipart/form-data'>
{{ form.non_field_errors }} {% csrf_token %} {% for field in form %}
<div class="apply">
{% if field.errors %}
<ol>
{% for error in field.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %} {% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %} {% bootstrap_form form %}
<button class="boxed-btn3 w-100" type="submit">Post</button>
</form>
what’s wrong in this logic why the snippet form doesn’t show up in the template and how to get it live immediately when i check the boolean field add code (snippet) in the page form
please help me bro