Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Task overlap in Django-Q
I have a task that I want to run every minute so the data is as fresh as possible. However depending on the size of the update it can take longer than one minute to finish. Django-Q creates new task and queues it every minute though so there is some overlap synchronizing the same data pretty much. Is it possible to not schedule the task that is already in progress? -
how can i call two functions from views.py in url.py?
I would like to call two functions from views.py i.e 'Register' and 'Login'. Both functions are returning the following render: return render(request, 'dashboard.html') Now, what do I have to write in url.py for calling both functions under one URL? Basically, registration and login are not two separate HTML pages. They are pop-ups on my home page that appear when you click on the register or login button. views.py def Register(request): global fn,ln,s,em,pwd if request.method == 'POST': m=sql.connect(host="localhost",user="root",passwd="12345",database="website") cursor = m.cursor() d = request.POST for key, value in d.items(): if key == "first_name": fn = value if key == "last_name": ln = value if key == "sex": s = value if key == "email": em = value if key == "password": pwd = value c = "insert into users Values('{}','{}','{}','{}','{}')".format(fn,ln,s,em,pwd) cursor.execute(c) m.commit() return render(request, 'dashboard.html') def Login(request): global em,pwd if request.method=="POST": m=sql.connect(host="localhost",user="root",passwd="12345",database='website') cursor=m.cursor() d=request.POST for key,value in d.items(): if key=="email": em=value if key=="password": pwd=value c="select * from users where email='{}' and password='{}'".format(em,pwd) cursor.execute(c) t=tuple(cursor.fetchall()) if t==(): return render(request,'error.html') else: return render(request,"welcome.html") return render(request,'dashboard.html') -
How to write activity history in Django, when we have more than one ManyToMany fields in the model?
We are using 'actstream' library and its not updating the actual many2many field id values into history table. Always its updating as an empty list instead of list of ids. class Parent(): name = models.CharField(max_length=255) tags = TaggableManager(blank=True) def __str__(self): return self.name class Table1(): name = models.CharField(max_length=255, null=True) type = models.CharField(max_length=255, null=True) parent_id = models.ManyToManyField(ParentTable, blank=True, related_name='%(class)s_parent_id') tags = TaggableManager(blank=True) def __str__(self): return self.name 'id' is auto incremented value in Django table. Once we call a save() method, then post_save signal will execute for logging additional information in the actstream table.tags and parent_id is updating as [] instead of user sending values in the actstream_action table.we are using @receiver(post_save) annotation and executing action.send() accordingly @receiver(post_save) def capture_models_post_save(sender, instance, created, **kwargs): userInfo = get_current_user() action.send(userInfo, verb='created',description='created',action_object=instance, modification=model_to_dict(instance)) -
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
Below are my url patterns from learning logs from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('learning_logs/', include('learning_logs.urls')), ] And below is the url I'm adding """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = { # Home page path('', views.index, name='index'), # Show all topics path('topics', views.topics, name='topics'), # Detail page for a single topic path(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic', ), # Page for adding a new topic path('new_topic', views.new_topic, name='new_topic'), } Below is the error I'm getting from my browser Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ learning_logs/ new_topic [name='new_topic'] learning_logs/ ^topics/(?P<topic_id>\d+)/$ [name='topic'] learning_logs/ topics [name='topics'] learning_logs/ [name='index'] The current path, learning_logs/topics/(?P1\d+)/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My Python version environments are Python 3.10 Django 4.1.1 IDE-PyCharm -
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
When I am running the command python3 manage.py runserver its running successfully but same command is run through docker run command then its throwing this error django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? -
Django proper way to model a one-to-one relationship
I'm looking for proper way to model such statements in Django: 1. "A Condition has exactly 2 Blocks: leftBlock and rightBlock" 2. "LeftBlock and RightBlock have the same fields in common" 3. "Blocks must be different in a Condition" 4. "A Block only belongs to 1 Condition" Here my reasoning: I identified 2 models: Condition and Block. To express 1, Condition must have 2 fields named like "left_block" "right_block" To express 2, it is enough one model called Block instead of 2 that are redundant. As for 3, this may be done with DJango CheckConstraint but I'm not sure. As for 4, I believe that we have one-to-one relationship between Condition and Block. Finally, my models: class Condition(models.Model): condition_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) left_block = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='left_block') right_block = models.OneToOneField(Block, on_delete=models.CASCADE, null=True, related_name='right_block') class Block(models.Model): block_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=16) So, is this correct? If not, how can I handle such situation? -
User Creation Form Django - add RecaptchaField
I'm trying to add captcha field to Django UserCreationFrom and I can not solve it. I can not post everything what I tried because I'm trying modify this view about 2 hours. I have register form on my site made by Django UserCreationFrom - everything is ok but I decied to add Recaptcha. I have app name "accounts" and in this app I have view in which is this: from django.contrib.auth.forms import UserCreationForm, get_user_model from django.template.context_processors import request from django.urls import reverse_lazy from django.views import generic from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox class SignUpForm(UserCreationForm): class Meta: model = get_user_model() fields = ('first_name', "last_name", "username", "email", "password1", "password2") class Captcha(UserCreationForm): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) class SignUpView(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy("login") template_name = 'accounts/signup.html' Signup.html looks like this: {% extends 'main.html' %} {% block title %} Přihlášení {% endblock %} {% block content %} <h2>Registrace</h2> <div class="box"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit"> Registrovat </button> </form> </div> {% endblock %} I installed the django-recaptcha library - added it in settings. Also I have in settings my RECAPtCHA_PUBLIC and PRIVATE KEY and I'm registered in Google_recaptcha website. My URLS looks like this: from django.contrib import admin … -
Redirect user to previous page after submitting form in Django
I am trying to redirect the user to the previous page once a form is submitted. To make it clear this is what the process would look like User starts on Venue_id page and clicks on product id User is directed to Product_id page and find a form User completes form and submit on Product_id page user redirect to Venue_id page upon form submission I found a good source of inspiration on the forum, particularly on this page (How to redirect to previous page in Django after POST request) (I also found some posts using the history of the browser. But decided to stick to this method, as it seems using browser history doesn't always work) I used next as suggested in the code in the above post. But there is something I don't understand which is probably why I get this wrong. Here is the different codes in views I tried for next: next = request.POST.get('next','/') => this sends me to '/', which is not what i want. However it seemed to work for the person who posted the original question even though they were trying to NOT be redirect to '/'; next = request.POST.get('next','') => sends me to … -
Custom class for Error and Success Massages in Django Rest Framework
I wrote most of the codes and there are many return statements like this... except Comments.DoesNotExist: return Response({"response": False, "return_code": "comments_not_exist", "result": "Comment_Get_Failed", \ "message": errors["comments_DoesNotExist"]}, status=status.HTTP_400_BAD_REQUEST) ...... except Exception as error: return Response({"response": False, "return_code": "internal_code_error", "result": "Comment_Get_Failed", \ "message": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ...... I was tired that. return_response.CustomException(detail={"your": "exception", "some_other": "key", "response": "key2", \ "result": "key3",}, status_code=status.HTTP_404_NOT_FOUND) but I don't think that's good practice. Looks like it's the same as return. I want to Implement a class that should contain all input shortcuts. Is there any better way to do that? Output should be like that. { "response": True / False, "return_code": "Success / Failed", "result": "..." "message": "Successfully Failed :)" } -
How to equate the field of a model with another field in the same model?
I would like the external_id field to always inherit the temporary_id values (for experimental purposes). I just want it to be equal to the temporary_id field. How do I do this? # External parts Lookup table class External(models.Model): temporary_id = models.CharField(max_length=32, unique=True) # Unique temporary external id actual_id = models.CharField(max_length=32, unique=True, blank=True) # Unique actual external id external_id = temporary_id # Display below in admin def __str__(self): return f"{self.external_id}" -
How to populate DB from Facebook response using python-social-auth
I have Django with python-social-auth installed. My custom user model: class User(AbstractUser): """Custom User model.""" username = None email = models.EmailField(blank=False, unique=True, verbose_name=_("Email")) facebook_link = models.URLField(blank=True, verbose_name=_("Facebook profile link")) contacts = models.CharField(blank=True, max_length=250, verbose_name=_("Contacts")) hometown = models.CharField(blank=True, max_length=250, verbose_name=_("Hometown")) start_coordinates = models.CharField(blank=True, max_length=100, verbose_name=_("Start coordinates")) avatar = ProcessedImageField( upload_to="avatar/", format="JPEG", options={"quality": 80}, default="avatar/default_avatar.jpg", verbose_name=_("Image"), ) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] I do succesfull authentication with Facebook with this code: SOCIAL_AUTH_USER_MODEL = 'accounts.User' SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'home' SOCIAL_AUTH_LOGIN_URL = 'login' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link', 'user_hometown'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture.type(large), link, hometown' } SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [ ('name', 'name'), ('email', 'email'), ('picture', 'avatar'), ('link', 'facebook_link'), ('hometown', 'hometown'), ] As a result, I have a new user instance created in DB with the automatically populated fields: fist_name, last_name, email. How do I can populate the rest of fields (facebook_link, hometown) with data from response? -
How to get started building a web video conferencing site?
I started coding early this year and have done little projects here and there like a chat bot, to do list etc. I want to do a few advanced full stack projects in the span of a year that will give me a deep dive understanding. Basically, I want to build a big project and learn as I go. I don't really care how long that takes. One of these projects is a web conferencing app like google meet but specifically to conduct coding interviews. It will have all the usual web conferencing features with an added code playground. I know it is ambitious project. However, I am having a hard time figuring out what tech stack to use. I wanted to use Vue for any frontend elements (which I know are not much) but simply because I want to pick up the framework. I am mostly a python person so I was wondering if I could use django on the backend? I am okay with using express to but just prefer python. I also want to use third party frame works. I am yet to research deeply but maybe agora, webRTC or socket or something idk Any advice would … -
how to select data from an external database and put them in django's database?
hello I'm a beginner in Django/python I have a python program in root folder that fill a database created in the same folder I want to take these data and put them in my Django's database dB.sqlite3 how can I do this, please? -
How do you make a synced volume with Docker, Django and Gunicorn?
Google solutions does not help, I feel like the problem is in me using Gunicorn as local server. I just cant get my volume to sync and update with me changing local files, how do I do that? Force re-build volume ever ytime sounds like something highly inefficient Tried used Watchtower but had no luck as well compose.yml services: back: container_name: blog-django build: ./blog-master command: gunicorn blog.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 links: - db volumes: - .:/app - blog-django:/usr/src/app/ - blog-static:/usr/src/app/static env_file: ./.env depends_on: db: condition: service_healthy nginx: container_name: blog-nginx build: ./nginx/ ports: - "1337:80" volumes: - blog-static:/usr/src/app/static links: - back depends_on: - back db: container_name: blog-db image: postgres:14 restart: always expose: - "5432" environment: - POSTGRES_DB=docker - POSTGRES_USER=docker - POSTGRES_PASSWORD=docker ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ healthcheck: test: ["CMD-SHELL", "pg_isready -U docker"] interval: 5s timeout: 5s retries: 5 mailhog: container_name: mailhog image: mailhog/mailhog #logging: # driver: 'none' # disable saving logs expose: - 1025 ports: - 1025:1025 # smtp server - 8025:8025 # web ui volumes: blog-django: blog-static: pgdata: Dockerfile FROM python:3.9.6-alpine WORKDIR /usr/src/app/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev … -
Where in Django Charfield() is max_length defined as compulsory?
I have a Django app and trying to understand the logic on how to read docs correctly in order to e.g. create a Charfield object. So here is my model: from django.db import models class Person(models.Model): f_name = models.CharField() . . . . . . If I run the app I get the error: Charfields must define a 'max_length' attribute I get that I need to do: f_name = models.CharField(max_length=40) But why? when I read the code for Charfield it's not there, so I read the code for its superclass Field but I don't see where max_length is set to be compulsory! Please assist (new to oop) Thank you :) -
Using KMeans adding it to my django app python
I have a general and basic understanding of how the K-Means algorithm works. My problem revolves around connecting people with similar interests which is represented in features that will be used during clustering. Having done that before on files like a csv and txt, how would I go about adding it to my Django app to have it run every time an event occurs, like someone outside the cluster likes another's post. -
Format Django rendered date string dates into YYYY-MM-DD format
When we pass date object in django view and render in html, it outputs in below format. 'Oct. 7, 2022', 'Sept. 9, 2022', 'Aug. 12, 2022', 'July 15, 2022', 'June 17, 2022', 'May 20, 2022', 'April 22, 2022', 'March 25, 2022', 'Feb. 25, 2022', 'Jan. 28, 2022', 'Dec. 31, 2021', 'Feb. 11, 2022', 'Nov. 5, 2021' This is example of how each month looks like. I want to convert it into YYYY-MM-DD format. I am using below approach which is working version but I am looking for optimized code for the same. import re import datetime date_value = 'Sept. 9, 2022' date_value = re.split("[., ]", date_value) date_value[0] = date_value[0][:3] date_value = ' '.join(date_value) date_value = datetime.datetime.strptime(date_value, '%b %d %Y').strftime('%Y-%m-%d') print(date_value) >> 2022-09-09 Is there any other way to directly convert it into this format? This question is not about formatting django date like date_value |date:"Y-M-d" on UI. Rather I am looking to do in python backend. Thanks in advance! -
How to sign-in with LDAP using django-allauth login page
We use django-allauth for authentication. And we want to use django-auth-ldap. Currently, we can login with LDAP from the default django sign-in page (/admin). We learned that this should be done with the DefaultAccountAdapter in the django-allauth package. How can we login with LDAP information using django-allauth sign-in page? # project/settings.py: ACCOUNT_ADAPTER = 'project.users.adapter.CustomAccountAdapter' # project/users/adapter.py: from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class CustomAccountAdapter(DefaultAccountAdapter): ... -
Django: How to create a model that contains a foreign key with CreateView?
If possible, I want to make a model that includes the foreign key with class-based CreateView. I know it can be done using a function. models.py class Pizza(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return "/pizzas" class Topping(models.Model): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse("pizza", kwargs={"pizza_id": self.pizza.pk}) views.py class NewTopping(CreateView): model = Topping template_name = "pizzas/new_topping.html" form_class = ToppingForm urls.py path("topping/<pk>/create",views.NewTopping.as_view(),name="new_topping") I've tried to do it like this, but I get an integrity error when I try to save the new instance: NOT NULL constraint failed: pizzas_topping.pizza_id -
How to raise error from custom save method in django?
I have defined a custom save method. In this method i want to raise some error if one of the field is empty. def save(self, *args, **kwargs): # do some operation and end up getting self.iot_boxes # this model field (iot_boxes) can be a list full of values or an empty list logger.info(f"Selected IOT boxes to be updated {self.iot_boxes}") super().save(*args, **kwargs) Initially iot_boxes may or may not be empty or after some operation it can end up empty during operation in the save() method. How can i display some kind of error on the admin page when the self.iot_boxes comes out as empty. -
Best ways deal with large data on backend django?
I know this is a broad question that is kinda difficult to understand. But I couldn't get answers by googling. I have a large amount of data from more than 100 000 users. The data is about purchases, shipping, user invites, and so on. Overall, it is quite big and almost all models in my Django backend have foreign keys to each other. When sorting users I have to access the database for each user, which takes around 30 seconds to sort. So, instead, I am caching all user-related data in Redis(refreshing it once a day) and sorting them on request (without accessing the database, jut using what is in the cache), which reduced the time to ~1.5sec. If someone knows a better way to deal with it, can you please share it? -
Warning when installing Tailwind in Django
To have tailwind in my django project I'm trying to crete an output.css file using: npx tailwindcss -i ./static/src/input.css -o ./static/dist/output.css --watch and I'm getting these warnings: warn - The `content` option in your Tailwind CSS configuration is missing or empty. warn - Configure your content sources or your generated CSS will be missing styles. warn - https://tailwindcss.com/docs/content-configuration If I get it correct the problem seems to be my tailwind.config.js and maybe I did not set the path correctly. This is my tailwind.config.js file: module.exports = { content: [ './templates/**/*.html' ], theme: { extend: {}, }, plugins: [], } This is my django's project structure: - website -- main -- app1 -- static --- src --- dist --- node_modules --- tailwind.config.js -- templates --- assets ---- base.html --- main ---- index.html --- app1 -- website --- setting.py this is my input.css file: /* static/src/input.css */ @tailwind base; @tailwind components; @tailwind utilities; What am I doing wrong? -
django.core.exceptions.ValidationError: ['“<django.db.models.fields.DecimalField>” value must be a decimal number.']
I have a decimal field in django models, it never shown any error till today when I added new field with decimalfield, why is that issue? -
Django task to created objects in database systematically failed on the first record
I use Django (2.2.5), Docker, celery and Postgresql database. I have write a celery task that query database first, create a dataframe with results of the query and update_or_create objects in databases based on this dataframe. code simplified # load queries definition queries = dcf_queries_definitions() # this line query the database # print(queries) if not queries.empty: for index, row in queries.iterrows(): # multiple call to api of another app to look for missing data # return **df** dataframe that will be used to create objects in database records = df.to_dict(orient='records') for record in records: try: DataCorrectionForm.objects.create( dcf_ide=record['dcf_ide'], category=record['category'], crf=record['crf'], crf_ide=record['crf_ide'], patient=record['patient'], record_date=record['record_date'], field_name=record['field_name'], field_label=record['field_label'], message=record['message'], field_value=record['field_value'], dcf_status=record['dcf_status'], query_id=record['query_id'], deactivated=record['deactivated'], comments=record['comments'] ) except Exception as e: print(record) print('Exception raised when trying to update object',e) continue But I have a OperationalError that systematically raised on the first objects to be created or updated. The message in not very explicit for me. OperationalError('server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n') I controlled data I try to insert in the model and there is no problem. If I upload the same datas from a csv file to insert in my database, there is no problem. I … -
Form Wizard || adding multiple persons in one of the steps
I am using Form Wizard in Django. My form is okay the problem is adding multiple person details in the form. There is a button on the HTML to add person. If it is click there is a drop down. For now the code works for adding one person only. Is there a way that you can repeat the step in FormWizard if the user wants to add many people? Do I need to save it in session? Thank you HTML {% extends "incident_report_home.html" %} {% block form_if %}{% block form_else %} {% csrf_token %} <fieldset> {% comment %} <legend>Title</legend> {% endcomment %} <div> {% comment %} <label>{{ form.field.label }}:<p class="note">{{ form.field.help_text }}</p></label> <hr> {% endcomment %} <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapsePeople" aria-expanded="false" aria-controls="collapsePeople"> <i class='bx bx-plus'></i> Add Person </button> <div class="collapse pt-4" id="collapsePeople"> <form> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputFirstName">First Name</label> {{form.incident_first_name}} </div> <div class="form-group col-md-4"> <label for="inputMiddleName">Middle Name</label> {{form.incident_middle_name}} </div> <div class="form-group col-md-4"> <label for="inputLastName">Last Name</label> {{form.incident_last_name}} </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputAge">Age</label> {{form.incident_age}} </div> <div class="form-group col-md-4"> <label for="inputGender">Gender</label> {{form.incident_gender}} </div> </div> <div class="form-group"> <label for="inputAddress">Address</label> {{form.incident_address}} </div> <!-- ================================= --> <hr> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputInvolvement">Involvement</label> {{form.incident_involvement}} </div> <div …