Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'
i was trying to make my first ecommerce website using django and i stuck at this error like 1 days, i already search in google but i can't find how to fix it. please help me to find the error. this is my code, if u need more just tell me i really need an answer thx i hope someone will help me cart.js : ''' var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productId = this.dataset.product`enter code here` var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser') { console.log('Not logged in') } else { updateUserOrder(productId) } }) } function updateUserOrder(productId, action) { console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then(response => response.json()) .then((data) => { console.log('data:', data); } ); } views.py : from django.shortcuts import render from django.http import JsonResponse from django.http import HttpRequest import json from .models import * def store(request): products = Product.objects.all() context = {'products': products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, … -
Django query filter with contains and empty list variable
matched = Details.objects.filter(Q(cnp=cnp) | Q(phones__contains=[phone]) | Q(emails__contains=[email])).values('id') class Details(models.Model): ... cnp = models.CharField(max_length=24, blank=True) phones = ArrayField(models.CharField(max_length=50), size=20, blank=True, default=list) emails = ArrayField(models.EmailField(), size=20, blank=True, default=list) Hello! I want to make a query and if any of the fields(cnp,phones or emails) have a match to get the result queryset. The cnp, phone and email variable will get just one value that I need to match with one or more values from the ArrayField. I made the query above using Q but the problem is that I can have empty list/string for phone or email variable and then that matches all my database. If i don't use 'contains', I can match single valued lists(from the db ArrayField) but for example if I have multiple emails in the db I need to match it with 'contains' to get a result. Is this possible only from a django query? Thanks! -
Multiple Django records for one user
I want to add multiple values for a user in Django. in that a user may have several records displayed. Records should belong to a specific user selected. Models.py looks like : class Medrecs(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=60, null=True) clinician = models.ForeignKey(Clinician, on_delete=models.PROTECT) Patient = models.ForeignKey(Patient, on_delete=models.CASCADE) meds = models.TextField() def __str__(self): return self.title models.ForeignKey doesnt work either. It displays records to all patients but I want a specific patient/user selected. OneToOne will display for specific user but only once. Views.py looks like: def my_profile(request): meds = Medrecs.objects.all() if request.user.is_authenticated: return render(request, 'MyDoc/my_profile.html', {'meds': meds}) else: return redirect('MyDoc:login_patient') And my template looks like : {% if meds %} {% for m in meds %} <div class="col-sm-6 panel-primary"> <img class="logo" style="height: 35px; width: 35px; margin-right: 15px;" src="{{ user.patient.image.url }}"> <p>St.Denvers Hospital,</p><br> <p>Healthcare is our compassion</p> <p>{{ m.title }}</p> <div class="panel panel-primary"> <div class="panel-heading active"> <h3 class="text-success">Doctor:{{ m.clinician }}</h3> <p>Name: {{ m.patient }}</p> </div> <div class="panel-body"> <p>Medication: {{ m.meds }}</p> </div> </div> </div> {% endfor %} {% endif %} This works fine but i can only add one patient record and i want multiple for the same user. At the Django database it tells me theres a record … -
Filter data /Disregard null value when filtering in Django
Does anybody know how can I filter data even the passing value is False, it so hassle to make lot of conditions I think there is a way to filter data even the value is false or empty. views.py def sample(request): if request.method=='POST': province = request.POST.get('province', False) municipality = request.POST.get('municipality', False) barangay = request.POST.get('barangay', False) status = request.POST.get('stats', False) batch= request.POST.get('Pbatch', False) it_batch= request.POST.get('Itbatch', False) filter= Person.objects.filter(province=province, municipality=municipality, barangay=barangay,status=status,batch=batch,it_batch=it_batch) return render .. so on and so on... The problem is when some data has no value or let say false it didn't recognize the data filter, is there any solution or idea how to achieve this? -
Django modelformset_factory Filter ForeignKey
Im stuck with this for days, Need help to filter this Item_formset: https://prnt.sc/vlgow4, so its only show record with Price_list.jenis = "Produk" as you can see below, the Model Item.item have a ForeignKey(Price_list), which i need to be filter based on Price_list.jenis record, whic is also have a foreignKey on Jenis_Pricelist, My models.py class Jenis_Pricelist(models.Model): jenis = models.CharField(max_length=10) def __str__(self): return self.jenis class Price_list(models.Model): nama_item = models.CharField(max_length=100, null=True) jenis = models.ForeignKey(Jenis_Pricelist, on_delete=models.PROTECT) def __str__(self): return f"{self.jenis} - {self.nama_item} - Rp{prc:,}" class Item(models.Model): item = models.ForeignKey(Price_list, on_delete=models.PROTECT, null=True) jumlah = models.IntegerField(default=1, blank=True, null=True) harga = models.DecimalField(max_digits=1000, decimal_places=2, null=True) def __str__(self): return self.item my forms.py Item_formset = modelformset_factory( Item, fields=('item', 'jumlah', 'harga'), extra=1, ) my view.py def crt_anm(request): template_name = 'pasien/profil/create_anamnesa.html' kontrol = Form_Anamnesa() item_formset = Anamnesa_Formset(instance=Price_list.objects.filter(jenis_id=3)) return render(request, template_name, { 'anamnesa': kontrol, 'item_formset': item_formset, }) -
Is it possible to have Read and Update inside the same View using Django?
I mean I have a project for inventory control. I wanted to create a single page where I could display the items and aside of the item I would have buttons like Update and Delete. When, say, Update is clicked a popup would appear (in the same page, just like when you open a website and there's that block telling you about cookies, or any promotion of the website you're surfing in). My tries so far: Javascript -> const handleUpdate = (url) => { const Http = new XMLHttpRequest(); url='localhost:8000'; Http.open("POST", url); Http.send(); Http.onreadystatechange = (e) => { console.log(Http.responseText) } } So when I click the button I would get the returned object. I know. Terrible. Quantum List -> While typing I thought: What if I created a form for every single model?! Yeah... 300+ IQ... And if I had like a thousand entries my html would be just like one of those physics book about the quantum universe. So question is: How would you go about that? And actually is there a way of doing it? -
What is the best way to serve static files like image and videos in a react django docker and nginx web app?
I was developing a web app with decoupled frontend and backend with SPA using react and the backend with django and am using docker to containeraize the servers and I don't know what is the best way to serve or to put the static files like image and video. -
My flow of code is not entering into if loop in django views.py
This is the part of code in django views.py , the flow of code is not entering into if loop and directly entering into else and creating problems. Why it is not entering into if(w == '3 Standard Deviation') , this loop ? I want to check if w or z == 3 Standard Deviation or 2 Standard Deviation then save csv file to respective static folder . @csrf_exempt def home(request): #import pdb; pdb.set_trace() global path_of_uploaded_csv if request.method == 'POST': UploadedData = UploadForm(request.POST, request.FILES) if UploadedData.is_valid(): # Dataframe try: dataframe = pd.read_csv(request.FILES['file']) except: return render(request, 'home.html', {'message': True}) No_of_Rows = dataframe.shape[0] d_frame = request.FILES['file'] # import pdb; pdb.set_trace() # File Storage on Disks fs = FileSystemStorage() fs.save(d_frame.name, d_frame) # list of columns df = dataframe.select_dtypes(exclude=["bool_", "object_"]) list_for_pop = df.columns import csv path_of_uploaded_csv = request.FILES['file'] import json json_object = {list_for_pop.get_loc( c): c for idx, c in enumerate(list_for_pop)} path_of_uploaded_csv.flush() return render(request, 'home.html', {'DataFrame': dataframe, 'item': list_for_pop, 'path': path_of_uploaded_csv, 'json_response': json_object, 'noOfRows': No_of_Rows}) elif(request.POST.get): # Dependent dropdown try: dpost_list = request.POST.getlist('dropdown1') except: return render(request, 'home.html', {'warning1': True}) print(dpost_list) # Independent Dropdown try: ipost_list = request.POST.getlist('dropdown2') except: return render(request, 'home.html', {'warning2': True}) w = request.POST.getlist('3std') z = request.POST.getlist('2std') #import pdb; pdb.set_trace() df_path = request.POST.get('path') … -
why django wizard form values disappear when I step back?
It's been days I am trying to split up a simple django form with some charfield and dropdowns to sub forms using django-formtools. I the first step I left 2 dropdowns field and in the second step, 2 char fields and one image file. Once I change dropdowns and go to the second form and vice versa, this is what happens: dropdown values will be kept till I submit the whole form and then will be reset. In the second step, what ever I add, whether char values or image file will be disapear after stepping back to the previews page. I tried to add get_form() and get_context_data() methods. But does not work: here is the code: class NewWizard(NamedUrlSessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) def done(self, form_list, **kwargs): ..... def get_form(self, step=None, data=None, files=None): if self.steps.current == 'step_first': step_files = self.storage.get_step_files(self.steps.current) print('step_filesA:', step_files) # return None else: step_files = self.storage.current_step_files print('step_filesB:', step_files) # return None if step_files and files: for key, value in step_files.items(): if files in key and files[key] is not None: step_files[key] = files[key] elif files: step_files = files return super(NewWizard, self).get_form(step=self.steps.current, data=data, files=step_files) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.step1 == '1': data_step = self.get_cleaned_data_for_step(int(self.steps.step1)+1) … -
To generate a table from a nested list in Django template
I have a nested list as such: dataList = [['Route To Path/file1.txt', 'Route To Path/file2.txt', 'Route To Path/file3.txt', 'Route To Path/file4.txt'], [['Routing', 'Error'], ['Routing', 'Error'], ['Routing', 'Error'], ['Routing', 'Error']], [[['file1.txt', 'Mapping error']], [['file2.txt', 'Mapping error']], [['file3.txt', 'Mapping error']], [['file4.txt', 'Mapping error']]]] My intention is to generate a table like below: Route To Path/file1.txt Routing Error file1.txt Mapping error Route To Path/file2.txt Routing Error file2.txt Mapping error etc... However with my code below, the table I get is: Route To Path/file1.txt Route To Path/file2.txt Routing Error Routing Error file1.txt Mapping error file2.txt Mapping error Can somebody point me where is my error on below code? <table id="myTable"> <thead> </thead> <tbody> {% for k in dataList %} <tr> {% if forloop.counter0 == 0 %} {% for i in k %} <tr> <td> {{ i }} </td> </tr> {% endfor %} {% elif forloop.counter0 == 1 %} {% for i in k %} <tr> <td> {{ i.0 }} </td> <td> {{ i.1 }} </td> </tr> {% endfor %} {% elif forloop.counter0 == 2 %} {% for i in k %} {% for j in i %} <tr> <td> {{ j.0 }} </td> <td> {{ j.1 }} </td> </tr> {% endfor %} {% endfor … -
Angular->Php->Python or Angular->Django, Python in PHP
I have a graduation project. I made the frontend development with Angular. There is also a machine learning system I built using Python. I have to combine these two. So I planned to write a Web API for Angular using Django. But I haven't used Django before. And I approached the deadline. I have created a Web API with PHP before and I am more experienced in PHP. I wonder what pros-cons would be if I developed this project as Angular->Php->Python? Should I learn Django quickly or do it with Php? A second question is, if I am going to do it with Php, what should I do for Python and Php communication? Should I do it by running Python scripts through Php? Or should I write the result returned from Python to the file and get it from the file in Php? Or something else? -
django admin groups and queryset
I'm searching for a way to customize the Django Administration to support permissions and data based on the user group. For example, I've just created the Developers1, Developers2 groups.. now I've also created the Transaction model, with AdminModel to specify how to list data. Transacton model: class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True) property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) *group = models.ForeignKey(Group, on_delete=models.CASCADE) im not sure about the *group field, should i delete it , or should i create Charfield, which is not a foreignkey to the django.contrib.auth.group model? and this is the admin transaction: @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) # for s in qs: if request.user.is_superuser: return qs return qs.filter(group_name__in=Group) search_fields = ['chp_reference','familymember__name'] inlines = [FamilyGroupInline,FamilyMemberInline] what im trying to do is i want each group to only access its own Transaction model, and each group can add, delete, update and view their own Transactions only(eg developers1 group cant access developers2 Transactions and vice versa) any thoughts should be appreciated thanks! -
I want to get result of two query data using ORM in django
I want to get result of two query data using ORM in django but only one data is being displayed. How may i resolve this? My codes: views.py def home(request): codes, descrp = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages p, major m WHERE p.major_cd = m.major_cd;') context = { "codes": codes, "descrp": descrp } return render(request, "website/index.html" , context ) index.html <select class="form-control select2"> <option>Select Major Head</option> {% for cd, ds in codes, descrp %} <option> {{ cd, ds }} </option> {% endfor %} </select> -
how to dynamicly change db password in django settings
I have a case when my db requires new token generated dynamicly as a password every 15 minutes. But it is advice from django team not to modify settings at runtime. And I found out that this is really not so easy to accomplish. I already tried this approche: Django multiple and dynamic databases but it seems more complex then it could be ... -
Django Gqueries: Get Grandchildren as CHUNKS of Children
Given a mother how can I get her grandchildren as chunks of her children? Here are my models: class Mother(models.Model): name = models.CharField(max_length=7) class Child(models.Model): mother = models.ForeignKey(Mother, on_delete=models.CASCADE) name = models.CharField(max_length=5) class GrandChild(models.Model): mother = models.ForeignKey(Child, on_delete=models.CASCADE) name = models.CharField(max_length=6) # I am in desperate need of below: her_grandchildren_from_each_of_her_daughters_and_sons = { "Daughter A": [ {"Granddaughter A": "Name A"}, {"Grandson B": "Name B"} ], "Son C": [ {"Granddaughter C": "Name C"}, {"Grandson D": "Name D"} ] } -
I am not able to active django in vs code. i get the following error message:
& : File C:\Users\AFFAN QADRI\env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & "c:/Users/AFFAN QADRI/env/Scripts/Activate.ps1" + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess -
Show or hide field in form based on selection in admin panel in Django
I have a model in my django app as below: class Question(BaseMmodel): title = models.CharField(max_length=50) body = models.TextField() subject = models.Charfield(max_length=20) history_date = models.DateField("history_date") #other fields I have registered this model in admin.py. Now what I would like to do is to have a toggle option in the question page in admin panel. I want to name it like Show history date field in question page. Here if I select this option then in the question form in frontend the history_date should be displayed or else it should not be displayed. How can I implement the required functionality? -
How to render the vue template into the django views?
Firstly I am creating the question and answer type app which the user creates questions. If the user added the same question which is present in the django API then I need to through an error on the template. So this app I used vuejs and django, DRF and webpack. Now I want to compare the questions present in the DB and user ready to push question content. #1. If this is not correct process How can I compare in the vuejs script. #2. How can we render the vuejs template into the django views return render('request' , QuestionEditor.vue') Is it the correct way to render the template of vue into the django? from django.contrib import messages from .models import Question def content(request): if request.method == 'POST': content = request.POST.get('content') if Question.objects.filter(content=content).exists(): messages.warning(request, 'Question already exists') return redirect('ask') # ask is nothing but name in the vuejs router file else: question = Question(content=content) question.save() messages.success(request, 'Question has been added') return redirect('/') return render(request, '../views/QuestionEditor.vue') -
how to close the collapse automatically when i press on other collapse button - html
hello i want to hide collapse by auto when i press on other button and show button data I'm using this format , my problem is data keep show when i press on other button ... i want show just the data when i press on some button and hide other collapse my html code : <div class="d-flex justify-content-center"> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#phone_pics" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone pics </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#space" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone space </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#review" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> review </button>&nbsp; </div> </div> <!-- this for phone pics --> <div id="phone_pics" class="collapse" aria-expanded="true"> <br> <div class="d-flex justify-content-center"> <div class="img"> {% for img in mobile_posts.mobile_images_set.all %} <div class="d-flex justify-content-center"> <img src="{{img.get_image}}" class="img-responsive img-thumbnail" width="50%" height="80%"> </div> {% endfor %} </div> </div> </div> <!-- this for review --> <div id="review" class="collapse" aria-expanded="true"> <br> <iframe width="100%" height="400px" src="{{mobile_posts.mobile_review_video}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe> </div> <!-- this for space --> <div id="space" class="collapse show" aria-labelledby="headingOne" > <br> </div> -
Learning Django [closed]
I know it seems ambitious but I am interested in building a few internet startups. I am competent in a few languages, including python and am intending to use django for building these websites/apps. Was hoping someone could recommend a good guide that would start fairly simple and by the end have me at a level where it could work with and build some pretty complex web apps. I am a fan of free youtube content so this would be best. Appreciate all the help. -
Send response and get request after every execution of statement in the views.py function - Django
Is there any way to send response to html template when the statement executes in the function everytime ? def name(request): tts = _TTS() tts.speak("May I know your first name ?") #send response to index.html after this speak() execution. tts.speak("May I know your last name ?") #send again response to index.html after this speak() execution. return render(request, 'index.html') I want to notify the client side everytime when the speak() execute. what would be the best way to deal with it ? -
how to access foreign key in a model class into django templates
I want to access all foreign key fields of my Answer class in the template. models.py class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True) subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def questions(request): context = { "questions": Question.objects.all(), "answers": Answer.objects.all(), "departments": Department.objects.all(), "semesters": Semester.objects.all(), "teachers": Teacher.objects.all(), "subjects": Subject.objects.all(), "rating_choices": RATING_CHOICES, } return render(request, "evaluation/questions.html", context) in the template, I want to access teacher, question, and subject through Answer class to build a form for submission. like this: This is my template that I think is problematic. <div class="container" style="margin-top: 5%;"> <br> <form action="{% url 'evaluation:index' %}" method="post"> {% csrf_token %} <select name="semester" id="semester_id"> {% for semester in semesters %} <option value="{{ semester }}">{{ semester }}</option> {% endfor %} </select> <select name="teacher" id="teacher_names"> {% for teacher in answers %} <option value="">{{ teacher.get_teacher_name }}</option> {% endfor %} </select> <select name="department" id="department_name"> {% for department in departments %} <option value="{{ department }}">{{ department }}</option> {% endfor %} </select> <select name="subject" id="subject_name"> {% for subject in subjects %} <option value="{{ subject }}">{{ subject }}</option> {% endfor %} </select> <ol> <br> {% for question in questions %} <li> {{ question }} {% for choice in rating_choices %} <ul> … -
Database Unique Constraint With At Least 1 Element in a List
I am using django-multilingualfield which transforms a given Charfield into multiple similar named CharFields dynamically depending on the languages set in the settings. For example, if on the model field "description" is of MultiLingualCharField type, it does not create actually a field with name "description" but many like "description_en", "description_de", "description_es" etc. As the exact field to be used is dependent on the user's choice on the application, for some instances description_en, for others description_de, or desciption_es will be filled while the non-used ones will be None. My question is how can I implement a UniqueConstraint stating "whichever description_xxx is not None", the combination of that and some other field (say date) is unique. Of course, it is possible to define seperate UniqueConstraints for each possible lang choice, but it will be heavily repetitive and not elegant, especially for apps with 10+ language choices. -
How to validate dateField in django form
I am trying to validate my Date of birth field in my Django form. I want the d_o_b field to be less than the current year. def validate_dob(value): # fxn that check if date of birth is not the current year if value > datetime.date.year(): raise forms.ValidationError('Date must be greater than current year') I get the below error when the try to execute the above code: TypeError at /account/edit/ 'getset_descriptor' object is not callable Here is my form: class ProfileEditForm(forms.ModelForm): dob = forms.DateField(validators = [validate_dob]) class Meta: model = Profile fields = ('dob', 'photo') labels = { 'dob': ('Date of birth'), } widgets = { 'dob': DateInput(attrs={'type': 'date'}) } -
How to use external oracle database on docker container?
I have django web and external oracle database, it is running on docker. How can i store data from django web to external oracle database? this is setting.py DATABASES = { 'oracle_database': { 'ENGINE': 'dj_db_conn_pool.backends.oracle', 'NAME': 'xxxx', 'USER': 'xxxx', 'PASSWORD': 'xxxxx', 'HOST': 'xxx.xxx.xx.xx', 'PORT': 'xxxx' } } and this is docker-compose.yml version: '3' services: web: image: app:latest build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8105:8000" networks: - db_network depends_on: - db tty: true db: build: . environment: user: 'xxxxx' database: 'xxxx' password: 'xxx' hostname: 'xxx.xxx.xx.xx' ports: "xxxx" networks: - db_network networks: db_network: driver: bridge but got error like this: django.db.utils.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded