i want to add additional parameters to the queryset in forms
class Reserve(forms.ModelForm):
food_name = forms.ModelChoiceField(queryset=Food.objects.all())
def __init__(self, year=None, month=None, day=None, *args, **kwargs):
super(Reserve, self).__init__(*args, **kwargs)
self.year = kwargs.pop('year')
self.month = kwargs.pop('month')
self.day = kwargs.pop('day')
self.fields['food_name'].queryset = Food.objects.filter(
serve_date__year = year, serve_date__month = month, serve_date__day = day)
class Meta:
model = Reservation
fields = ('food_count', 'food_name')
but its return KeyError:
'year'
Year is an explicit keyword parameter here, it isn't in kwargs.
self.year = year
And so on for the other parameters you've listed explicitly.
Related
Can you please tell me how to transfer the calendar to the form with a get request, with clicking on the days of the week and transferring to the form? There is a filtering for all fields at the same time now, only with the date of trouble (
Approximately how such a calendar can be transmitted? Thanks in advance.
class Traveller(models.Model):
title = models.CharField(max_length=30,default='',null=False)
origin = models.ForeignKey(Origin,on_delete=models.CASCADE,max_length=100,verbose_name= 'Источник',default='')
destination = models.ForeignKey(Destination,on_delete=models.CASCADE, verbose_name="Местонахождение",default='')
transport = models.ForeignKey(Transport,on_delete=models.CASCADE, verbose_name="Транспорт",default='')
passengers = models.ForeignKey(Passengers,on_delete=models.CASCADE, verbose_name="Пассажиры",default='')
url = models.SlugField(max_length=130, unique=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Путешествие'
verbose_name_plural = 'Путешествие'
def get_absolute_url(self):
return reverse("traveller", kwargs={"url": self.url})
`views:
class FullTraveller:
def get_origin(self):
return Origin.objects.all()
def get_destination(self):
return Destination.objects.all()
def get_transport(self):
return Transport.objects.all()
def get_passengers(self):
return Passengers.objects.all()
class TravellerView(FullTraveller, ListView):
template_name = 'index.html'
model = Traveller
queryset = Traveller.objects.all()
paginate_by = 1
class FilterTravelView(FullTraveller,ListView):
def get_queryset(self):
if self.request.GET.getlist("origin") and self.request.GET.getlist("destination") and self.request.GET.getlist(
"transport") and self.request.GET.getlist("destination"):
queryset = Traveller.objects.filter(origin__in=self.request.GET.getlist("origin"),
destination__in=self.request.GET.getlist("destination"),
transport__in=self.request.GET.getlist("transport"),
passengers__in=self.request.GET.getlist("passengers"))
else:
queryset = Traveller.objects.filter(Q(origin__in=self.request.GET.getlist("origin")) | Q(
destination__in=self.request.GET.getlist("destination")) | Q(
transport__in=self.request.GET.getlist("transport"))| Q(
passengers__in=self.request.GET.getlist("passengers")))
return queryset
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["origin"] = ''.join([f"origin={x}&" for x in self.request.GET.getlist("origin")])
context["destination"] = ''.join([f"destination={x}&" for x in self.request.GET.getlist("destination")])
context["transport"] = ''.join([f"transport={x}&" for x in self.request.GET.getlist("transport")])
context["passengers"] = ''.join([f"passengers={x}&" for x in self.request.GET.getlist("passengers")])
return context
forrm in template
`
```
```
I tried various options with widgets, but it didn’t work to insert them into the template
I am developing an online Book Store.
Here is the models:
class Author(models.Model):
name = models.CharField(max_length=250, unique=True)
class Publisher(models.Model):
name = models.CharField(max_length=250, unique=True)
class Book(models.Model):
author = models.ManyToManyField(Author, related_name='authors')
publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT, blank=True, null=True)
isbn13 = models.BigIntegerField(unique=True)
name = models.CharField(max_length=500)
...
Here is the View:
class AuthorsListView(ListView):
model = Author
context_object_name = 'authors_list'
template_name = 'authors_list.html'
paginate_by = 500
class AuthorBooksListView(ListView):
model = Book
context_object_name = 'author_books'
template_name = 'author_books.html'
def get_queryset(self, **kwargs):
author_id = Author.objects.get(pk = self.kwargs['pk'])
qs = super().get_queryset(**kwargs)
return qs.filter(author = author_id)
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet
context['author'] = Author.objects.get(pk = self.kwargs['pk'])
return context
class PublishersListView(ListView):
model = Publisher
context_object_name = 'publishers_list'
template_name = 'publishers_list.html'
paginate_by = 500
class PublisherBooksListView(ListView):
model = Book
context_object_name = 'publisher_books'
template_name = 'publisher_books.html'
paginate_by = 20
def get_queryset(self, **kwargs):
publisher_id = Publisher.objects.get(pk = self.kwargs['pk'])
qs = super().get_queryset(**kwargs)
return qs.filter(publisher = publisher_id)
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet
context['publisher'] = Publisher.objects.get(pk = self.kwargs['pk'])
return context
class BooksListView(ListView):
model = Book
context_object_name = 'books_list'
template_name = 'books_list.html'
paginate_by = 100
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
Here is the urls:
path('authors/', AuthorsListView.as_view(), name = 'authors_list'),
path('author/<int:pk>/', AuthorBooksListView.as_view(), name='author_detail'),
path('publishers/', PublishersListView.as_view(), name='publishers_list'),
path('publisher/<int:pk>/', PublisherBooksListView.as_view(), name='publisher_detail'),
path('', BooksListView.as_view(), name='books_list'),
path('book/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
On the Book Detail Page I want to display:
Related books by the same author
Related books by the same publisher
How can I do this? Please help me.
I was trying to add these code to the BookDetailView:
def get_queryset(self, **kwargs):
book = Book.objects.get(pk = self.kwargs['pk'])
queryset = {
'books': Book.objects.all(),
'publisher_books': Book.objects.filter(publisher = book.publisher.id),
}
return queryset
But it gives me an error:
'dict' object has no attribute 'filter'
#djangodjarhes - Can you try the following? Ideally I modify the get_queryset if I want to change the way the queryset should be filtered other than the URL kwargs. For anything else, I override the get_context_data
def get_context_data(self, **kwargs):
context = super(BookDetailView, self).get_context_data(**kwargs)
book = Book.objects.get(pk = self.kwargs['pk'])
publisher_books = Book.objects.filter(publisher = book.publisher.id)
context["publisher_books"] = publisher_books
return context
In your case and feel free to correct me
queryset = {
'books': Book.objects.all(),
'publisher_books': Book.objects.filter(publisher = book.publisher.id),
}
This is not right. You are returning a dict when the get_queryset is supposed to return a queryset. You cannot return a dict. Either you change it to do this
queryset = Book.objects.filter(publisher = book.publisher.id)
return queryset
or use get_context_data if you want to return a dict.
I have a form like this,
class UniqueUrlForm(forms.ModelForm):
cc_number = cc_form.CardNumberField(label='Card Number')
cc_expiry = cc_form.CardExpiryField(label='Expiration Date')
cc_code = cc_form.SecurityCodeField(label='CVV/CVC')
class Meta:
model = Transactions
fields = ['customer_name', 'customer_phone', 'customer_email', 'total_amount', 'cc_number', 'cc_expiry',
'cc_code']
def __init__(self, *args, **kwargs):
super().__init__()
store_id = kwargs.get("store_id", "1")
payment_page = get_object_or_404(
PaymentPageDisplayDetails.objects.filter(store_id=store_id).values("payment_fields_visible"))
with urllib.request.urlopen(payment_page['payment_fields_visible']) as url:
display_fields = json.loads(url.read().decode())
for field_name in display_fields:
self.fields[field_name] = forms.CharField(required=False)
and a view like this,
def getpaymentpage(request, store_identifier):
uniqueurl_form = UniqueUrlForm(request.POST or None, request.FILES or None, {"store_id": 1})
if uniqueurl_form.is_valid():
trx_details = {
"amount": uniqueurl_form.cleaned_data['amount'],
"customer_email": uniqueurl_form.cleaned_data['customer_email'],
"customer_phone": uniqueurl_form.cleaned_data['customer_phone'],
"cc_number": uniqueurl_form.cleaned_data['cc_number'],
"cc_name": uniqueurl_form.cleaned_data['customer_name'],
"cc_month": uniqueurl_form.cleaned_data['cc_month'],
"cc_year": uniqueurl_form.cleaned_data['cc_year'],
"cvv": uniqueurl_form.cleaned_data['cvv'],
}
return HttpResponse(trx_details)
context = {
'form': {
uniqueurl_form,
},
"page": store_display,
}
return render(request, 'unique_url.html', context)
I have tried print(uniqueurl_form.errors) it always returns empty and uniqueurl_form.is_valid() as false.
Is it because I'm adding dynamic fields to the form.
I have referred the following,
dynamically add field to a form
What am I doing wrong here?
Thank you for your suggestions.
weirdly it started working when i made following changes,
class UniqueUrlForm(forms.ModelForm):
cc_number = cc_form.CardNumberField(label='Card Number')
cc_expiry = cc_form.CardExpiryField(label='Expiration Date')
cc_code = cc_form.SecurityCodeField(label='CVV/CVC')
class Meta:
model = Transactions
fields = ['customer_name', 'customer_phone', 'customer_email', 'total_amount', 'cc_number', 'cc_expiry',
'cc_code']
def __init__(self, *args, **kwargs):
store_id = kwargs.get("store_id", "1")
super(UniqueUrlForm, self).__init__(*args, **kwargs)
payment_page = get_object_or_404(
PaymentPageDisplayDetails.objects.filter(store_id=store_id).values("payment_fields_visible"))
with urllib.request.urlopen(payment_page['payment_fields_visible']) as url:
display_fields = json.loads(url.read().decode())
for field_name in display_fields:
self.fields[field_name] = forms.CharField()
my guess is because I did not specify class name in my .super() event though it was appending the fields it was not sure what validations to put on those fields.
I have a django form with a ModelChoiceField input and it lists the result as tuples instead of simple values.
I have no clue on how to do it.
DJANGO
class PayThis(forms.Form):
amount = forms.FloatField(required=False)
cost2 = forms.FloatField(required=False)
year = forms.ModelChoiceField(required=False,queryset=AnAgricol.objects.values_list('anul').all())
HTML
<option value="(2019,)">(2019,)</option>
I expect to get this: < option value="2019">2019< /option >
A ModelChoiceField deals, like the name suggests, with model objects. You thus can not use values_list here.
Your Form thus should define something like:
class PayThis(forms.Form):
amount = forms.FloatField(required=False)
cost2 = forms.FloatField(required=False)
year = forms.ModelChoiceField(required=False, queryset=AnAgricol.objects.all())
You can override the __str__ to return a string representation of the year, like:
AnAgricol(models.Model):
anul = models.IntegerField()
def __str__(self):
return str(self.anul)
If the year however is not something to represent AnAgricol, then you could use a ChoiceField [Django-doc], like:
class PayThis(forms.Form):
amount = forms.FloatField(required=False)
cost2 = forms.FloatField(required=False)
year = forms.ChoiceField(required=False, choices=[])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['year'].choices = [
(yr, yr) for yr
in AnAgricol.objects.values_list('anul', flat=True).distinct()
]
i want to filter serve_date field in Reserve modelform.
when run this form, return: expected string or buffer
class Reserve(forms.ModelForm):
food_name = forms.ModelChoiceField(queryset=Food.objects.all())
def __init__(self, year=None, month=None, day=None, serve_date=None, *args, **kwargs):
super(Reserve, self).__init__(*args, **kwargs)
self.year = year
self.month = month
self.day = day
self.serve_date = serve_date
date_stamp = time.strptime(year+month+day,"%Y%M%d")
serve_date = datetime.date(*date_stamp[:3])
self.fields['food_name'].queryset = Food.objects.filter(
serve_date__year = year, serve_date__month = month, serve_date__day = day)
class Meta:
model = Reservation
fields = ('food_count', 'food_name')
Food model:
class Food(models.Model):
class Meta:
verbose_name = "Food"
verbose_name_plural = "Foods"
def __unicode__(self):
return self.food_name
food_name = models.CharField(verbose_name="Food Name", max_length=50)
price = models.CharField(verbose_name="Food Price", max_length=50)
serve_date = models.DateTimeField(verbose_name="Serve Date")
Traceback
args ()
day None
kwargs {u'auto_id': u'id_%s',
u'empty_permitted': True,
u'error_class': <class 'django.forms.utils.ErrorList'>,
u'prefix': u'form-0',
u'use_required_attribute': False}
month None
self <ReservationForm bound=False, valid=Unknown, fields=(food_name;food_count)>
serve_date None
year None
you can use form_kwargs:
django Doc: Passing custom parameters to formset forms