Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test validate_unique raises ValidationError Django forms
I have a ModelForm called SignUpForm located in myproj.accounts.forms SignUpForm overrides Django's validate_unique so that the 'email' field is excluded from 'unique' validation as required by the model's unique=True (this is dealt with later in the view). Everything works as expected. I now want to test the code by raising a ValidationError when self.instance.validate_unique(exclude=exclude) is called. The problem I have is how to use mock to patch the instance.validate_unique so that a ValidationError is raised. ** SignUpForm's validate_unique(self) - myproj.accounts.forms** def validate_unique(self): exclude = self._get_validation_exclusions() exclude.add('email') try: self.instance.validate_unique(exclude=exclude) except forms.ValidationError as e: self._update_errors(e) This test works, but it does not raise the error on the method (validate_unique) and not the instance (self.instance.validate_unique). def test_validate_unique_raises_exception(self): with patch.object(SignUpForm, 'validate_unique') as mock_method: mock_method.side_effect = Exception(ValidationError) data = {"email": 'someone@somewhere.com', 'full_name': A User, "password": "A19A23CD", } form = SignUpForm(data) self.assertRaises(ValidationError) My question is how can I raise a ValidationError using mock when self.instance.validate_unique is called? -
How to count value in Python-Django website
I have the number of sales and the number of returns. I need to display the percentage of non-returned items in safetycoef. For example, there are 500 sales and 100 returns, it must be 80% in 'safetycoef'. Or 1000 sales and 240 returns, it means 76%. How to implement it? html: <div> {% for phone in object_list %} <div class="smartphone" > {% endif %} <p>{{ phone.title }} — reliabilty {{phone.safetycoef }}%</p> <p>Based on {{phone.sales }} sales and {{phone.returns }} returns </p> </div> {% endfor %} </div> -
Django step by step form with multiple ForeingKey fields
I can't make a step-by-step form for filling related models. If you want to suggest FormWizard, I can't figure it out. There are very few examples on the Internet and the examples are too simple. I'm trying to use a user session and save forms gradually class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") # about 30 fields accept = models.DateField(verbose_name="Принят дата", blank=True) class ProjectDetail(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name="Проект") img = models.ImageField(upload_to=("%d-%m-%Y/"), verbose_name="Обложка объекта") # about 40 fields lessor = models.CharField(max_length=255, verbose_name="Контактное лицо") lessor_phone = models.PositiveBigIntegerField(verbose_name="Телефон") Forms class AddressForm(forms.ModelForm): class Meta: model = Address fields = ["city", "street", "numb"] def __init__(self, *args, **kwargs): city = kwargs.pop("city", "") super(AddressForm, self).__init__(*args, **kwargs) self.fields["city"] = forms.ModelChoiceField(queryset=City.objects.all()) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["file", "sq", "rent_tax"] class ProjectDetailForm(forms.ModelForm): class Meta: model = ProjectDetail exclude = ['project', 'comment', 'resume', 'complite', 'created_at'] Views def step1(request): initial={'fn': request.session.get('fn', None)} print(initial) form = AddressForm(request.POST or None, initial=initial) if request.method == 'POST': if form.is_valid(): request.session['fn'] = form.cleaned_data['fn'] return HttpResponseRedirect(reverse('step2')) return … -
How to get database fields inside a form
What I need? I need to put a form on my page, where all fields from my database are shown, and you can change them and save to database. A simple editor for my database table. What I have? my HTML:enter code here <tr> <td>{{ form.name }}</td> <td>{{ form.token }}</td> <td><button class="btn btn-lg btn-success w-100">Add</button></td> </tr> my models.py from django.db import models # Create your models here. class TrafficSources(models.Model): name = models.CharField('name', max_length=250) token = models.CharField('token', max_length=250) def __str__(self): return self.name my forms.py from .models import TrafficSources from django.forms import ModelForm, TextInput class TrafficSourcesForm(ModelForm): class Meta: model = TrafficSources fields = ['name', 'token'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': {{here I need the name from database table}} }), 'token': TextInput(attrs={ 'class': 'form-control', 'placeholder': {{here I need the token from database table}} }) } This is the view.py for that page def settings(request): ts = TrafficSources.objects.all() form = TrafficSourcesForm() data = { 'form': form } url = 'url for API request' # ts_token = TrafficSources.objects.filter(name='propeller') for h in ts_token: token = h.token headers = {'Authorization': 'Bearer ' + token} res = requests.get(url, headers=headers) return render(request, 'mainpage/dashboard.html', {'ts': ts, 'js': res.text, 'hd': headers, 'form' : form}) My questions: 1) I … -
django does not reassign id number to model fields
I created a django model for applicants. i made it in such a way that the admin can delete an applicant's name from the model. But whenever an applicant's name is deleted the IDs remain the same, for exmaple if i delete an applicant with ID number 4 instead of the next applicant's number to become the new 4 it remains 5. here is my code view code: `def delete(request, id): applicant = Applicants.objects.get(id=id) applicant.delete() return HttpResponseRedirect(reverse('applicants_list')) html code: <table border="1" > {% for x in myapplicants %} <tr> <td>{{ x.id }}</td> <td>{{ x.fname }}</td> <td>{{ x.lname }}</td> <td>{{ x.p_course }}</td> <td>{{ x.total_grade }}</td> <td><button><a href="delete/{{ x.id }}" >Reject Application</a></button></td> </tr> {% endfor %} </table>` -
How to Convert to dict in django data from ajax
Need to convert this data to list of dict in django <QueryDict: {'data[0][val]': ['0.00'], 'data[0][id]': ['e82c2454-7d0f-4af2-90a8-58998e2e4780'], 'data[0][modal]': ['appointment'], 'data[1][val]': ['0.00'], 'data[1][id]': ['e82c2454-7d0f-4af2-90a8-58998e2e4780'], 'data[1][modal]': ['appointment'], 'data[2][val]': ['0.00'], 'data[2][id]': ['05b796cf-27de-42e0-b5ef-59ba5e8aeb0a'], 'data[2][modal]': ['additional_study'], 'data[3][val]': ['0.00'], 'data[3][id]': ['05b796cf-27de-42e0-b5ef-59ba5e8aeb0a'], 'data[3][modal]': ['additional_study']}> To Need to convert to [ { 'val':'', 'id':'dfsdf' }, { 'val':'', 'id':'dfsdf' } ] -
Overriding the Celery Task Class
Am trying to implement a task where the global variables are shared between two different Celery tasks. For that, I have inherited task class and used property. As per celery documentation the base class will initialize when a new task is invoked. Do we have an approach where can reuse the object in between tasks? Can we override the run() method from Task? If we override the run method. How can we register the task ? with celery using Celery 5. X ? Tried Serializing object.. Any alternate approach would be appreciated. class handler(Task): def __init__(self): self.base_obj = "" @property def global_handler(self): return self.global_thread_handler @property def base_handler(self): return self.base_obj @app.task(base=handler) def test123(): test123.base_handler = cls1() @app.task(base=handler) def test456(): test456.base_handler.method() -
Django project files handling logic (fresher question)
In my django project I want user to have an option to upload csv file, than I want to extract data from it , process them and send back processed csv file to user. I would like to know where do I need to implement the logic of file processing in modules or views? -
ImportError: cannot import name dataclass_transform
This is the error message i am getting. Havent seen this error and have no idea how to solve it. ImportError: cannot import name dataclass_transform 2023-01-18 15:07:57.908318: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory 2023-01-18 15:07:57.908340: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. Traceback (most recent call last): File "start_information_extractor.py", line 6, in <module> from queue_handler.document_queue_listner import DocumentQueueListner, QueueConfig File "/home/qburst/CVParsing/queue_handler/document_queue_listner.py", line 14, in <module> from main.billparser import MachineGeneratedBillExtractorPipeline File "/home/qburst/CVParsing/main/billparser/__init__.py", line 4, in <module> from main.billparser.models.bill_info_extractior import MachineGeneratedBillExtractorModel File "/home/qburst/CVParsing/main/billparser/models/bill_info_extractior.py", line 5, in <module> from main.billparser.models.qa_model import BillExtractorQAModel File "/home/qburst/CVParsing/main/billparser/models/qa_model.py", line 3, in <module> from haystack.nodes import TransformersReader File "/home/qburst/CVParsing/.env/lib/python3.8/site-packages/haystack/__init__.py", line 20, in <module> from haystack.schema import Document, Answer, Label, MultiLabel, Span, EvaluationResult File "/home/qburst/CVParsing/.env/lib/python3.8/site-packages/haystack/schema.py", line 24, in <module> from pydantic import BaseConfig, Field File "pydantic/__init__.py", line 2, in init pydantic.__init__ # File "pydantic/dataclasses.py", line 39, in init pydantic.dataclasses # +=========+=========================================+ ImportError: cannot import name dataclass_transform can anyone help? -
HTMX can trigger without attributes like hx-post-get-put...?
I have a form like below. if "Cancel Request" is clicked in the form, "delete__product" will be deleted. my problem here is that htmx cannot work without (I hope not) a process like hx-post-get.... is there a solution for this? ` {% csrf_token %} Are you sure you want to delete ""? Cancel Request Delete ` -
How to fetch data (1+ lac records) from mysql using django
How to fetch data (lac of records) from mysql within seconds? I am using pagination concept but its taking more time for displaying data in html, how to solve this problem. using paginantion or any library. I used orm query for fetch data from table. -
Migrate django database to existing one
So I am using Django with mysql database (most basic tables, like auth, user, admin and few custom models) but I need to migrate those tables with data to a existing PostgreSQL database. The issue is that there are tables created there already. Should I create additional models in the models.py file for those models existing in the database already so that migrations will be applied correctly? I am trying to figure what are the steps that I should take to properly switch databases in the Django app. So far what I have done is saved the data from current (mysql) database: python manage.py dumpdata > dump.json Now the next step I took was to change database in settings.py to postgres. After this I save current table schemas using inspectdb. Here is where I want to ask what should be next steps(?) Merge old and new models.py files. Apply migrations Add data from json dump file to the new database. -
about accessing li but not ul inside the li
im trying to access the text content that is "education" in the code that is written in a li element but not the text content that are written inside the ul of that li element. Basically li has uls and i just want to access li content and not ul's. <span class = "navs nav category">Category</span> <div> <ul class="dropdown-items"> <li class="">Education</li> <ul class="dropdown-items"> <li class="Education">Science</li> <ul class="dropdown-items"> <li class="Science">>Physics</li> <li class="Science">>Chemistry</li> <li class="Science">>Biology</li> </ul> </li> </ul> </li> <li class="">>Entertainment</li> <li class="">>Spiritual</li> </ul> </div> this is my html actually this come out dyanamically because of following code in template: <ul class="dropdown-items"> {% for cat in cats %} {% if not cat.children.all %} <li class="{{cat.parent.name}}">>{{cat.name}}</li> {%else%} <li class="{{cat.parent.name}}">{{cat.name}}</li> {% include "blog/category.html" with cats=cat.children.all %} </li> {% endif %} {% endfor %} </ul> -
Objects are not being displayed to the front end as soon as i use context_object_name in django
I was trying to display a list of items on the front end of a project using Django. I successfully did it and could see the objects in a list upon spinning up the server. But as soon as I used context_object_name in the views.py file, and then check the page, the objects are not appearing. Also, there is no error shown in the terminal and the docker logs too. Here's my Views.py file from django.shortcuts import render from django.views.generic import ListView from .models import Book # Create your views here. class BookListView(ListView): model = Book context_object_name = 'book_list' template_name = 'books/book_list.html' Here's the models.py file from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title Here's the book_list.html file <!--templates/books/book_list.html--> {% extends '_base.html' %} {% block title %}Books{% endblock title %} {% block content %} {% for book in book_list %} <div> <h2><a href="">{{ object.title }}</a></h2> </div> {% endfor %} {% endblock content %} -
Django Ninja API schema circular import error
I have UserSchema: # users/models.py class User(AbstractUser): ... # users/schemas.py from typing import List from tasks.schemas import TaskSchema class UserSchema(ModelSchema): tasks: List[TaskSchema] = [] class Config: model = User ... ...and TaskSchema: # tasks/models.py class Task(models.Model): ... owner = models.ForeignKey(User, related_name="tasks", on_delete=models.CASCASE) # tasks/schemas.py from users.schemas import UserSchema class TaskSchema(ModelSchema): owner: UserSchema class Config: model = Task ... But it throws: ImportError: cannot import name 'TaskSchema' from partially initialized module 'tasks.schemas' (most likely due to a circular import) (/Users/myname/codes/django/ninja-api/tasks/schemas.py) What I want to do is that I want to fetch: GET /api/todos - a list of tasks with related owners GET /api/todos/{task_id} - a task with owner GET /api/users/{user_id} - a user with a list of owned tasks Versions: python = ^3.11 django = ^4.1.5 django-ninja = ^0.20.0 Please let me know if you need more information. -
Why Popen.communicate returns the satus of another subprocess.Popen?
I have codes that starts Django server and React server at the same time. Here are the codes: back_server.py import os import subprocess def run_server(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketBack/BackServer') subprocess.Popen(['python', f'{target_dir}/manage.py', 'runserver'], universal_newlines=True) front_server.py import os import subprocess def run_server(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketPlaying/market-playing') os.chdir(target_dir) process = subprocess.Popen(['npm', 'start'], universal_newlines=True, shell=True) return process server.py import back_server import front_server def run_server_all(): back_server.run_server() front_server.run_server().communicate() run_server_all() When I check the status of the front_server using subprocess.communicate(), it also returns the output of the back_server. Doesn't subprocess.Popen create independent process? Why does front_server.run_server().communicate() returns the status of back_server too? -
Why using anchor tags directly doesn't work and what is the solution
How to work with anchor tags in django?I mean what things should i include in url to make it working .Say I have home,about and contact page.When I go to about and contact error pops up but home seems to work just fine. I tried including all of home,contact and about in the same render method but I guess it's incorrect -
Django doesn't import UserCreationForm
I try to import UserCreationForm from django.contrib.auth.forms. However I got en error like this: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What does this mean? I follow this question. However in my wsgi.py file this kind of settings were set up. What should I do? UPDATE: The same error raises when I try to run this code: from django.contrib.auth.models import User. -
Getting ChromeDriver from Selenium
I'm dockerizing my Python-Selenium application, and have this three lines in my Dockerfile: RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' RUN apt-get update -qqy --no-install-recommends && apt-get install -qqy --no-install-recommends google-chrome-stable While outside Docker it works okay, when running selenium inside Dockerized app I get this error: (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) I'm initializing my selenium function with this code, but I guess when Dockerizing it the service part may need to change? Anyone can guide? def function_scrap(data1): # op = webdriver.ChromeOptions() # op.add_argument('headless') chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_prefs = {} chrome_options.experimental_options["prefs"] = chrome_prefs chrome_prefs["profile.default_content_settings"] = {"images": 2} driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options) -
Django update database each second
I'm trying to update Django's project database each second. For now, I can deal with Javascript's function setInterval in my template html but each time I refresh the page or reload my server the values restarts at my database values. I think it could be better to deal that directly in the views.py and then call the variables in my html but got no idea how I can do an incrementation each sec in that way. here is my code using Javascript's function setInterval : #models.py class materiaux(models.Model): nom = models.CharField(max_length=100) nombre = models.IntegerField() production = models.IntegerField() class Meta: ordering = ['id'] def __str__(self): return str(self.nom) #views.py def objetUpdate(request): items = materiaux.objects.all() for item in items: if item.nom == "objet1": nombre_objet1 = item.nombre production_objet1 = item.production if item.nom == "objet2": nombre_objet2 = item.nombre production_objet2 = item.production if item.nom == "objet3": nombre_objet3 = item.nombre production_objet3 = item.production return render(request, 'materiaux.html', {'nombre_objet1': nombre_objet1, 'production_objet1':production_objet1, nombre_objet2': nombre_objet2, 'production_objet2':production_objet2, 'nombre_objet3': nombre_objet3, 'production_objet3':production_objet3}) #materiaux.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}Matériaux{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> <script> var nombreObjets1= {{ nombre_objet1 }}; var nombreObjets2= {{ nombre_objet2 }}; var nombreObjets3= {{ nombre_objet3 }}; var productionObjets1 … -
How To Make Auto Blogger using Python for django bloging website
I want to create an auto blogger for my website. I use react and Django REST to build my website. The auto blogger will copy the article with an image from another blog website and post it on my website. Example: WordPress auto blogger plugin. Click here --> wordpress auto blogger package -
Fernet cryptography.fernet djnago
I am using cryptography.fernet in my views.py and I get this error: File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\relations.py", line 190, in get_attribute return super().get_attribute(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\fields.py", line 479, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `course` on serializer `SectionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'course'. [18/Jan/2023 09:01:55] "GET /api/chapter-section-list/1/ HTTP/1.1" 500 140636 -
how to pass Two params value in one url
event_category = self.request.query_params.get('event_category').split(',') event_subcategory = self.request.query_params.get('event_subcategory') AttributeError: 'NoneType' object has no attribute 'split' i passing event_subcategory params..i get AttributeError: 'NoneType' object has no attribute 'split' -
python django landscape page generating pdf report
I am working on a django project and I have already created PDF report but I want landscape page because some data is hiding after generating PDF report: views.py: def export-pdf(request): response = HttpResponse(content_type = 'application/pdf') response['Content-Disposition'] = 'inline; attachment; fileName=ABC Reports' +\ str(datetime.datetime.now())+'.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string = render_to_string('enroll/pdf-output.html', context) html = HTML(string=html_string) result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response I have shared the image of pdf report where you can see that status column and its related data is hiding, therefore I need landscape page or an arrangement of page by hard code where I can adjust the pdf report page according to my need. -
Django+AlpineJS : fetching ForeignKey object data with x-init and x-data and iterating over it
(edit, the post formatting got messed up, ugh) I have 2 models, Band (has parameters name, genre, country) and Album (has a band ForeignKey, and other parameters - name and year), and I'm trying to serialize it with AlpineJS so that I have a page displaying a list of bands with a list of corresponding albums beside them. I can do it normally without Alpine, but for this case I need to build a filtering search (like by genre or year, but that's not the current issue) with Alpine so I just have to use it. I also know how to fetch data of objects from one model, but when it's two of them within the same x-data div I'm at loss. Perhaps is there a way of making one single function that has both all Band AND Album data? But then how would I list them beside each other if there's no id requested, I don't know. Damn I get lost at this though I understand all these object relations for the most part. The code below is what I have right now. Tried this, the inner x-for loop doesn't work, but it works fine without it, i.e. if …