Choices in django form - python

in my form i want to select department from 2 options: some object(every time only one) and None.
my form.py
class TeamGoalForm(ModelForm):
def __init__(self, *args, **kwargs):
employees = kwargs.pop('employees')
department = kwargs.pop('department')
super().__init__(*args, **kwargs)
self.fields['employees'].queryset = employees
self.fields['department'].choices = [(1, department), (2, None)]
self.fields['department'].initial = [1]
class Meta:
model = TeamGoal
fields = ('team_goal_title','department','employees', 'team_goal_description', 'gpd_year','team_factor_0','team_factor_1','team_factor_2','team_factor_3','team_factor_weight')
widgets = {
'team_goal_title': forms.TextInput (attrs={'class':'form-control', 'placeholder':'Enter the title of goal'}),
'department': forms.Select (attrs={'class': 'form-control', 'placeholder':'Select department'}), }
in my view.py I have had:
if request.method == 'POST':
form = TeamGoalForm(request.POST, employees=employees, department=department)
if form.is_valid():
form.save()
Here my department is an object.
How to implement something like this, 'cos my solution does't work?

You are not showing much of the code, but here is more or less how the different files should look like, hope this helps:
**#models.py**
from django.db import models
class department(models.Model):
# department fields
pass
class TeamGoal(models.Models):
...
deparment = models.ForeignKey(department, on_delete=models.CASCADE)
...
**#forms.py**
from django.forms import ModelForm
from django import forms
class TeamGoalForm(ModelForm):
class Meta:
model = TeamGoal
fields = (
'team_goal_title',
'department',
'employees',
'team_goal_description',
'gpd_year',
'team_factor_0',
'team_factor_1',
'team_factor_2',
'team_factor_3',
'team_factor_weight'
)
deparments = deparment.objects.all()
widgets = {
'deparments': forms.Select(choices=deparments,
attrs={
'class': 'form-control',
'placeholder':'Select department'
})
**#views.py**
from .forms import TeamGoalForm
def AddTeamGoalForm(request):
context = {
'TeamGoalForm': TeamGoalForm,
}
if request.method == 'POST':
addTeamGoalForm = TeamGoalForm(request.POST)
if addTeamGoalForm.is_valid():
newTeamGoalForm = addTeamGoalForm.save()
return redirect('/')
else:
return render(request, '/TeamGoalForm.html', context)
**# TeamGoalForm.html**
<form method="POST">
{% csrf_token %}
{{ TeamGoalForm}}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
NOTE: you may need to adjust it based on the code you've already writen, but hopefully this leads close to a solution.

Related

ModelFormset in Django CreateView

I'm still new to Django & I would like to know how can allow user to add more than 1 ReferrerMember on Registration form as I wanted to achieve similar to the image url below
https://imgur.com/a/2HJug5G
I applied modelformset but so far it's giving me an error where "membership_id" violates not-null constraint the moment I submitted the form.
I've searched almost everywhere to find how to implement this properly especially on class-based view instead of function based view but still no luck. If possible please help me point out on any mistakes I did or any useful resources I can refer to
models.py
class RegisterMember(models.Model):
name = models.CharField(max_length=128)
email = models.EmailField()
class ReferrerMember(models.Model):
contact_name = models.CharField(max_length=100)
company_name = models.CharField(max_length=100)
membership = models.ForeignKey(RegisterMember, on_delete=models.CASCADE)
forms.py
class RegisterMemberForm(ModelForm):
class Meta:
model = RegisterMember
fields = ['name', 'email', ]
class ReferrerForm(ModelForm):
class Meta:
model = ReferrerMember
fields = ['contact_name ', 'company_name ', ]
ReferrerMemberFormset = modelformset_factory(ReferrerMember, form=RegisterMemberForm, fields=['contact_name ', 'company_name ', ], max_num=2, validate_max=True, extra=2)
views.py
class RegisterMemberView(CreateView):
form_class = RegisterMemberForm
template_name = 'register.html'
def post(self, request, *args, **kwargs):
member_formset = ReferrerMemberFormset (request.POST, queryset=ReferrerMember.objects.none())
if member_formset .is_valid():
return self.form_valid(member_formset )
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['member_formset'] = ReferrerMember(queryset=ReferrerMember.objects.none())
return context
register.html
<form method="post">
{% csrf_token %}
{{form.as_p}}
{{member_formset.as_p}}
<input type="submit">
</form>

Not able to save data using Django form

I stack. I try many thinks. I want to put 2 forms in my mainpage. Models, forms in index.html, ModelForm, save(), urls.. I think everything ok. But submit button do nothing.
#models.py
from django.db import models
class Iletisim(models.Model):
DURUM = [
('KT', 'Keşif Talebi'),
('AB', 'Arıza Bildirimi'),
('IL', 'İletişimden'),
]
SINIF = [
('Konut', (
('SI', 'Site '),
('DA', 'Apartman Dairesi'),
('VI', 'Yazlık/Bağ/Villa'),
)
),
('İşyeri', (
('OF', 'Ofis/Büro/Dükkan'),
('FA', 'Fabrika/Şantiye/Otel/Okul'),
)
),
('DG', 'Diğer'),
]
name = models.CharField(max_length=100, verbose_name="Ad/Soyad")
phone = models.CharField(max_length=100, verbose_name="Telefon")
address = models.CharField(max_length=250, verbose_name="Adresi")
message = models.CharField(max_length=1000, verbose_name="Mesaj")
email = models.EmailField(max_length=40, verbose_name="E-Posta")
province= models.CharField(max_length=40,verbose_name="Şehir")
tarih = models.DateTimeField(default=None)
basvuru = models.CharField(max_length=2, choices=DURUM)
sinif = models.CharField(max_length=2, choices=SINIF)
class Meta:
ordering = ["tarih", "email"]
verbose_name = "Mesaj"
verbose_name_plural = "Mesajlar"
def __str__(self):
return self.basvuru
My forms folder
from django.shortcuts import redirect, render
from django.forms import ModelForm
from apps.giris.models import Iletisim
class Kesif_Form(ModelForm):
class Meta:
model = Iletisim
fields = '__all__'
def kesif_kayit(request):
if request.method=='POST':
form = Kesif_Form(request.POST)
if form.is_valid():
yeni_kesif = Iletisim()
yeni_kesif.name = request.POST.get("name")
yeni_kesif.phone = request.POST.get("phone")
yeni_kesif.address = request.POST.get("address")
yeni_kesif.message = request.POST.get("message")
yeni_kesif.email = request.POST.get("email")
yeni_kesif.province = request.POST.get("province")
yeni_kesif.tarih = request.POST.get("tarih")
yeni_kesif.basvuru = request.POST.get("basvuru")
yeni_kesif.sinif = request.POST.get("sinif")
yeni_kesif.save()
return redirect('index')
else:
form = Kesif_Form()
context={'form' : form}
return render(request,'index.html',context)
Main class
...
from forms.formlar import Kesif_Form
class Anasayfa_View(TemplateView, Kesif_Form):
template_name = 'index.html'
def get_context_data(self, **kwargs):
...
context['kform'] = Kesif_Form
...
return context
index.html
...
{{ kform.errors }}
<form action="{% url 'kesif' %}" method="POST" class="php-email-form php-email-form animate__animated animate__fadeInRight">
{{ kform.errors }}
{{ kform }}
<input type="submit" value="gir">
</form>
...
urls.py
...
from forms.formlar import kesif_kayit
urlpatterns = [
path('admin/', admin.site.urls),
path('', Anasayfa_View.as_view(), name='grsndx'),
path('kesif/', kesif_kayit, name='kesif'),
path('<str:ktgr>/', Detaylar_View.as_view(), name='dtyndx'),
path('<str:ktgr>/<str:bslk>/', Detay_View.as_view(), name='dtydty'),
]
and submit not work, every fields in form, I want 2 forms but I have not work anyone.
help..
structure
-project
-apps
-giris
-models.py
+detay
...
+env
-fls
-settings
-urls
-forms
-formlar.py
...
-templates
-index.html
...
-manage.py
...
If you are using Django model form than you have to do something like this first create form class
class Kesif_Form(ModelForm):
class Meta:
model = Iletisim
fields = '__all__'#here you to defined specific you field or all the field
than you have to submit it like this
def kesif_kayit(request):
if request.method=='POST':
form = Kesif_Form(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = Kesif_Form()
context={'form' : form}
return render(request,'index.html',context)
you don't have save it manually Django Model Form will save it for you.

Django form is valid() returns false

I am trying to do multiple file uploads in Django but am encountering some errors: form.is_valid() returning false. <br>
I have tried printing form.erorrs and it gives me the following:
<ul class="errorlist"><li>uploaded_images<ul class="errorlist"><li>“b'\xbd\x06D\xcd3\x91\x85,\xdf\xa5K\n'” is not a valid value.</li></ul></li></ul>
I am not sure how to interpret this general error. Been searching for quite some time but couldn't find an answer.
Edit:
Im also encountering a "This field is required." error
Perhaps this screenshot may help with debugging:
I must be missing something simple but I just can't find it!!
Another pair of eyes to help me sieve through would be very appreciated!
views.py
from django.shortcuts import render,redirect
from django.views.generic.edit import FormView
from .forms import BRForm
from .models import *
class BRHomeView(FormView):
form_class = BRForm
model = TargetImage
template_name = 'br/br-home.html'
context_object_name = 'bankrecon'
def get(self, request):
form = BRForm(request.POST, request.FILES)
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('uploaded_images')
print("POST")
print(request.POST)
print("FILES")
print(request.FILES)
print(form.errors)
if form.is_valid():
form.save()
return redirect('br-home')
models.py
from django.db import models
# Create your models here.
class UploadedImages(models.Model):
image_files = models.ImageField(null=True, blank=True, upload_to='images/')
class TargetImage(models.Model):
invoice_date = models.DateTimeField()
recon_date = models.DateTimeField()
uploaded_images = models.ManyToManyField(UploadedImages)
def __str__(self):
return self.invoice_date
forms.py
from django import forms
from django.core.validators import FileExtensionValidator
from .models import *
class BRForm(forms.ModelForm):
class Meta:
model = TargetImage
fields = ('invoice_date', 'recon_date', 'uploaded_images')
widgets = {
'invoice_date': forms.DateInput(attrs={'type': 'date'}),
'recon_date': forms.DateInput(attrs={'type': 'date'}),
'uploaded_images': forms.ClearableFileInput(attrs={'multiple': True, 'accept':'.jpeg, .png, .jpg'}),
}
relevant template code:
<div class="mt-5 d-flex justify-content-center">
<form action="" enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ form.as_p }}
<div class="d-flex justify-content-center">
<button class="btn btn-success mt-3" type="submit">Submit</button>
</div>
</form>
</div>
Extra info: My request.POST and request.FILES seems to be working fine:
POST
<QueryDict: {'csrfmiddlewaretoken': ['hiding this'], 'invoice_date': ['2021-02-01'], 'recon_date': ['2021-02-01']}>
FILES
<MultiValueDict: {'uploaded_images': [<InMemoryUploadedFile: first_slide (1).jpg (image/jpeg)>, <InMemoryUploadedFile: fourth_slide (1).jpg (image/jpeg)>]}>
Thank you all!!
Some errors that I see in your code:
You're trying to render a POST request in your get method.
You're not passing any data from POST request to your form instance. That's why is_valid() is returning False.
Change your code to something like this and see if it works:
...
def get(self, request):
form = BRForm()
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form = BRForm(request.POST)
if form.is_valid():
form.save()
return redirect('br-home')
I have managed to solve this issue! <br>
Link: https://stackoverflow.com/a/60961015/10732211 <br>
I overhauled the entire thing and followed the above link. Probably the models relations have some issues that does not work. <br>
views.py
class BRHomeView(FormView):
# model = TargetImage
template_name = 'br/br-home.html'
context_object_name = 'bankrecon'
def get(self, request):
form = BRFormExtended()
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form = BRFormExtended(request.POST,request.FILES)
files = request.FILES.getlist('image_files')
if form.is_valid():
print("Form Valid")
print(form.cleaned_data['invoice_date'])
print(form.cleaned_data['recon_date'])
user = request.user
invoice_date = form.cleaned_data['invoice_date']
recon_date = form.cleaned_data['recon_date']
target_image_obj = TargetImage.objects.create(user=user,invoice_date=invoice_date, recon_date=recon_date)
for file in files:
UploadedImage.objects.create(target_image=target_image_obj,image_files=file)
else:
print("Form Invalid")
return redirect('br-home')
forms.py
class BRForm(forms.ModelForm):
class Meta:
model = TargetImage
fields = ['invoice_date', 'recon_date']
widgets = {
'invoice_date': forms.DateInput(attrs={'type': 'date'}),
'recon_date': forms.DateInput(attrs={'type': 'date'}),
}
class BRFormExtended(BRForm):
image_files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta(BRForm.Meta):
fields = BRForm.Meta.fields + ['image_files',]
models.py
from django.contrib.auth.models import User
from django.utils import timezone
class TargetImage(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
uploaded_date = models.DateTimeField(default=timezone.now)
invoice_date = models.DateTimeField()
recon_date = models.DateTimeField()
def __str__(self):
return self.user.__str__()
class UploadedImage(models.Model):
target_image = models.ForeignKey(TargetImage, on_delete=models.CASCADE)
image_files = models.ImageField(null=True, blank=True, upload_to='images/')
Also, it would be helpful to have a media root folder and edits to urls.py is also required.
urls.py
from django.urls import path
from .views import BRHomeView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', BRHomeView.as_view(), name='br-home'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
Hopefully this will help someone!

IntegrityError at /collection/order/ FOREIGN KEY constraint failed error while adding a new object

Hi I was just learning django and trying to create a model form with manaytomany relationship between item and order
below is my code snippet.
models.py
class Item(models.Model):
name = models.CharField(max_length=25,default="",primary_key=True)
weight = models.FloatField()
def __str__(self):
return self.name
class Order(models.Model):
customername = models.CharField(max_length=25,default="")
item = models.ManyToManyField(Item,default="")
metal = models.ForeignKey(Material,on_delete=models.CASCADE)
price = models.IntegerField()
place = models.CharField(max_length=25)
orderdate = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.customername
forms.py:
from django import forms
from .models import Order, Material, Item
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = '__all__'
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = '__all__'
views.py:
def ItemSaveorUpdate(request):
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request,messages.SUCCESS,"Movie rating submitted succesfully")
else:
form = ItemForm()
return render(request,'addItem.html',{"form":form})
def OrderSaveorUpdate(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request,messages.SUCCESS,"Order added succesfully")
return redirect('material')
elif request.method == 'PUT':
item = Item.objects.get(pk=id)
form = OrderForm(instance=item)
form.save()
else:
#item = Item.objects.get(pk=id)
form = OrderForm()
return render(request,'addOrder.html',{"form":form})
Template additem.html:
<form action="{% url 'item' %}" request="post">
{% csrf_token %}
{{form.as_p }}
<input type="submit" value="add">
</form>
urls.py:
urlpatterns = [
path('item/', views.ItemSaveorUpdate, name="item"),
path('material/', views.MaterialSaveorUpdate, name="material"),
path('order/', views.OrderSaveorUpdate, name="order"),
I am trying to select multiple items while creating an order and after clicking add it is giving the error IntegrityError at /collection/order/
FOREIGN KEY constraint failed. Important to mention that the order is getting added which I can see in admin panel but the items are not getting selected.
Please help to avoid this issue and let me know what I missed here.
Thank you.
The issue solved by removing default for item fields in Order class in models.py
item = models.ManyToManyField(Item,default="")
after removing
item = models.ManyToManyField(Item)
Its is working fine now.
Thank you.

Django/Python: form data doesn't get stored in database

Django 1.8 / Python 3.4
I wanna add data from an html-form via a Django view named "add" to my database. However, for some reason this just doesn't happen and I can't figure out what's wrong. Presumably the mistake is in the view's code, but what exactly do I need to change?
models.py
from django.db import models
from model_utils import Choices
class Entry(models.Model):
user = models.CharField(max_length=50)
title = models.CharField(max_length=200)
description = models.TextField()
due_date = models.DateField('Date')
due_time = models.TimeField('Time')
STATUS = Choices('Open', 'Done')
status = models.CharField(choices=STATUS, default=STATUS.Open, max_length=4)
def __unicode__(self):
return u"%s %s %s %s %s" % (self.user, self.title, self.description, self.expiry, self.status)
def expiry(self):
return u"%s %s" % (self.due_date, self.due_time)
The interesting part of my add.html
<td><input type="text" name="title"></td>
<td><input type="text" name="description"></td>
<td><input type="text" name="due_date"></td>
<td><input type="text" name="due_time"></td>
<td>
<select name="status" size="1" selected value="Open">
<option>Open</option>
<option>Done</option>
</select>
</td>
forms.py
from django import forms
from django.forms.widgets import TextInput
class EntryForm(forms.Form):
title = forms.CharField(max_length=200)
description = forms.widgets.TextInput()
due_date = forms.DateField()
due_time = forms.TimeField()
status = forms.ChoiceField(choices=[(x, x) for x in range(1, 2)])
And the relevant view in my views.py
from django import forms
from django.shortcuts import render
from django.shortcuts import redirect
from website.list.forms import EntryForm
def add(request):
if request.method == "POST":
form = EntryForm(request.POST)
if form.is_valid():
new_entry = form.save()
new_entry.save()
return redirect('website')
else:
form = EntryForm()
return render(request,'add.html', {'form': form})
Any help is appreciated!
[EDIT]
So, this is what my add.html looks like now:
<form action="." method="post">
{% csrf_token %}
{{ form }}
<br><input type="submit" value="Send"/>
<br><br>Cancel
</form>
And the slightly edited views.py again:
from django import forms
from django.shortcuts import render
from django.shortcuts import redirect
from www.todolist.forms import EntryForm
from django.contrib.auth.models import User
def add(request):
if request.method == "POST":
form = EntryForm(request.POST)
if form.is_valid())
form.save()
return redirect('website')
else:
form = EntryForm()
return render(request,'add.html', {'form': form})
Figured it out ...
This is what forms.py has to look like in order for the save() function to work in the view:
class EntryForm(forms.ModelForm):
CHOICES = (
('1', 'Open'),
('2', 'Done'),
)
title = forms.CharField(max_length=200)
description = forms.CharField(widget=forms.Textarea)
due_date = forms.DateField()
due_time = forms.TimeField()
status = forms.ChoiceField(choices=CHOICES)
class Meta:
model = Entry
fields = '__all__'
The important things to notice are "ModelForm" instead of just "Form" and the class Meta information.
I am guessing you are getting an error here; form = EntryForm(request.POST) but because you are manually writing out the form html instead of using the Django form to do it, you aren't seeing the error.
https://docs.djangoproject.com/en/1.8/topics/forms/#the-template is how you should use Django to render your html for your Django form; and this by default will display any errors the happened when trying to validate your data.

Categories