Form can't assign to function call - python

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?

Related

Filtering Forms in Django

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)

How do I fail the booking if the booked boolean field is set to True in django?

I am having trouble making if/else work in my django app, I want to check if a listing is booked, booked is a boolean field and the listing is a foreign key to the Booking class where the user selects a listing to book. Now I just want to know how that foreign key can be checked if the listing is booked so it fails to book and gives an error.
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
If you want to use booked field in Listing model, you can do this (you can also render Listing objects with booked=False):
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
# here you can do something like
if new_ticket.listing.booked:
messages.error(request, 'Booked Already')
return redirect('profile')
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.listing.booked = True
self.listing.save()
super().save(*args, **kwargs)

Django Product Total

I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products.
I prepare models & views.
Models:
class Kategori(models.Model):
adi = models.CharField(max_length=10, verbose_name="Kategori")
def __str__(self):
return self.adi
class Birim(models.Model):
birim = models.CharField(max_length=2, verbose_name="Birim")
def __str__(self):
return self.birim
class Urunler(models.Model):
adi = models.CharField(max_length=50, verbose_name="Ürün Adı")
kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True)
etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True)
tarih = models.DateField(default=datetime.now(), editable=False)
birim = models.ForeignKey(Birim, verbose_name="Birim")
kategori = models.ForeignKey(Kategori, verbose_name="Kategori")
aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.adi
class StokCikis(models.Model):
urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün")
tarih = models.DateTimeField(default=datetime.now())
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan")
tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden")
def __str__(self):
return self.urun.adi
class StokGiris(models.Model):
urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün")
tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True)
irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True)
tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y"))
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.urun.adi
Views.py
def kategori(request):
kategori = Kategori.objects.all()
return render_to_response('stok_kategoriler.html', locals())
def kategoriEkle(request):
kategoriId = request.GET.get('id')
if kategoriId:
ktgr = Kategori.objects.get(pk=kategoriId)
form = KategoriForm(instance=ktgr)
else:
form = KategoriForm
if request.method == 'POST':
if kategoriId:
form = KategoriForm(request.POST, instance=ktgr)
else:
form = KategoriForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/kategoriler')
button = "Ekle"
baslik = "Kategoriler"
return render(request, 'stok_kategori_ekle.html', locals())
def kategoriSil(request):
kategoriId = request.GET.get('id')
kategori = Kategori.objects.get(pk=kategoriId)
kategori.delete()
return HttpResponseRedirect('/stok/kategoriler')
def stokBirimler(request):
birimler = Birim.objects.all()
return render_to_response('stok_birimler.html',locals())
def stokBirimEkle(request):
birimId = request.GET.get('id')
if birimId:
stok_birim = Birim.objects.get(pk=birimId)
form = BirimForm(instance=stok_birim)
else:
form = BirimForm()
if request.method == 'POST':
if birimId:
form = BirimForm(request.POST, instance=stok_birim)
else:
form = BirimForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/birimler/')
baslik = "Stok Birimleri"
return render(request, 'stok_birim_ekle.html', locals())
def stokBirimSil(request):
birimId = request.GET.get('id')
birim = Birim.objects.get(pk=birimId)
birim.delete()
return HttpResponseRedirect('/stok/birimler/')
def stokUrunler(request):
urunler = Urunler.objects.all()
return render_to_response('stok_urunler.html', locals())
def urunEkle(request):
urunId = request.GET.get('id')
if urunId:
stok_urun = Urunler.objects.get(pk=urunId)
form = UrunForm(instance=stok_urun)
else:
form = UrunForm()
if request.method == 'POST':
if urunId:
form = UrunForm(request.POST, instance=stok_urun)
else:
form = UrunForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/urunler/')
baslik = "Stok Ürünleri"
return render(request, 'stok_urun_ekle.html', locals())
def urunSil(request):
urunId = request.GET.get('id')
urun = Urunler.objects.get(pk=urunId)
urun.delete()
return HttpResponseRedirect('/stok/urunler/')
Located in the model StokGiris.miktari and Stok.Cikis.miktari fields need calculation. Total = StokGiris.miktari - StokCikis.miktari and I want to list the records.
If I understand your question correctly, you want to aggregate the values of miktar of both models and subtract them from each other. You can do it with Django built-in aggregation:
from django.db.models import Sum
total = StokGiris.objects.all().aggregate(Sum('miktar')) - StokCikis.objects.all().aggregate(Sum('miktar'))
As for listing the records... Not really sure what you mean again, but some ways to "list the records":
# Just a list of DB items
list_of_stokgiris = list(StokGiris.objects.all())
# Serialized list of dictionaries with the DB values
list_of_stokcikis = StokCikis.objects.values() # You can add an argument to specify which fields you want to be serialized
# Serialized list of tuples with DB values
# I.e. [('Filipp',), ('Artjom',), ('Marat',)]
list_of_urunler = Urunler.objects.values_list('adi') # Same here for the argument. Multiple args are also supported.

