Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to get the url name from a django url path?
In my view i export the main_url_patterns from my app and i want to process this list to get two parts in a different lists: URL path URL name So in my view i do something like that: def siteurls_view(request): path_list=urls.main_urlpatterns url_list=[] for p in path_list: print(p, type(p),p[0]) Where urls.main_urlpatterns is: path('consumptions_points/send/', views.send_consumptions_points_view, name='send_consumptions_points'), path('consumptions/', views.consumptions_view, name='consumptions'), path('consumptions/new/', views.consumptions_new_view, name='consumptions_new'), path('consumptions/get_tx/', views.get_tx_consumption_view, name='get_tx_consumption'), path('consumptions/send/', views.send_consumptions_view, name='send_consumptions') So i would like to get for example all names from the path and insert them into a new list. Many thanks -
Django form is not submitted to the database
I am writing a Django website for dentists, the dentist can register patients with form easily not an issue, however when registering visits for a patient it is not saved, in the admin panel both models works just fine, on the website the visits form dose not save to database. models.py from django.db import models class Paitent(models.Model): pname = models.CharField(max_length=50) age = models.IntegerField() gender = models.CharField(max_length=50) address = models.CharField(max_length=50) telephone = models.IntegerField() mHistory = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.pname class Visit(models.Model): paitent = models.ForeignKey(Paitent,null=True ,on_delete=models.CASCADE, blank=True) toothNumber = models.CharField('involved tooth', max_length=120) cComplaint = models.CharField('chief complaint',max_length=120) sASymptoms = models.CharField('signs and symptoms',max_length=120) diagnosis = models.CharField(max_length=120) procedure = models.CharField(max_length=120) notes = models.TextField(blank=True) currentVisit = models.DateTimeField( 'time and date of current visit', null=True) nextAppointment = models.DateTimeField() def __str__(self): return self.toothNumber forms.py from django import forms from .models import Paitent from .models import Visit class PaitentForm(forms.ModelForm): class Meta: model = Paitent fields = ['pname', 'age', 'gender', 'address', 'telephone'] class VisitForm(forms.ModelForm): class Meta: model = Visit fields = ['paitent', 'toothNumber', 'cComplaint', 'sASymptoms', 'diagnosis', 'procedure', 'notes', 'currentVisit', 'nextAppointment'] views.py from django.shortcuts import render from .models import Paitent from .models import Visit from .forms import PaitentForm from .forms import VisitForm import calendar from calendar import HTMLCalendar … -
Hi, I am having an working NLP (spacy) model in jupyter. i need to add this model to django backend
Hi, My spacy model format is looks like this how can i add this model to django backend and this is my spacy model, how can i add this to django backend? -
How to create an object in Django Rest Framework that is related to other models
I have 3 models: user, barber and booking. In my createBooking view, I am having trouble to figure out how to pass the IDs of the user and the barber. Here's my code: The view: def createBooking(request): data = request.data booking = Booking.objects.create( barber_id = data['barberb_id'], customer_id = data[ 'customer_id'], timeslot = data['timeslot'], ) serializer = BookingSerializer(booking, many=False) return Response(serializer.data) The booking model: customer_id = models.ForeignKey(User, on_delete = models.CASCADE,) barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE) timeslot = models.DateTimeField('appointment') def __str__(self): return f"{self.customer_id} {self.barber_id} {self.timeslot}" With the current code, I'm getting the error Cannot assign "['customer_id']": "Booking.customer_id" must be a "User" instance. -
Django Migration issue when we are adding new column to the auth.Group table
We had a CustomUser model in our application and I am trying to add two new columns to the existing auth.Group table as below. Group.add_to_class('source', models.CharField(max_length=255, default='XXXXXXX')) Group.add_to_class('tags', TaggableManager(blank=True)) When we try to execute python manage.py makemigrations. Its throwing an error saying inconsistent of migration history. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration customuser.0001_initial is applied before its dependency auth.0013_group_source_group_tags on database 'default'. Need suggestion on the same. How do we handle migrations in such situation. We don't want to create new data base and migrate all the data everytime. -
How to fetch id with get method in django?
I have a model named WorkOut that stores all the data regarding workout sessions. LIke type of workout, reps, weights etc. There are 2 columns that I do not fill initially. I am trying to fill them with button clicks. Start time and end time. The idea is at the beginning of the set user will click a button and it will fill up the "start time" column with current time. At the end of the set they will click the other button to fill up the "end time" column. To achieve this I need to fetch the id for that specific object(row). If I have 10 sets of workout, I need to get the id for each specific row so when button is clicked only the column associated to that row is updated. It should be simple but I am struggling. This is how my attempt looks like- WorkOut.objects.get('id') I am running a for loop to display the entire model on the template. I checked by displaying all the id on my template, they are there. But the above code doesn't fetch individual id. When I know the id, I can go like this- WorkOut.objects.get(id=18) And sure enough it …