Django modal autoimplement - django

Can anyone advise on how to deal with retrieving data from other models in Django? I was able to put information with the name of the company in the form, but after choosing from dropdown, I would like the tax identification number from database to be completed automatically. The problem is both the automatic completion and the binding and extraction of data.
p[1]: https://i.stack.imgur.com/V3TJ7.png
p[2]: https://i.stack.imgur.com/qZYAG.png
Model:
klient_lista = Klient.objects.all().values_list("nazwa_firmy", "nazwa_firmy")
class Faktura(models.Model):
numer = models.CharField(max_length=260, blank=False, null=False, unique=True)
klient = models.CharField(max_length=260, choices=klient_lista)
NIP = models.CharField(max_length=260)
kwota_netto = models.FloatField(blank=False, null=True)
VAT = models.FloatField(blank=False, null=True)
kwota_brutto = models.FloatField(blank=False, null=True)
views:
#login_required
def Faktury(request):
faktura = Faktura.objects.all()
faktura_Form = Faktura_Form(request.POST or None)
if faktura_Form.is_valid():
faktura_Form.save()
return redirect(Faktury)
return render(request, 'Faktury.html', {'form': Faktura_Form, 'faktura': faktura})

You don't need to store klient objects in a variable instead use foreign key to connect the two tables. I hope you refer to the "number" field by tax identification number and it is defined in klient model.
class Faktura(models.Model):
klient = models.ForeignKey(Klient,on_delete=models.CASCADE)
NIP = models.CharField(max_length=260)
kwota_netto = models.FloatField(blank=False, null=True)
VAT = models.FloatField(blank=False, null=True)
kwota_brutto = models.FloatField(blank=False, null=True)
To use client name include following in you client model
class Klient(models.Model):
...model fields
def __str__(self):
return self.name
replace name with the field which stores client name

Related

Filtering a django QuerySet by a previously ordered queryset

I am trying to order a queryset by distance from an input location. I am able to order the original queryset that contains the point fields, however when I use that queryset to filter a query on another model then it returns the queryset unordered. The code is as follows:
Models:
class EnglandSpine(models.Model):
urn = models.CharField(db_column='URN', primary_key=True, max_length=10)
schname = models.CharField(db_column='SCHNAME', max_length=150, blank=True, null=True)
postcode = models.ForeignKey(Postcodes3, to_field='pc', on_delete=models.CASCADE, db_column='POSTCODE', max_length=10, blank=True, null=True)
class Postcodes3(models.Model):
gid = models.AutoField(primary_key=True)
pc = models.CharField(max_length=10, blank=True, null=True, unique=True)
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
the_geom = gis_models.PointField(blank=True, null=True)
def __str__(self):
return self.pc
objects = GeoManager()
class Meta:
managed = True
db_table = 'postcodes3'
I am able to retrieve an ordered list of postcodes with the following view
views.py
class PCSearch(TemplateView, SingleTableView):
template_name = 'schoolData/pcs.html'
def get(self, request):
form = PostSearch()
return render(request, self.template_name, {'form':form})
def post(self, request):
form = PostSearch(request.POST)
if form.is_valid():
pcps = form.cleaned_data['Postcode']
pc = pcps.replace(' ','')
d = form.cleaned_data['Distance']
ss = form.cleaned_data['schtype']
gs = form.cleaned_data['gentype']
adms = form.cleaned_data['seltype']
pcr = Postcodes3.objects.get(pc=pc)
area = (pcr.the_geom, Distance(mi=d))
pcs = Postcodes3.objects.filter(the_geom__distance_lte=area).values('pc')
pcss = pcs.annotate(distance=GeometryDistance("the_geom", pcr.the_geom)).order_by("distance")
Finally I would pass the pcss variable through one more filter to get all the schools...
results = EnglandSpine.objects.filter(postcode__in=pcss)
But this does not return the query set in any order?
My second approach was to set the postcode field in EnglandSpine as a foreign key to Postcodes3 pc and perform Geometry Distance search, but it cant find the related object postcodes.the_geom.
Really stuck here and after countless hours I cannot find a specific example that relates to my issue.
Any help would be much appreciated.
Thanks,

Django Model inheritance: model child class creating extra rows in model parent class data-table

