ModelForm with multiple values not responsive - python

so I encountered this problem with Django and ModelForms. Everything loads as expected but when I'm trying to send data by hitting Enter nothing happens.
models.py
class Drinks(models.Model):
name = models.CharField(max_length=50)
number = models.DecimalField(decimal_places=2, max_digits=2000)
def __str__(self):
return self.name
forms.py ( I tried with list and tuple as well )
class DrinksForm(forms.ModelForm):
class Meta:
model = Drinks
fields = [
'name',
'number'
]
views.py
def DrinksView(request):
form = DrinksForm(request.POST or None)
if form.is_valid():
print("VALIDATION COMPLETE")
form.save()
form = DrinksForm()
return render (request, 'form2.html', { 'form' : form })
template.html
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
admin.py
from django.contrib import admin
from .models import Drinks
admin.site.register(Drinks)
I did all necessary migrations.
Any Ideas what im doing wrong?

Your form doesn't have a submit button:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
For your view, consider this instead:
def new_drink_view(request):
if request.method == "POST":
form = DrinksForm(request.POST)
# check if valid
# ...
else:
form = DrinksForm()
return render (request, 'form2.html', { 'form' : form })
Be sure to import the DrinksForm form.

Related

Django forms is not valid

my page html :
resrver salle !
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="reserver">
</form>
views .py :
def reserversalle(request , id):
form= ReserverSalle(request.POST or None)
print(form)
if form.is_valid():
print("gooddd")
context= {
'form' : form ,
}
return render(request,'registration/reserversalle.html', context)
forms.py :
class ReserverSalle(forms.Form):
nomsalle = forms.CharField(required=True , widget=forms.TextInput)
motifresa = forms.CharField(required=True , widget=forms.TextInput)
datedebut = forms.DateField( initial="2019-06-21",
widget=forms.SelectDateWidget(years=YEARS))
heuredebut = forms.TimeField( initial='00:00:00')
heurefin = forms.TimeField( initial='00:00:00')
hello i try to submit my form but my form is not valid please i need some help
Try adding form attributes action and method
<form action="." method="post">...</form>
if request.method == 'POST':
form = ReserverSalle(request.POST)
....
else:
form = ReserverSalle()
you need to specify method and action in your form tag in html
<form method="POST" action="<<URL_TO_HANDLE_YOUR_FORM>>">
<> means Url specified in your URL.py which direct it to the views.py function you have written

Django - filter drop down choices based on user group

i am trying to filter a forms drop down list based on a users group
To find the user group i am using a custom templatetag
template tag
from django import template
register = template.Library()
#register.filter(name='in_group')
def in_group(user,group_name):
try:
group=Group.objects.get(name=group_name)
except Group.DoesNotExist:
return False
return group in user.groups.all()
task.html
{% load group_check %}
<form method="post">
{% csrf_token %}
{% if user.is authenticated %}
{% if requset.user|in_group:'DEVELOPER' %}
#...DO SOMETHING
{{ form.as_p }}
<button type="submit">add task</button>
</form>
models
GOALS_TYPE= (('DT','Daily Task'),
('WT','Weekly Task'),
('V','Verified'),
('D','Done'),
)
class GoalStatus(models.Model):
title = models.CharField(max_length=254, null=True)
task_id=models.IntegerField(default=1,null=False)
description =models.CharField(max_length=254)
verified_by=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null=True)
status=models.CharField(choices=GOALS_TYPE, max_length=2, default='DT')
def __str__(self):
return self.title
the template for the form is based on the forms.py
forms.py
class ChangeTaskForm(forms.ModelForm):
class Meta:
model = GoalStatus
fields = ('title', 'task_id','description','status', 'verified_by')
views.py
def move_goals(request,pk):
if request.method == 'POST':
form = ChangeTaskForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/index/')
else:
form = ChangeTaskForm()
return render(request, 'oderascrumy/task.html', {'form': form})
urls.py
path('task/<pk>/', views.move_goals, name='move_goals')
so for example if the user is in group "developer", the drop down choices for status will be only verified and done
You can do like below
views.py
def move_goals(request,pk):
if request.method == 'POST':
form = ChangeTaskForm(request.POST, user=request.user)
if form.is_valid():
return HttpResponseRedirect('/index/')
else:
form = ChangeTaskForm(user=request.user)
return render(request, 'oderascrumy/task.html', {'form': form})
forms.py
class ChangeTaskForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(ChangeTaskForm, self).__init__(*args, **kwargs)
if user.groups.filter(name='DEVELOPER').exists():
self.fields['status'].choices = (('V','Verified'), ('D','Done'),)
class Meta:
model = GoalStatus
fields = ('title', 'task_id','description','status', 'verified_by')
template.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">add task</button>
</form>
I think no need of template tag for this.

"This field is required" when field is populated on Django modelForm

