Filtering Forms in Django - python

I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions.
My model is this:
class Region(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class Salesman(models.Model):
region = models.ForeignKey(Region,
related_name='region',
on_delete=models.CASCADE)
name = models.CharField(max_length=40)
surname = models.CharField(max_length=40)
def __str__(self):
return self.name
class Rating(models.Model):
RATING_CHOICES = [(i, str(i)) for i in range(1,6)]
salesman = models.ForeignKey(Salesman,
related_name='salesman',
on_delete=models.CASCADE)
phone = models.CharField(max_length=15, blank=True)
rating = models.IntegerField(choices=RATING_CHOICES, blank=False)
sent_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.phone
I found modified __init__ method for my forms.py:
class RateAddForm(forms.ModelForm):
class Meta:
model = Rating
def __init__(self, region_id=None, **kwargs):
super(RateAddForm, self).__init__(**kwargs)
if region_id:
self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id)
And also my views.py is this:
def report_add(request, region_id):
if request.method == 'POST':
print(region_id)
form = RateAddForm(request.POST, region_id=region_id)
if form.is_valid():
message = "Thanks!"
form.save()
return HttpResponse(message)
else:
print("Something went wrong!")
form = RateAddForm()
else:
form = RateAddForm(request.POST)
return render(request,
'account/report.html',
{'form': form})
It still shows me all salesmen on my database, even if i choose a region. How to solve this problem that form should show only salesmen of selected region. Thanks in advance!