I am trying to apply basic model inheritance based on the Django documentation. The end goal is to access the shared id of the Exam and Date models in the get_date_info view, which is called after the get_exam_info view. Perhaps there is a better way to do this than model inheritance, but this seemed the most straight forward to me.
Here is the relevant Model code:
class Exam(models.Model):
instructor_first_name = models.CharField(max_length=30)
instructor_last_name = models.CharField(max_length=30)
department = models.CharField(max_length=30, null=True)
course_name = models.CharField(max_length=30, null=True)
course_number = models.IntegerField(null=True)
section_number = models.IntegerField(null=True)
num_students = models.IntegerField(null=True)
calculator = models.CharField(max_length=30, blank=True)
notes = models.CharField(max_length=30, blank=True)
computer_exam = models.BooleanField(default=False)
scantron = models.BooleanField(default=False)
timed = models.BooleanField(default=False)
dictionary = models.BooleanField(default=False)
comment = models.CharField(max_length=300, blank=True)
class Date(Exam):
start_date = models.DateField()
end_date = models.DateField()
late_start_date = models.DateField(blank=True, null=True)
late_end_date = models.DateField(blank=True, null=True)
Here is the relevant view code:
def get_exam_info(request):
if request.method == 'POST':
exam_form = ExamForm(request.POST)
if exam_form.is_valid():
exam_form.save()
date_form = DateForm()
return render(request, 'date_info.html', {'date_form': date_form})
else:
exam_form = ExamForm()
return render(request, 'exam_info.html', {'exam_form': exam_form})
def get_date_info(request):
exam_request = Exam.objects.all()
if request.method == 'POST':
date_instance = Date()
date_form = DateForm(request.POST, instance=date_instance)
if date_form.is_valid():
date_form.save()
current_user_id = date_instance.exam_ptr_id
print(current_user_id)
return HttpResponseRedirect('/')
else:
date_form = DateForm()
return render(request, 'date_info.html', {'date_form': date_form})
Here is the result in the database:
This is the Exam table
And this is the Date table
Some other things I tried: I created an abstract model that contains the shared id, then I made the Exam and Date classes subclasses of this abstract superclass. This gave the expected behavior in the database, but then the exam instances were not available in the views. I also tried many combinations of creating OneToOneFields to link the Exam and Date models, but none of these gave the desired behavior.
I've been trying to figure out why this happening for an embarrassingly long time. Any help would be appreciated!

How to print foreignkey Model relation?

If in My model, Moneybook have a many moneylogs.
so, I design a model
Moneybook/models.py
name = models.CharField(max_length=30, default="행복한 여행!")
owner = models.ForeignKey(
user_models.User, on_delete=models.CASCADE, related_name="owner")
companion = models.ManyToManyField(
user_models.User, related_name="companion", blank=True)
country = CountryField()
location = models.CharField(max_length=50, blank=True)
start_date = models.DateTimeField(default=NOW)
end_date = models.DateTimeField(default=NOW)
Moneylog/models.py
moneybook = models.ForeignKey(
moneybook_models.Moneybook, on_delete=models.CASCADE, related_name="moneybooks")
payer = models.ForeignKey(
user_models.User, on_delete=models.CASCADE, related_name="payer")
dutch_payer = models.ManyToManyField(
user_models.User, related_name="dutch_payer")
price = models.IntegerField()
category = models.CharField(max_length=10)
memo = models.TextField()
If i want to load all the moneylogs in the each belonging moneybook. how can i load it?
I guess...
def moneybook_detail(request, pk):
moneylogs=moneylog.filter(moneylog.moneybook.id=request.moneybook.id)
return render(request, "moneybooks/detail.html")
but error occured.
moneylogs = moneylog.filter(request.moneybook.id=request.moneybook.id)
SyntaxError: keyword can't be an expression
You can either query the Moneylog table with the following query by using the double underscore __ to filter based on referenced object fields.
moneylogs = MoneyLog.filter(moneybook__id=<<<MoneyBookID_GOES_HERE>>>)
Or by using the internal ReverseManyToOneManager in Django
just by using
moneybook = MoneyBook.objects.get(pk=<<<<MoneyBookID_GOES_HERE>>>>)
moneylogs = moneybook.moneylog_set.all() # all() to get all money logs
# You can do filter(...) on it too to filter the moneylogs too.
this will return all money logs related to the money book.
In general, you have to use double underscore __ to reference foreign key columns in filters:
def moneybook_detail(request, pk):
moneylogs=moneylog.filter(moneybook__id=request.moneybook.id)
return render(request, "moneybooks/detail.html")