After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:
forms.py:
class UploadFileForm(forms.ModelForm):
class Meta:
model = Job
fields = ['jobID',
'original_file']
labels = { 'jobID': _('Job ID'),
'original_file': _('File'),}
error_messages = {
'jobID': {'max_length': _("Job ID is limited to 50 characters."),
},
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
models.py:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Job(models.Model):
user = models.ForeignKey('auth.User')
original_file = models.FileField()
jobID = models.CharField(max_length=50)
rev = models.IntegerField()
create_date = models.DateTimeField(default = timezone.now)
def save(self):
"Get last value of rev considering jobID and User and increment"
"see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
if last_rev:
rev = last_rev[0].rev + 1
else:
rev = 1
super(Job,self).save()
def __unicode__(self):
return self.jobID + " rev " + str(self.rev)
class Meta:
indexes = [
models.Index(fields=['user','jobID']),
]
unique_together = ("user","jobID","rev")
ordering = ['-create_date']
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job
# Create your views here.
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request,'precheck/prestage.html')
else:
form = UploadFileForm()
return render(request, 'precheck/upload.html',{'form': form})
def success(request):
return render(request, 'precheck/prestage.html')
upload.html
{% extends 'base.html' %}
{% block content %}
<h2>Upload File</h2>
{% if error %}
{{ error }}
<br />
<br />
{% endif %}
<form method = "POST" action="{% url 'precheck:upload' %}">
{% csrf_token %}
{{ form.as_p }}
<br />
<input type="submit" class="btn btn-primary" value="Upload">
</form>
{% endblock %}
I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.
EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:
<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">
The error is not for jobID, but for original_file. This is because you are not using the enctype="multipart/form-data" attribute on the form element.

trouble with subscribing form (Django)

Please, help.. I do not udersatand what I should do this code to work..
home.html:
<form class="subscribe-form" action="{% url 'subscribe' %}" method="POST">{% csrf_token %}
{{ form }}
<button class="btn btn-main btn-lg" type="submit">Подписаться!</button>
</form>
{% if success %}
<div class="subscribe-result">
{{ success }}
</div>
{% endif %}
urls.py:
url(r'^$', 'interior_app.views.home', name='home'),
url(r'^subscribe/$', 'interior_app.views.subscribe', name='subscribe')
models.py:
class Subscriber(models.Model):
email = models.EmailField('', max_length=100, null=True, blank=True)
forms.py:
class SubscriberForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ['email']
admin.py:
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email',)
admin.site.register(Subscriber, SubscriberAdmin)
views.py:
def home(request):
portfolios = PortfolioObject.objects.all()
photos = []
for portfolio in portfolios:
for obj in portfolio.photo_set.all():
photos.append(obj)
form = SubscriberForm()
context = {"photos": photos[::2], "form": form}
return render(request, "home.html", context)
def subscribe(request):
print request
success = ''
if request.method == "POST":
print request.POST
form = SubscriberForm(request.POST)
print form
if form.is_valid():
form.save()
success = "Ваш Email успешно отправлен"
form = SubscriberForm()
else:
form = SubscriberForm()
context = {"photos": photos[::2], "form": form, "success": success}
return render(request, "home.html", context)
I input email in the form, push button and nothing is happening.
Any data in admin, any {{ success }}.
I need not AJAX.. I would like to do this feature only with Django

Django form is not valid without showing any errors

The form, that is described below, is not valid. And expression {{ search_id_form.errors }} doesn't show anything.
Django template:
<form method="POST">
{% csrf_token %}
{{ search_id_form.idtype.label_tag }}
{{ search_id_form.idtype }}
{{ search_id_form.index.label_tag }}
{{ search_id_form.index }}<br>
<input type="submit" name="id_search_button" value="Submit">
</form>
Python class:
class IDSearchForm(forms.Form):
idtype = forms.ChoiceField(
choices=[('idx', 'Our Database ID'), ('uprot', 'UniProt'), ('ncbi', 'NCBI')],
initial='idx',
widget=forms.RadioSelect,
label="Which identifier to use:"
)
index = forms.CharField(label="Identifier:")
View:
def search(request):
if request.method == 'POST':
# handling other forms ...
# find a toxin by id
if 'id_search_button' in request.POST:
search_id_form = IDSearchForm()
if search_id_form.is_valid():
idtype = search_id_form.cleaned_data['idtype']
index = search_id_form.cleaned_data['index']
return render(request, 'ctxdb/result_ctx.html', {
# here I try to use predefined object to pass to renderer (for debugging)
'ctx': get_object_or_404(CTX, idx='21')
})
# handling other forms ...
# other forms
search_id_form = IDSearchForm()
# other forms
return render(request, 'ctxdb/search.html', {
# other forms
'search_id_form': search_id_form,
# other forms
})
In the view function I handle four different forms on single page. Other forms work correctly. What is the problem here?
When calling .is_valid, you need to pass the data to search_id_form which you are not doing.
Change
search_id_form = IDSearchForm()
to
search_id_form = IDSearchForm(request.POST)

Categories