django python slug variable in models.py

While I hit the search button..it shows the
Page not found (404)
No Category matches the given query.
My views
def search_in_category(request, slug):
# reset the search params, if present
try:
del request.session['search']
except KeyError:
pass
return search_results(request, slug)
def search_results(request, slug):
category = get_object_or_404(Category, slug=slug)
fields = list(category.field_set.all())
fields += list(Field.objects.filter(category=None))
fieldsLeft = [field.name for field in fields]
if request.method == "POST" or 'search' in request.session:
ads = category.ad_set.filter(active=True,
expires_on__gt=datetime.datetime.now())
# A request dictionary with keys defined for all
# fields in the category.
post = {}
if 'search' in request.session:
post.update(request.session['search'])
else:
post.update(request.POST)
sforms = prepare_sforms(fields, fieldsLeft, post)
isValid = True
for f in sforms:
# TODO: this assumes the form is not required
# (it's a search form after all)
if not f.is_valid() and not f.is_empty():
isValid = False
if isValid:
if request.method == 'POST':
request.session['search'] = {}
request.session['search'].update(request.POST)
return redirect('classifieds_browse_search_results', slug=slug)
for f in sforms:
ads = f.filter(ads)
if ads.count() == 0:
return render_to_response('classifieds/list.html',
{'no_results': True,
'category': category},
context_instance=RequestContext(request))
else:
context = context_sortable(request, ads)
context['category'] = category
return render_to_response('classifieds/list.html', context,
context_instance=RequestContext(request))
else:
sforms = prepare_sforms(fields, fieldsLeft)
return render_to_response('classifieds/search.html',
{'forms': sforms, 'category': category},
context_instance=RequestContext(request))
My models.py
class Category(models.Model):
site = models.ForeignKey(Site)
template_prefix = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
enable_contact_form_upload = models.BooleanField(default=False)
contact_form_upload_max_size = models.IntegerField(default=2 ** 20)
contact_form_upload_file_extensions = models.CharField(max_length=200,
default="txt,doc,odf,pdf")
images_max_count = models.IntegerField(default=0)
images_max_width = models.IntegerField(help_text=_(u'Maximum width in pixels.'),
default=1024)
images_max_height = models.IntegerField(help_text=_(u'Maximum height in pixels.'),
default=1024)
images_max_size = models.IntegerField(help_text=_(u'Maximum size in bytes.'),
default=2 ** 20)
images_allowed_formats = models.ManyToManyField(ImageFormat, blank=True)
description = models.TextField(default='')
sortby_fields = models.CharField(max_length=200,
help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
blank=True)
sort_order = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name + u' Category'
class Meta:
verbose_name_plural = u'categories'
My url
url(r'^search/(?P<slug>[-\w]+)/$', 'browse.search_in_category',
name='classifieds_browse_category_search'),
url(r'^search/results/(?P<slug>[-\w]+)/$', 'browse.search_results',
name='classifieds_browse_search_results'),
This my code, Why I am getting the 404 error? What I have to do for fix this error?
you cannot do
return search_results(request, slug)
do rather this redirect
return redirect(reverse('classifieds_browse_search_results', kwargs={'slug':slug}))
dont forget to import
from django.core.urlresolvers import reverse
from django.shortcuts import redirect

Django Forms Updating Record Issues

I am getting an error when I try to update a record in Django using a form. I get an error that a record with that number already exists. Below is my model and view. This is really driving me nuts. I though that Django would just update the record instead of trying to write a new record.
class Report(models.Model):
report_number = models.CharField(max_length=4, unique=True)
detected = models.CharField(max_length=40)
computer_name = models.CharField(max_length=40)
username = models.CharField(max_length=15)
cab_date_time = models.CharField(max_length=40)
collector = models.CharField(max_length=40)
addresses = models.TextField()
fault = models.CharField(max_length=40)
known_malware = models.TextField(default='No')
collected_files = models.TextField(default='None')
registry_keys = models.TextField()
service_number = models.CharField(max_length=15, blank=True)
notes = models.TextField(blank=True)
sample_requested = models.CharField(max_length=4, blank=True)
action = models.CharField(max_length=35, blank=True)
And View
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
form = ReportForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'reports/report.html', {'form': form})
Here is the Form defination
from django.forms import ModelForm
from reports.models import Report
class ReportForm(ModelForm):
class Meta:
model = Report
exclude = ('moderator',)
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
if request.method == 'POST':
form = ReportForm(request.POST, instance=instance)
if form.is_valid():
form.save(force_update=True)
return HttpResponseRedirect('/')
else:
form = ReportForm(instance=instance)
return render(request, 'reports/report.html', {'form': form})

Categories

Resources