Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In model create days for every year created
Am new to Django (and Python) and have a problem initializing my model. For every school year created in the database, I want the corresponding days (not exactly 365/366, but > 300) to be created with a default value of 0 (a one-to-many relationship). I learned that I should not try to do this in a constructor, but after the constructor has run (and the object and its attributes have become accessible). So is this a case for using signals or should I override pre- or post-save(). And why? Or is there a third option which I have missed so far? from django.db import models import pandas as pd class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True class SchoolYear(BaseModel): start = models.DateField() end = models.DateField() def init_days(self): current_date = self.start delta = timedelta(days=1) while current_date <= self.end: self.days.add(schoolyear=self, date=current_date, value=0) current_date += delta class Day(BaseModel): schoolyear = models.ForeignKey(SchoolYear, on_delete=models.CASCADE) date = models.DateField() value = models.IntegerField() -
How to make django faster when there are large datasets?
I am making e-commerce website using django restframework. However, I realize that number of reviews are going to be larger as time goes.. (reviews have bunch of images and texts) let say 1000 reviews per items, It will make whole website slow when I go on to the product detail page or product list page.. how to prevent django getting slower when related datasets are bigger and bigger? -
Database not working running tests in Django with PostgreSQL in docker compose
I hope you are doing well! I am having a problem. I am trying to run my Django tests inside of my container with docker compose with the command line sudo docker compose run --rm app sh -c 'python3 manage.py test', but I am receiving these logs I am not pretty sure what is happening here. I am not noticing something weird in my docker-compose file either. I have tried cleaning the volumes, deleting all the images, and building again just in case I made something wrong through the process but it didn't fix my problem. I will let you know the file just in case. version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=dev - DB_USER=devuser - DB_PASS=changeme container_name: django_container depends_on: - db db: image: postgres container_name: postgresql_db restart: always volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=dev - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: -
Getting the value of a foreign key of a foreign key in Django
I have three models as follows: class ServiceCategory(models.Model): name = models.CharField(max_length=50) def natural_key(self): return self.name class Service(models.Model): service_category = models.ForeignKey(ServiceCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) def natural_key(self): return self.name class Request(models.Model): name = models.CharField(max_length=50) services = models.ManyToManyField(Service) def natural_key(self): return self.name I want to query with the default Django in a way that I can get the names of the Service Category since I will be filtering on it. Currently I have the following: data = (Request.objects.filter( services__service_category__name=service ).distinct() ) data = serialize("json", data, use_natural_foreign_keys=True) So far I only get back the names of the services, but not the service categories. I have tried values but it throws an error when I serialize. I tried to add the fields argument in serialize with services__service_category__name and it did not work as well. Can anyone help with this please ? -
Reload Variable Data from DB without restarting Django
I have a function in my Django Views.py and I use the data in another function but if a user changes True to False then I want to update it without having to restart Django. def update_list(): global processess processess = botactive.objects.filter(active=True).values_list('user') update_list() I use processess which fetches users who have a model field set to True but if they set it to False I want to not include them if there is a new request. listi = [row[0] for row in processess] def wallet_verify(listi): # print(listi) database = Bybitapidatas.objects.filter(user = listi) ... This is the request I make and want it to use fresh data without restarting Django and also in python and not using html. def verifyt(request): with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor: results = executor.map(wallet_verify, listi) return HttpResponse("done") -
How to generate many wallet addresses from a parent address using pycoin
I'm new to pycoin which is a python library for bitcoin and other alt-coins and couldn't get my head around it well yet. I'm working on a project requiring a parent wallet address with many child wallet addresses that could be used to receive coins via django. For example, Wallet A would be able to create child 1, child 2 and child 3 ..... and those children could be used to receive coins that will go straight to the parent's Wallet A Thanks a lot in advance -
How can I do to load the static folder from a CSS file?
How can I do to load the static folder from a CSS file? I tried to import using url() but it doesn't work. I want to use the static path to give a background to an element. background: url"{% static 'assets/img/check.png' %}", #458fff; } ``` -
Django complexity of one-to-one field reverse lookup
Reverse lookup takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
PyDictionary import issue
I am having issues on Mac OS installing PyDictionary into a Django project. When I pip3 install PyDictionary it says Requirement already satisfied: when I enter the command pip3 freeze it shows me PyDictionary==2.0.1 is already installed. But it can't find the module for some reason: from django.shortcuts import render from PyDictionary import PyDictionary # Create your views here. def index(request): return render(request, 'index.html') def word(request): search = request.GET.get('search') dictionary = PyDictionary() meaning = dictionary.meaning(search) synonyms = dictionary.synonym(search) antonyms = dictionary.antonym(search) context = { 'meaning': meaning, 'synonyms': synonyms, 'antonyms': antonyms } return render(request, 'word.html') I get the error: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/natelampros/PycharmProjects/english_dictionary/englishdictionary/dictionary/urls.py", line 2, in <module> from . import views File "/Users/natelampros/PycharmProjects/english_dictionary/englishdictionary/dictionary/views.py", line 2, in <module> from PyDictionary import PyDictionary ModuleNotFoundError: No module named 'PyDictionary' I've looked and can not find out why it can't find the module. I've tried installing PyDictionary on vs code and in terminal and it … -
Problem in passing parameters in a basic CRUD in Django from Views to index.html
When I try to access the button named E the following error page is loaded enter image description here views.py def editar(request,id): cliente = Cliente.objects.get(id=id) formulario = ClienteForm(request.POST or None, request.FILES or None, instance=cliente) if formulario.is_valid and request.method == 'POST': formulario.save() return redirect('clientes') return render(request, 'clientes/editar.html',{'formulario':formulario}) index.html <td> <a name="" id="" class="btn btn-info" href="{% url 'editar' cliente.id %}" role="button">E</a> </td> <td> <a name="" id="" class="btn btn-danger" href=" {% url 'eliminar' cliente.id %} " role="button">B</a> </td> urls.py > urlpatterns = [ > path('',views.inicio,name='inicio'), > path('nosotros',views.nosotros,name='nosotros'), > path('clientes',views.clientes,name='clientes'), > path('clientes/crear',views.crear,name='crear'), > path('clientes/editar',views.editar,name='editar'), > path('eliminar/<int:id>',views.eliminar,name='eliminar'), > path('clientes/editar/<int:id>',views.editar,name='editar'), > ] -
How do I filter out students to sections in django?
I am very new at Django and I've been struggling to figure out what to do. I am currently making a Learning Management System Project where in teachers can create a course and under that course there are specific students who are enrolled. The problem is I do not know how to do that. Basically this is what i want to happen: Each student has its own section and 1 section has its own courses. -
Adding forms dynamically to a Django formset
Dynamically adding forms to a formset with jQuery Hey everyone Basically, I have this Django code which I try to make Formset with jQuery. It allows user dynamically add/remove Form-set The problem is a management_form. It wan't increment prefix with TOTAL_FORMS. They still 0 at all fields that I have added. Any help is appreciated models class Product_added(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True,related_name='customer_product_added') products = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='product_added_product') service = models.CharField(max_length=200, choices=SERVICE_A, blank=True, null=True) product_add = models.CharField(max_length=200, choices=PRODUCT, blank=True, null=True) quantity = models.IntegerField(null=True, blank=True, choices=QUANTITY) forms class Product_addedForm(forms.ModelForm): class Meta: model = Product_added fields = ['service','product_add','quantity','total_price_added','notes' ] views def ProductCreateView(request, pk): customer = get_object_or_404(Customer, pk=pk) formset_addedFormset = modelformset_factory(Product_added, form=Product_addedForm) form = PersonCreationForm() formset = formset_addedFormset(queryset=Product_added.objects.none(), prefix="product_added_product") if request.method == 'POST': form = PersonCreationForm(request.POST or None) formset = formset_addedFormset(request.POST or None, queryset=Product_added.objects.none(), prefix="product_added_product") if form.is_valid() and formset.is_valid(): new_form = form.save(commit=False) new_form.customer=customer new_form.save() try: for form in formset: new_formset = form.save(commit=False) new_formset.products = product new_formset.save() except: pass messages.success(request, 'good') return redirect('product_list') else: messages.warning(request,'not good') return redirect('product_create',pk) context = {'customer':customer, 'formset':formset, 'form':form } return render(request, 'product_create.html',context) html template {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <form method="POST"> {% csrf_token %} <h3>Add … -
Getting the error "TemplateDoesNotExist at / index.html" when runnig a django project
I tried few of the solutions I found with no success. Here is the urls.py file (the settings.py was too long for posting this question): urls.py from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from django.conf.urls import include admin.site.site_header = 'Marked By Covid Admin' urlpatterns = [ path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html'), name='index'), ] Please tell me which part of the settings.py is needed to solve the issue, and I'll add it. I'd be grateful for your suggestions regarding what's wrong. Thanks! -
can't use django admin list_filter on reverse related date field
I have 2 models involved. class Purchase(): ...... class PremiumBill(): purchase = models.ForeignKey paid_at = models.DateTimeField in my admin.py in the PurchaseAdmin list_filter = ("premiumbill__paid_at",) it gives me this error Filtering by premiumbill__paid_at__gte not allowed -
How to link two projects in VS code (integrate two projects)
I have a project in VS code locally running. I want to link my project to another project (cloning from git hub). I mean I want to place a link which should go to the second project after clicking. I cloned second project in the folder of the first project. I am confused now, and I don't know what should I do or from which file I should start to link them. -
Manage tow Signals in two different apps in Django
i have two Django applications, blogApp and accounts, when i created a signal file for blogapp that can slugify title after saving the model into database, this works perfectly. But when i added the second signal file to accounts that can create profile to the user when he finished his registration, it shows me this error: , and when i check the admin section, i can see the profile has been successfully created. PostModel in blogApp application: Signals in blogApp application: ProfileModel in accoounts application: Signals in accounts application: So, how can i create the user profile without indexing to Post signals. Because what i'm thinking is the two signals of two apps is activating after the user press register. My link to GitHub project: GitHub project -
How would I implement a system where a specific user signs up to a specific event (Django)?
I want to create and app for signing up to events however I have come up to a hurdle. I have created this system in which a user gets added to an event when they trigger a view however when doing this the user signs up to all events, instead of just one. How would I do it so the user signs up to the event they are choosing? models.py: from django.db import models from django.contrib.auth.models import User class UserA(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def __str__(self): return self.user.username class systemTitle(models.Model): title = models.CharField('Title', max_length=300) time = models.DateTimeField('Time') place = models.CharField('Place', max_length=500) description = models.TextField('Description') people = models.IntegerField('Free Spaces', default=50) users = models.ManyToManyField(UserA, blank="True") class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.title return self.place views.py: from django.shortcuts import render from .models import systemTitle from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from email.message import EmailMessage import smtplib @login_required def index(request): latest_activities = systemTitle.objects.order_by('-time')[:5] context = {'latest_activities': latest_activities} return render(request, 'systema/index.html', context) def details(request, systemTitle_id): try: systemT = systemTitle.objects.get(pk=systemTitle_id) except systemTitle.DoesNotExist: print('error') return render(request, 'systema/details.html', { 'systemT' : systemT }) def success(request, systemTitle_id): user = request.user user_email = user.email systemT = systemTitle.objects.get(id=systemTitle_id) systemT.people -= 1 systemT.users.create(user=user) systemT.save() … -
What does NOT NULL constraint failed: generalpage_userregister.user_id mean and how is the issue resolved in my case?
I'm trying to create a website using Django but have an issue I've been struggling with for a few hours. Can someone explain why I recieve: NOT NULL constraint failed: generalpage_userregister.user_id error and how to resolve this issue? I suspect it has something to do with the pk but I can't get my head around this. I'm trying to create a custom model and when I try to create a superuser, I get the error mentioned above. my view is: page = "create-account" form = UserRegisterForm() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): userRegister = form.save(commit=False) userRegister.user = request.user(id=pk) #user.username = user.username.lower() userRegister.save() #login(request, userRegister) return redirect("generalpage:home-page") else: form = UserRegisterForm() context = {"form": form, "page": page} return render(request, "generalpage/create_account.html", context) ``` My urls are: ``` from django.urls import path from . import views app_name = "generalpage" urlpatterns = [ path("hem/", views.home, name="home-page"), path("registrering/", views.registerprofile, name="register-page"), path("logga-in/", views.loginpage, name="login-page"), path("logga-ut", views.logoutuser, name="logoutuser"), path("skapa-annons/", views.createroom, name="createroom-page"), path("skapa-konto/<str:pk>/", views.createaccount, name="createaccount-page"), path("radera-rum/", views.deleteroom, name="deleteroom"), path("uppdatera-rum/", views.updateroom, name="updateroom"), ] ``` the models is: ``` from datetime import datetime import email from email import message from email.policy import default from enum import unique from pyexpat import model from wsgiref.validate import validator from django.db … -
Show type string on a Django webpage instead of bytes?
I am trying to get the contents of an XML file stored in an S3 bucket to show as text in the browser. However, it just displays as numbers (bytes) rather than a legible string. My code (views.py): def file_content(request): file_buffer = io.BytesIO() s3_client = boto3.client("s3", "eu-west-1") s3_client.download_fileobj("mybucket", "myfolder/exmaple.xml", file_buffer) file_content = file_buffer.getvalue() return HttpResponse(file_content) What I've tried I've tried changing this line: file_content = file_buffer.getvalue() To: file_content = file_buffer.getvalue().decode("utf-8") Or: file_content = str(file_buffer.getvalue()) But it is still displaying as bytes in the browser. The actual file content displays as a string when using print() in the console but not in the browser. I'm not sure whats going wrong? Thank you for your time. -
error datefiled input when add new record
I have next problem. I have models: Period and CompletedWork class Period(models.Model): date = models.DateField() def __repr__(self): return self.date class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type')) work_scope = models.FloatField(blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) def __repr__(self): return f'{self.period}, {self.worker}, {self.work_done}' def __str__(self): return self.__repr__() def is_active(self): if self.active: return True return False def __str__(self): return str(self.__repr__()) In the forms I make a widget for Date input: class CompletedWorkForm(forms.ModelForm): class Meta: model = CompletedWork fields = ( 'period', 'worker', 'work_done', 'work_scope', 'work_notes', ) widgets = { 'period': DatePickerInput(), } widget.py looks like this: class DatePickerInput(forms.DateInput): input_type = 'date' my view: class CreateCompletedWorkView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = CompletedWork form_class = CompletedWorkForm template_name = 'completed_work_add.html' success_url = reverse_lazy('completed_work_list') success_message = f'Record successfully added' def get_form_kwargs(self): kwargs = super(CreateCompletedWorkView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): form.instance.record_author = self.request.user return super().form_valid(form) And now I have a problem creating a new record: "Select a valid choice. That choice is not one of the available choices." Please … -
Automatically count elements in ManyToMany Django model
I'm looking for a way to count a number of "reserved" objects inside of "IPSubnetAllocation" class that I've created (if at all possible?). Effectively what I'm doing is allocating smaller IP subnets within a larger block "IPBlockAllocation" e.g: Parent Prefix: 192.168.0.0/24 Child Prefix: 192.168.0.0/31 192.168.0.2/31 Omitted... 192.168.254/31 I can assign a child prefix to an interface (any network device) and set it's reserved status to True. This means it's no longer available for reservation (this logic is outside of scope). What I would like however is to automatically increment / decrement count of "subnets_reserved" of the "IPBlockAllocation". class IPSubnetAllocation(models.Model): parent_prefix = models.ForeignKey( 'IPBlockAllocation', null=True, on_delete=models.CASCADE ) subnet = models.CharField( blank=True, null=True, unique=True, max_length=15) assigned_interface = models.ForeignKey( DeviceInterfaces, null=True, on_delete=models.CASCADE) reserved = models.BooleanField(default=False) role = models.CharField(choices=IP_BLOCK_ROLE, default='Select', max_length=10) class IPBlockAllocation(models.Model): name = models.CharField(unique=True, max_length=255) prefix = models.GenericIPAddressField( blank=True, null=True, unique=True, validators=[validate_ipv4_address]) mask = models.IntegerField(choices=SUBNET_MASK, default='Select') subnets = models.ManyToManyField(IPSubnetAllocation, blank=True) subnets_count = models.IntegerField(blank=True, null=True) subnets_reserved = models.IntegerField(default=0, blank=True, null=True) role = models.CharField(choices=IP_BLOCK_ROLE, default='Select', max_length=10) -
uwsgi does not show 2xx and 3xx responses in the log
For testing purposes I need to see all the requests that come to my uwsgi application (and Django behind it), but I only see 4xx and 5xx, here is my uwsgi.ini config: [uwsgi] http-socket = :8080 ;chdir = /code/ module = app.wsgi:application master = true processes = 2 #logto = ./uwsgi.log logdate = %%d/%%m/%%Y %%H:%%M:%%S vacuum = true buffer-size = 65535 stats = 0.0.0.0:1717 stats-http = true max-requests = 5000 memory-report = true ;touch-reload = /code/config/touch_for_uwsgi_reload pidfile = /tmp/project-master.pid enable-threads = true single-interpreter = true log-format = [%(ctime)] [%(proto) %(status)] %(method) %(host)%(uri) => %(rsize) bytes in %(msecs) msecs, referer - "%(referer)", user agent - "%(uagent)" disable-logging = true ; Disable built-in logging log-4xx = true ; but log 4xx's anyway log-5xx = true ; and 5xx's log-3xx = true log-2xx = true ignore-sigpipe = true ignore-write-errors = true disable-write-exception = true ;chown-socket=www-data:www-data -
How to fetch the list of Estimate records using SuiteScript in Netsuite
I am unable to fetch the List of Estimate records using SuiteScript in Netsuite. I have used the same script for the CUSTOMER records and it is working fine but when I am using the same for ESTIMATE records but it is not working. Here is my SuiteScript code: define(['N/https','N/query'], function (https, query) { /** * @NApiVersion 2.1 * @NScriptType WorkflowActionScript */ const exports = {}; function onAction(context) { // Create a query definition on estimate records let myEstimateQuery = query.create({ type: query.Type.ESTIMATE }); // Create conditions for the query let firstCondition = myEstimateQuery.createCondition({ fieldId: 'Opportunity', operator: query.Operator.EMPTY_NOT }); myEstimateQuery.condition = myEstimateQuery.and(firstCondition); // Create query columns myEstimateQuery.columns = [ myEstimateQuery.createColumn({ fieldId: 'id' }), myEstimateQuery.createColumn({ fieldId: 'custbody_quote_internal_id' }), myEstimateQuery.createColumn({ fieldId: 'tranid' }), myEstimateQuery.createColumn({ fieldId: 'externalid' }), myEstimateQuery.createColumn({ fieldId: 'currency' }), myEstimateQuery.createColumn({ fieldId: 'duedate' }), myEstimateQuery.createColumn({ fieldId: 'enddate' }), myEstimateQuery.createColumn({ fieldId: 'startdate' }), myEstimateQuery.createColumn({ fieldId: 'subtotal' }), myEstimateQuery.createColumn({ fieldId: 'custbody_tran_term_in_months' }), myEstimateQuery.createColumn({ fieldId: 'custbody_end_user' }), myEstimateQuery.createColumn({ fieldId: 'custbody_qumu_deployment_type' }), myEstimateQuery.createColumn({ fieldId: 'custbody_qumu_orig_renewal' }), myEstimateQuery.createColumn({ fieldId: 'custbody_qumu_target_renewal' }) ]; // Run the query let resultSet = myEstimateQuery.run(); log.debug('resultSet>> ', resultSet); log.debug('resultSet.length>> ', resultSet.results.length); log.debug('resultSet.results>> ', resultSet.results); } exports.onAction = onAction; return exports; }); -
Reduce db queries in Django view
looks like its doing 3 queries, how can I simplify it so that it makes only 1 db query? employee = Employee.objects.get(email=self.request.user.email) filter_args = Q(internal=False) if ProjectPM.objects.filter(user=employee): filter_args = Q(projectpm=None) | Q( projectpm__user=employee, projectpm__start_date__lte=today, projectpm__end_date__gte=today, ) elif ProjectSales.objects.filter(user=employee): filter_args = Q(projectsales=None) | Q( projectsales__user=employee, projectsales__start_date__lte=today, projectsales__end_date__gte=today, ) if filter_args: qs = qs.filter(filter_args) -
HTML imported picture doesn't appear on Website
I tried to import a picture to an HTML Website, the Image is in the same folder as the template is and I made a css class to import the image. When I look on the Website I see the frame of the image but there is only a question mark in it, I am working with Django if that matters. I appreciate any help. Mac user <div> <img class="header.jpg" src="header.jpg"> </div> } .header-image { width: 100%; } .image-container { background-color: azure; padding: 16px; padding-left: 150px; padding-right: 150px; }