Try setting the self.base_fields['salesman'].queryset instead of
self.fields['salesman'].queryset (i.e "base_fields" instead of "fields").
(That's what I do when I need to filter in Admin forms)

Related

Form can't assign to function call

Flight funtion doesn't return from models in view. I changed models from null=True to nothing. Is the problem within my return code or is it something else? The thing is nothing gives an error other than views which is weird.
def add_flight(request):
if request.method == 'POST':
form = FlightForm(request.POST)
if form.is_valid():
a = Flight(departing_date=form.cleaned_data["departing_date"],
deptAirport=form.cleaned_data["deptAirport"],
arrAirport=form.cleaned_data["arrAirport"],
duration=form.cleaned_data["departing_date"],
airline=form.cleaned_data["airline"],
price=form.cleaned_data["price"],
deptCity=form.cleaned_data["deptCity"],
arrCity=form.cleaned_data["arrCity"],
deptHour=form.cleaned_data["deptHour"], ,
arrHour=form.cleaned_data["arrHour"])
a.save()
#return HttpResponse("Success!")
return HttpResponseRedirect('/flights/')
else:
form = FlightForm()
return render(request, 'add_flight.html', {'form': form})
It can't return Flight model from models which looks like this
class Flight(models.Model):
departing_date = models.CharField(max_length=10)
deptAirport = models.CharField(max_length=100)
arrAirport = models.CharField(max_length=100)
duration = models.CharField(max_length=5)
airline = models.CharField(max_length=20)
price = models.CharField(max_length=100)
deptCity = models.CharField(max_length=100)
arrCity = models.CharField(max_length=100)
deptHour = models.CharField(max_length=4)
arrHour = models.CharField(max_length=4)
def __str__(self):
return self.departing_date+" "+self.deptAirport+" "+self.arrAirport+" "+self.duration+" "\
+self.airline+" "+self.price+" "+self.deptCity+" "+self.arrCity+" "+self.deptHour+" "+self.arrHour
Any suggestions?

what am I doing wrong at the moment to validate my lesson class?

I want to validate if my lesson material belongs to a xyz user with pro right it will show the correct conent, but if not it will display become a member , but however I am getting if I change id membership to pro or vice versa it always true the statement
def get(self, request):
template = loader.get_template(self.template_name)
template_member = loader.get_template(self.template_payment)
#rendering the template in HttpResponse
lesson = Lesson.objects.first()
user_membership = UserMembership.objects.filter(user=self.request.user).first()
user_membership_type = user_membership.membership.membership_type
lesson_allowed_mem_types = lesson.allowed_memberships.all()
if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists():
return HttpResponse(template.render())
else:
return HttpResponse(template_member.render())
models
class Lesson(models.Model):
allowed_memberships = models.ManyToManyField(Membership)
class Membership(models.Model):
membership_type = models.CharField(
choices=MEMBERSHIP_CHOICES,
default='Free',
max_length=30)
def __str__(self):
return self.membership_type
class UserMembership(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.email
Aren't you just trying to see if the user has a Membership?
if UserMembership.objects.filter(
user=request.user,
membership__membership_type="PAID MEMBER",
).exists():
# user is member
return HttpResponse(template.render())
else:
# user is not a member
return HttpResponse(template_member.render())

django view create model object

my site uses a rating feature where users are able to create a request for a new category, afterwards at least 100 users have to rate on this request, if 100/100 users have rated positiv for this request, the category should get created but i don't know how i can create the category model instance after the rating has reached 100/100 Positive votes.
views.py
def category_request_up_vote (request, pk):
category_request = get_object_or_404(CategoryRequests, pk=pk)
try:
if request.method == 'GET':
if category_request.author == request.user:
messages.error(request, 'You are trying to vote a request you created by your own. Thats not possible (Transmision ignored).')
return redirect('category_request_detail', pk=category_request.pk)
if CategoryRequests_Vote.objects.filter(voter=request.user, voted=category_request).exists():
messages.error(request, 'You already Voted this request. Double votes are not allowed (Transmision ignored).')
return redirect('category_request_detail', pk=category_request.pk)
else:
if category_request.up_vote == 100:
print("So what should i do now?")
else:
category_request.up_vote = F('up_vote') + 1
category_request.save()
CategoryRequests_Vote.objects.create(voter=request.user, voted=category_request)
messages.success(request, 'You have successfully Provided an Up-Vote for this Request.')
return redirect('category_request_detail', pk=category_request.pk)
else:
messages.error(request, 'Uuups, something went wrong, please try again.')
return redirect('category_request_detail', pk=category_request.pk)
except:
messages.error(request, 'Uuups, something went wrong, please try again.')
return redirect('category_request_detail', pk=category_request.pk)
models.py
class Category(models.Model):
title = models.CharField(max_length=30, verbose_name="Title")
description = models.TextField(max_length=200, null=True, blank=False)
cover = fields.ImageField(blank=False,
null=False,
upload_to=get_file_path_static_glued,
validators=[default_image_size, file_extension_category_cover],
dependencies=[FileDependency(
processor=ImageProcessor(format='PNG', quality=99, scale={
'max_width': 700, 'max_height': 700}))])
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.post = None
self.post_sell_multiple = None
def __str__(self):
return self.title
#classmethod
def get_indexable(cls):
return cls.objects.all()
#classmethod
def configure_mapping(cls, mapping):
# mapping is an elasticsearch_dsl Mapping object
mapping.field('title', 'string')
return mapping
class CategoryRequests(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=20, verbose_name="Title")
description = models.TextField(max_length=200, null=True, blank=True)
cover = fields.ImageField(
null=True,
blank=True,
upload_to=get_file_path_user_uploads,
validators=[default_image_size, default_image_file_extension],
dependencies=[FileDependency(processor=ImageProcessor(
format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))])
published_date = models.DateField(auto_now_add=True, null=True)
status = StatusField(default='Waiting')
STATUS = Choices('Waiting', 'Rejected', 'Accepted')
up_vote = models.IntegerField(default=0)
down_vote = models.IntegerField(default=0)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
verbose_name = "Category Request"
verbose_name_plural = "Category Request(s)"
ordering = ['title']
def __str__(self):
return self.title
The CategoryRequest model has the fields that the Category model requires, such as title, description, etc.
Use simple django ORM for this, inside your if category_request.up_vote == 100:
you can write,
category=Category.objects.create(title=category_request.title,description=category_request.description) ,
add the other fields that the Category model needs
and in the next line category.save(). So now the category is created.

How would I create a form for a foreign key field that has a drop down menu with an 'add item' option in django?

I'll start with my model fields:
class Store(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Product(models.Model):
type = models.CharField(max_length=250)
def __str__(self):
return self.type
class Receipt(models.Model):
store = models.ForeignKey(Store)
date = models.DateField()
line_items = models.ManyToManyField(Product, through='ReceiptProduct')
def __str__(self):
return self.store.name + ': ' + str(self.date)
class ReceiptProduct(models.Model):
receipt = models.ForeignKey(Receipt)
product = models.ForeignKey(Product)
price = models.FloatField()
description = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.product.type
What I would like to do is create a form for the ReceiptProduct model.
class AddItemForm(ModelForm):
class Meta:
model = ReceiptProduct
fields = ['product', 'price', 'description']
Done. And the view?
def add_receipt_product(request, receipt_id):
current_receipt = Receipt.objects.get(id=receipt_id)
if request.method != 'POST':
# No data submitted; create a blank form.
form = AddItemForm(initial={'receipt': current_receipt})
else:
# POST data submitted; process data.
form = AddItemForm(data=request.POST)
if form.is_valid():
new_product = form.save(commit=False)
new_product.receipt = current_receipt
new_product.save()
return HttpResponseRedirect(reverse('purchase_log:receipt_details', args=[receipt_id]))
context = {'current_receipt': current_receipt, 'form': form}
return render(request, 'purchase_log/add_receipt_product_form.html', context)
Okay, so what I would like to do is, under the 'product' field (which is a drop down menu populated by the Product model), have an option called, maybe, 'custom product' or something, that the user can select to add an item to the Product model and will then appear in future drop down menus. Is this do-able?
Thank you all in advanced!!
Django implements this in terms of a "formset". Check out this tutorial for additional information: http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html I think the example there is fairly similar to yours.
In the Django admin interface, things are somewhat easier, and you can use an Inline.

Django simple queryset in form field

I couldn't find any solution in previous answers so i'm here asking how to register the result of a form field made by a queryset. Maybe i'm doing wrong something simple here how ever my model are:
#python_2_unicode_compatible
class Choice(models.Model):
choice_text = models.CharField(max_length=100)
def __str__(self):
return self.choice_text
#python_2_unicode_compatible
class Contatto(models.Model):
contatto_choice = models.ForeignKey(Choice, on_delete=models.PROTECT)
phone_number = models.CharField(max_length=12)
email = models.CharField(max_length=100)
text = models.CharField(max_length=250)
def __str__(self):
return self.email
class ContactForm(ModelForm):
class Meta:
model = Contatto
fields = ['contatto_choice', 'phone_number','email','text']
My forms.py is:
class ContactForm(forms.Form):
contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all())
phone_number = forms.CharField(max_length=12)
email = forms.CharField(max_length=100)
text = forms.CharField(widget=forms.Textarea, max_length=500)
and my views is:
def contatti(request):
if request.method=="POST":
form = ContactForm(request.POST)
if form.is_valid():
contatto = Contatto()
contatto.phone_number = form.cleaned_data['phone_number']
contatto.email = form.cleaned_data['email']
contatto.text = form.cleaned_data['text']
contatto.contatto_choice = form.cleaned_data['contatto_choice']
contatto.save()
recipients = ['cercaservizi#gmail.com']
send_mail("Contatto Cercaservizi", contatto.phone_number+' '+contatto.email+' '+contatto.text,contatto.email, recipients)
return HttpResponseRedirect('/')
else:
form = ContactForm()
return render(request, 'form.html', {'form': form})
The view of the submitted form complains about the fact that a contatto_choice should be an instance of a choice i cannot find any tutorial about how to solve this. If you could help it would be appreciated.
Edit Your ContactForm
class ContactForm(ModelForm):
contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all())
class Meta:
model = Contatto
fields = ['contatto_choice', 'phone_number','email','text']
and you will not need other form

Categories

Resources