The submit button doesn't work.
Can't save in database
{% block content %}
<form class="" action="{% url 'post_create_url' %}" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{% if field.errors %}
<div class="alert alert-danger">
{{ field.errors }}
</div>
{% endif %}
{{ field.label }}
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Create Post</button>
</form>
{% endblock %}
this is my views.py code
class PostCreate(View):
def get(self, request):
form = PostForm()
return render(request, 'blog/post_create_form.html', context={'form': form})
def post(self, request):
bound_form = PostForm(request.POST)
if bound_form.is_valid():
new_post = bound_form.save()
return redirect(new_post)
return render(request, 'blog/post_create_form.html', context={'form': bound_form})
and this is my form code
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'slug', 'body', 'tags']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'slug': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
'tags': forms.SelectMultiple(attrs={'class': 'form-control'}),
}
def clean_slug(self):
new_slug = self.cleaned_data['slug'].lower()
if new_slug == 'create':
raise ValidationError('Slug may not be "Create"')
return new_slug`
class PostCreate(View):
def get(self, request):
form = PostForm()
return render(request, 'blog/post_create_form.html', context={'form': form})
def post(self, request):
bound_form = PostForm(request.POST)
if bound_form.is_valid():
### new_post = bound_form.save() That's the problem.
bound_form.save()
###return redirect(new_post)
return HttpResponseRedirect('new_post')
return render(request, 'blog/post_create_form.html', context={'form': bound_form})
Related
After displaying my posts, I don't manage to Edit any of them.
When I print the instance variable which is in views.py in my terminal, it displays only the title and the author like this title - author, which is the method defined in models.py.
Help please!
Views.py
#login_required(login_url='login_view')
def update_post_view(request, post_id, slug=None):
instance = Article.objects.get(id = post_id)
if request.method == 'POST':
form = UpdatePostForm(request.POST, request.FILES, instance=instance)
if form.is_valid():
form.save()
return redirect('posts_view')
else:
form = UpdatePostForm(instance=instance)
return render(request,'update_post.html', {'form':form})
forms.py
class UpdatePostForm(forms.ModelForm):
class Meta:
model = Article
fields = ('author',)
title = forms.CharField(max_length=255, label='username',
widget= forms.TextInput(attrs= {'placeholder':'Title...', 'class': 'title'}))
body = forms.CharField(max_length=255, label='body', required=True, widget=forms.Textarea(attrs={'placeholder':'Start writing your post...'}))
urls.py
path('update_post/<int:post_id>/<slug:slug>', views.update_post_view, name='update_post_view')
update_post.html
{% extends 'base.html' %}
{% block title %}Update Post{% endblock %}
{% block content %}
<h2>Update Posts...</h2>
<form action="" method="POST">
{% csrf_token %}
<div>
<h3>{{form.title}}</h3>
<small>{{form.author}}</small>
<p>{{form.body}}</p>
</div>
<button class="btn btn-secondary">Update</button>
</form>
{% endblock %}
Picture gets uploaded on the django admin panel but when i click on the image on the panel it shows the page not found error.
forms.py
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = ['photo']
urls.py
path('w_p.html', views.WProduct_list, name='WProduct_list'),
views.py
def WProduct_list(request, category_slug=None):
category = None
categories = Category.objects.all()
wproducts = Product.objects.filter()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
wproducts = Product.objects.filter()
if(request.method=='POST'):
form = ApproveImgForm(request.POST, request.FILES)
form.save()
context = {
'category': category,
'categories': categories,
'wproducts': wproducts,
}
return render(request, 'shop/w_p.html', context)
models.py
class ApprovImg(models.Model):
photo=models.ImageField(upload_to='products/%Y/%m/%d')
def __str__(self):
return str(self.photo)
w_p.html
<tr>
<td>{{ product.name }}</td>
<td> {{ product.price }}</td>
<td><form action="w_p.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit">
</form>
</td>
</tr
Can someone please help?
You should inherit from ModelForm.
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = "__all__" # not recommended, you should specify the fields.
# views.py
def upload_file(request):
if request.method == 'POST':
form = ApproveImgForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect('/home/')
else:
form = ApproveImgForm
return render(request, 'upload_image.html', {'form': form})
# urls.py
urlpatterns = [path('upload', upload_file, name='upload')]
# upload_image.html
<form action="{% url 'upload' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.photo.label_tag }} {{ form.photo.help_text }}</p>
<p>
{{ form.photo.errors }}
{{ form.photo }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
I’m trying to set the default value in the form (the field is the date for publishing the article “public”), but when loading the form on the page, the field is empty. I tried to set the default value in the "header" field (any value, not necessarily today's date) - also does not appear.
form:
from main.models import Article
from datetime import datetime
class AddArticleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddArticleForm, self).__init__(*args, **kwargs)
self.fields['publish'].initial = datetime.now()
class Meta:
model = Article
fields = ('title', 'author', 'body', 'publish', 'status')
labels = {
'body': 'Text'
}
widgets = {
'title': forms.TextInput(attrs={'class': 'md-form'}),
'author': forms.TextInput(attrs={'class': 'md-form'}),
'body': forms.Textarea(attrs={'class': 'md-textarea', 'rows': 3}),
'publish': forms.DateTimeInput(attrs={'class': 'md-form'}),
'status': forms.Select(attrs={'class': 'custom-select'})
}
views:
def add_article(request):
form = AddArticleForm(request.POST)
if form.is_valid():
form.save()
return redirect('/articles/')
args = {
'form': form
}
return render(request, 'html/add_article.html', args)
html:
...
<form action="." method="post" class="add-article">
{% csrf_token %}
{% for field in form %}
<div class="md-form">
{% if field.name != 'status' and field.name != 'publish' %}
<label for="{{ field.name }}">{{ field.label }}</label> {{ field }}
{% else %}
<label for="{{ field.name }}"></label> {{ field }}
{% endif %}
</div>
{% endfor %}
<button type="submit" class="btn btn-pink btn-block">Share</button>
</form>
...
Probably the issue is you are sending request.POST as argument to the form class even if it is a GET request.
form = AddArticleForm(request.POST)
^^^^^^^^^^^^^
So I suggest to update the view like this:
def add_article(request):
form = AddArticleForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect('/articles/')
context = {
'form': form
}
return render(request, 'html/add_article.html', context)
So that, it will handle POST requests explicitly, and send request.POST as argument only if there is request.POST.
I think you should add initial argument in your field form.
For example:
name = forms.CharField(initial='Your name')
Here is documentation on this:
https://docs.djangoproject.com/en/3.0/ref/forms/fields/#initial
I want to display only employees which emp_type is 'Doctor'?
** Here is Models.py **
class Employee(models.Model):
name = models.CharField(max_length=50)
emp_type_choices = [
('Nurse', 'Nurse'),
('Doctor', 'Doctor'),
('Other', 'Other'),
]
emp_type = models.CharField(
max_length=6, choices=emp_type_choices, default='Nurse')
def __str__(self):
return self.name
class Ticket(models.Model):
patient = models.CharField(max_length=50)
doctor = models.ForeignKey(Employee, on_delete=models.CASCADE)
def __str__(self):
return self.patient.name
This is my Forms.py
class TicketModelForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ['doctor', 'status']
widgets = {
'doctor': forms.Select(attrs={'class': 'form-control','placeholder': 'Doctor Name'}),
}
This is my Views.py
#login_required
def TicketToGenerateView(request, pk):
ticket = get_object_or_404(Patient, pk=pk)
form = TicketModelForm(request.POST or None)
if form.is_valid():
obj.save()
return redirect('/dashboard/ticket')
context = {
'form': form,
'ticket': ticket,
}
return render(request, 'dashboard/ticket.html', context)
This is my Template
<form action="." method="POST">
{% csrf_token %}.
{% for field in form %}
<div class="form-group">
{{ field }}
{% if field.errors %}
{% for error in field.errors %}
<p class="text-danger">{{ error|escape }}</p>
{% endfor %}
{% endif %}
</div>
{% endfor %}
<div class="form-group float-right">
<button type="submit" class="btn btn-success btn-sm" value=" {{ valueBtn }} "> <span
class="glyphicon glyphicon-plus"></span> </button>
</div>
</form>
In the template, I'm displaying all registered employees as a dropdown list, but I would like to display only employees which their emp_type is 'Doctor'.
Also the Admin site I would like to see the only emp_type which are 'Doctor'.
Thanks
# You have to use filter for your query
emp_doctor = Employee.objects.filter(emp_type='Doctor')
print(emp_doctor)
I am trying to use Taggit for users to be able to tag their posts while they are submitting a form. But I can successfully let them type manually(their tags), I am trying to change to check boxes. Any ideas?
forms.py
class TalesForm(ModelForm):
class Meta:
model = Tale
fields = ('title', 'body', 'tags')
m_tags = TagField()
models.py
class Tale(models.Model):
title = models.CharField(max_length = 50)
body = models.TextField(max_length = 10000)
pub_date = models.DateTimeField(default = datetime.now)
poster = models.CharField(max_length = 30)
tags = TaggableManager()
def __unicode__(self):
return self.title
views.py
def add(request):
if request.user.is_authenticated():
if request.method=='POST':
form=TalesForm(request.POST)
if form.is_valid():
m_tags = form.cleaned_data['tags']
newTale=Tale(title=form.cleaned_data['title'], body=form.cleaned_data['body'], poster = request.user)
newTale.save()
for m_tag in m_tags:
newTale.tags.add(m_tag)
#form.save_m2m()
return HttpResponseRedirect('/home/%s'%newTale.id)
else:
return render_to_response('story/add.html', {'form':form}, context_instance=RequestContext(request))
else:
form=TalesForm()
args = {}
args.update(csrf(request))
args['form'] = form
context= {'form': form}
return render_to_response('story/add.html',context, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/home')
html
<form method="post" action="/home/add/">
{% csrf_token %}
<div class="register_div">
{% if form.title.errors %}<p class="error" >{{ form.title.errors }}</p>{% endif %}
<p><label for="title"{% if form.title.errors %} class="error"{% endif %}>Title:</label></p>
<p>{{ form.title}}</p>
</div>
<div class="register_div">
{% if form.body.errors %}<p class="error" >{{ form.body.errors }}</p>{% endif %}
<p><label for="body"{% if form.body.errors %} class="error"{% endif %}>Body:</label></p>
<p>{{ form.body }}</p>
</div>
<div class="register_div">
<p><label for="tag">Tags:</label></p>
<p>{{ form.tags }}</p>
</div>
<input type="submit" value="Add Story" name="submit" />
</form>
Define your form this way:
from taggit.models import Tag
class TalesForm(ModelForm):
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all(),
widget=forms.CheckboxSelectMultiple())
class Meta:
model = Tale
fields = ('title', 'body', 'tags')