Hi my problem is the next, I'm trying to do a Forms with filter raw sql but I can't solved this problem
'RawQuerySet' object has no attribute 'all'
Forms.py
class pruebaForm (forms.Form):
userid = forms.ModelChoiceField(queryset = users.objects.raw('SELECT userid FROM groupsmembers WHERE groupid=User.groupid'))
softlimit = forms.IntegerField()
hardlimit = forms.IntegerField()
printerid = forms.ChoiceField()
class Meta:
model = userpquota
Views.py
#login_required
def asignarcuota_lista (request):
f = userpquotaFilter(request.GET, queryset=userpquota.objects.all())
if request.method == "POST":
form = pruebaForm(request.POST)
if form.is_valid():
asignarcuota = form.save(commit=False)
asignarcuota.save()
messages.success(request,'Se ha asignadoº correctamente')
return redirect('asignarcuota_lista',)
else:
form = pruebaForm()
return render (request, 'pykota/asignarcuota_lista.html', {'filter': f, 'form': form})
Related
I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)
I am trying to create a 'Label'. Basically, you click on 'label' button, and it will show title and content under. I am using POST method. But when I click on 'submit', it gave me this error:
IntegrityError at /project/1/issue/2/label/
NOT NULL constraint failed: issue_tracker_label.project_id
Btw, I am using crispy form and I did do makemigrations and migrate after I modified my model.py. Not sure why I still get this error.
view.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
model.py
class Label(models.Model):
issue = models.ForeignKey(Issue, related_name='issue_label', on_delete=models.CASCADE)
project = models.ForeignKey(Project, related_name='project_label', on_delete=models.CASCADE)
title=models.CharField(max_length=20,default='Debug')
color=models.CharField(max_length=20,default='red')
def __str__(self):
return self.title
form.py
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('title','color',)
Try adding the project in your object save:
views.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.project = project
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
Notice the label.project = project
I have 2 models that it must be input to database in same time by submit button in my template.
this is my first model
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID=models.CharField(max_length=5,blank=True,null=True)
SiswaNIS = models.IntegerField(null=True, blank=True)
second model
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.CharField(max_length=10,blank=True,null=True)
and this is my view.py
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
if request.method == 'POST':
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return redirect('index')
else:
form = datasiswa()
form2 = riwayatsekolah()
return render(request, 'siswa/tambah_siswa.html', {'form': form, 'form2': form2})
how to insert SiswaID fromDataPribadiSiswa to SiswaID_FK in RiwayatSekolah at same time where all form is blank?
You can use ForeignKey field.
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.ForeignKey(DataPribadiSiswa)
Now in view you can try to save Siswa instance first and then to add it into Sekolah instance:
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
if request.method == 'POST':
if form.is_valid() and form2.is_valid():
siiswa_instance = form.save()
Sekolah_instance = form2.save(commit=False)
Sekolah_instance.SiswaID_FK = siiswa_instance
Sekolah_instance.save()
hallo i want to create data with checkbox field but data cannot save in database when i use widget RadioSelect
this is forms.py
class VehicleAttribute(forms.ModelForm):
OPERATION = [('production','Production Vehicle'),('supporting','Supporting Vehicle')]
PAYLOAD_METER = [('yes','Yes'),('no','No')]
NUMBER_STRUT = [('0','0'),('3','3'),('4','4')]
operation = forms.ChoiceField(widget=forms.RadioSelect, choices = OPERATION)
payload_meter = forms.ChoiceField(widget=forms.RadioSelect, choices = PAYLOAD_METER)
number_of_strut_pressure = forms.ChoiceField(widget=forms.RadioSelect, choices = NUMBER_STRUT)
class Meta:
model = Vehicle_attribute
fields = ['operation','payload_meter','number_of_strut_pressure']
this is views.py
def data_vehicle_add(request):
if request.method == "POST":
form = VehicleAttribute(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('data_vehicle_add.html', pk=post.pk)
else:
form = VehicleAttribute()
return render(request,'data_vehicle_add.html', {'form':form}, context_instance=RequestContext(request))
can you help me solve this problem?
I want to pass a pk from one form to another so that it can be used as the foreign key for the second form. Here are the model:
models.py
class CompanyDetails(models.Model):
name = models.CharField(max_length=100)
class CompanyDetailsForm(forms.ModelForm):
class Meta:
model = CompanyDetails
class DataRequest(models.Model):
company = models.ForeignKey(CompanyDetails, default="0")
agency_name = models.CharField(max_length=100)
class DataRequestForm(forms.ModelForm):
class Meta:
model = DataRequest
exclude = ['company']
And here is the view for the first form:
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', data.id))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
How should I set up my second view so that the form will save an object that has the foreign key for the object created by the first form in it?
I got it to work by passing the primary key of the first object through the url. It goes abc.com/form -> abc.com/form/16/datarequest. Not super ideal since by changing the number in the url the second object will use some other foreign key.
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', args=(data.id,)))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
def datarequest(request, company_id):
if request.method == 'POST':
form = DataRequestForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.company = CompanyDetails.objects.get(pk=company_id)
data.save()
return HttpResponse("Thanks")
else:
form = DataRequestForm()
return render(request, 'canareeform/datarequest.html', {'form': form})
If anyone has a better solution I'd love to hear it.