Get the records by joining three table that are not in another table

I'm trying the get the records from the Student table, condition is that the student's primary key do not exist in the From table.(From is used as a relation) table.
Relation is "student from department"
Model:
class Student(models.Model):
name = models.CharField(max_length=20)
password = models.CharField(max_length=30)
phone_no = PhoneNumberField(null=False, blank=False, unique=True)
email = models.EmailField()
pic_location = models.FileField()
username = models.CharField(max_length=30)
class From(models.Model):
s = models.ForeignKey(Student, on_delete=models.PROTECT)
d = models.ForeignKey(Department,on_delete=models.PROTECT)
class Department(models.Model):
name = models.CharField(max_length=20)
password = models.CharField(max_length=30)
phone_no = PhoneNumberField(null=False, blank=False, unique=True)
email = models.EmailField()
I'm trying to get those records in the list view. And please review whether the way i'm retrieving session variable is good to go in such case??
class PendingStudent(ListView):
# Students pending for department approval
context_object_name = 'pending_students'
model = From
template_name = "admin_panel/department/student_detail.html"
def get_queryset(self):
department = self.request.session.get('username')
return From.objects.filter(~Q(d__name==department))
I've used session, to store what type of user is logged in (student/teacher/department).
It seems that you want to return a queryset which excludes certain values. For that I'd use .exclude() instead of filter since it's more explict.
You can check that here
def get_queryset(self):
department = self.request.session.get('username')
queryset = From.objects.exclude(d__name=department)
# In order to print the SQL query you can do this below
# print(queryset.query.__str__())
return queryset
However, if you want to return many students who are not in the From the table you could do something like:
def get_queryset(self):
return Student.objects.filter(from__d__isnull=True)
You can check that here

how can I increase the value of my article in another model view for example in django

So here, I would like the quantity existing of my Article model to increase when saving the Purchase model,
Here is my code in views.py that does not work!
I am still a beginner in Django. thank you in advance
example:
quantity of article in stock: 20
quantity purchased during a purchase: 5
so in the end in the database I would like to have 25 in the item warren in stock!
sorry for my english, i use google translator
def achat_form_view(request):
if (request.method == 'POST'):
form = AchatForm(request.POST,error_class=ParagraphErrorList)
if form.is_valid():
Article.quantite = Article.quantite + Achat.quantite_a
form.save(commit=True)
return redirect('manapoitra_achat')
else:
form = AchatForm()
return render(request, 'achatH.html', {'form': form})
models.py :
class Achat(models.Model):
id_article_a = models.ForeignKey(Article, on_delete=models.CASCADE)
id_fournisseur_a = models.ForeignKey(Fournisseur, on_delete=models.CASCADE)
quantite_a = models.PositiveIntegerField(max_length=4, verbose_name="Quantité(s)")
date_a = models.DateTimeField(auto_now_add=True, verbose_name="Date de création")
date_save_tara_a = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.pk+' achat'
class Article(models.Model):
photo = models.FileField()
nom = models.CharField(max_length=60, verbose_name="Produit")
type = models.ForeignKey(Type, verbose_name="Type", on_delete=models.CASCADE)
categorie = models.ForeignKey(Categorie, verbose_name="Catégorie", on_delete=models.CASCADE)
prix_de_vente = models.CharField(max_length=8, verbose_name="Prix de vente")
prix_d_achat = models.CharField(max_length=8, verbose_name="Prix d'achat")
quantite = models.PositiveIntegerField(max_length=4, verbose_name="Quantité(s)")
date_a = models.DateTimeField(auto_now_add=True, verbose_name="Date de création")
date_de_perim = models.DateField(blank=True, null=True, verbose_name="Perimé(e) le")
def __str__(self):
return self.nom
The problem with your code is that Achat and Article refer to the entire class, not any specific instance. What you want to do is take the Achat created by your form, and increase the quantity of the specific Article chosen in that form. You can do this via the return value of form.save(), which is an instance of Achat.
if form.is_valid():
achat = form.save()
article = achat.id_article_a
article.quantite += achat.quantite_a
article.save()
return redirect('manapoitra_achat')
(Note, your field naming convention is very strange; there's no need to suffix with _a, but more importantly you should not name ForeignKey fields with an id_ prefix; the Django ForeignKey is not an ID, but gives you access directly to the related object. So for example id_article_a should be just article.)