Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Database Design Problem - Multiple App Single Database
I have two django applications using the same database. These applications have their own models. Since both applications use the same database, I can authorize with common users, I can use User model as foreign key for models. Let's call these two django apps A and B. Because A and B use the same database, a user can be associated with models in both applications. If a user is associated with a model in both applications, the user I deleted from application A cannot be deleted because it is associated with a model in application B. I think I made a wrong design. How can I overcome this problem? -
Sum of averages raw query
I have the following code that I have to optimize: These are the models: class Question(models.Model): label = models.CharField(max_length=255, verbose_name='Question') class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) submit_date = models.DateTimeField() int_val = models.IntegerField(null=True, blank=True, verbose_name='Int Response') class Plan(models.Model): name = models.CharField(max_length=100) questions = models.ManyToManyField(Question, through='PlanQuestion') start_date = models.DateField(null=True) completion_date = models.DateField(null=True) class PlanQuestion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) target_score = models.FloatField() target_percentage = models.FloatField() And here is the unoptimized code: plans = Plan.objects.filter(start_date__isnull=False, completion_date__isnull=False) sum_of_averages = 0 total_plans = 0 for plan in plans: plan_questions = plan.questions.through.objects.filter(plan=plan) sum_of_scores = 0 total_plan_questions = 0 for plan_question in plan_questions: cur_date = datetime.now().date() start_date = plan.completion_date end_date = start_date if start_date and (cur_date > plan.completion_date) else cur_date query = """ SELECT id, COUNT(*) AS count, AVG(int_val) AS int_average FROM Response WHERE question_id=%(question_id)s AND DATE(submit_date) >= %(stard_date)s AND DATE(submit_date) <= %(end_date)s """ score = Response.objects.raw(query,params={'question_id': plan.question.id, 'start_date': plan.plan.start_date if plan.plan.start_date else end_date, 'end_date': end_date }) sum_of_scores += score[0].int_average total_plan_questions += 1 question_avg = sum_of_scores / total_plan_questions if total_plan_questions else 0 sum_of_averages += question_avg total_plans += 1 return sum_of_averages / total_plans if total_plans else 0 As you can see in the above code for every question of the plan, a score is calculated, … -
Need help to make a query from django model
I have a CustomUser model, working fine . It stores a value in otp table everytime on save instance. but i want to send this pre saved otp value through email . email function is working good but i don't how to make query here for that specific user who wants get the otp. as every user would have a random value. here is the code. #models.py class CustomUser(AbstractUser): username = None phone_regex = RegexValidator( regex=r'^\+?1?\d{9,14}$', message="Phone number must be entered in the form of +129999999999.") phone_number = models.CharField(validators=[phone_regex], max_length=17, unique=True, verbose_name='Phone Number', blank=False) email = models.EmailField(_('email address'), unique=True) isPhoneVerified = models.BooleanField( verbose_name='Is Phone Number Verified?', default=False) isEmailVerified = models.BooleanField( verbose_name='Is Email Verified?', default=False) otp = models.CharField(max_length=6) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email'] objects = CustomUserManager() def __str__(self): return self.phone_number + " | " + self.email # Method to Put a Random OTP in the CustomerUser table to get verified for the next time after save. def save(self, *args, **kwargs): number_list = [x for x in range(10)] # list comprehension code_items = [] for i in range(6): num = random.choice(number_list) code_items.append(num) code_string = "".join(str(item) for item in code_items) # list comprehension again # A six digit random number from the … -
How to arrange forms fields vertically?
I am creating a login form by using the Forms class. Unfortunately, when I run the page I found the arrangement of the fields is horizontal. Can you help me to make it vertically, please? In the bellow the forms.py code: from django import forms class LoginForm(forms.Form): username = forms.CharField(label='Your name', max_length = 50) password = forms.CharField(max_length = 50, widget=forms.PasswordInput) And here is the views.py code: from django.shortcuts import render from .models import Login from .forms import LoginForm # Create your views here. def login_function(request): try: username = request.POST.get('username') password = request.POST.get('password') data = Login(username = username, password = password) data.save() except: x = 'error' return render(request,'pages/login.html', {'loginform':LoginForm}) And here is login.html code: {% block content %} <form method="POST"> {% csrf_token %} {{loginform}} <input type="submit" value="Save"> </form> {% endblock content %} -
Invalid block tag on line 5149: 'endif'. Did you forget to register or load this tag? Where am I wrong?
I'm not sure where I am going wrong here. I believe I have followed every rule here. Please point out if I missed something. I'd appreciate your help. (% if tot86|floatformat > 0 %) <div class="row"> <div class="col-8 text-start fs2 border-bottom border-end border-start border-dark"><b>Income</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot86|floatformat}}</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot86|floatformat}}</b></div> </div> <div class="row"> <div class="col-8 text-start fs2 border-bottom border-end border-start border-dark"><b>AMOUNT PAYABLE</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot90|floatformat}}</b></div> <div class="col-2 text-center fs2 border-bottom border-end border-dark"><b>{{tot91|floatformat}}</b></div> </div> {% endif %} -
i got an error in my forms.py file of project
` from django import forms from django.core import validators from matplotlib import widgets from .models import * class Userregistration(forms.ModelForm): class Meta: model=User fields=['username','password','name','email_id','contact','address'] widgets={ 'username':forms.CharField(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'name':forms.CharField(attrs={'class':'form-control'}), 'email_id':forms.EmailField(attrs={'class':'form-control'}), 'contact':forms.CharField(attrs={'class':'form-control'}), 'address':forms.CharField(attrs={'class':'form-control'}), } ` it is showing me typeerror:'__init()'got an unexpected keyword argument 'attrs' -
List field names of a model as choices in the field of another model
Unfortunately, I cant find exactly what I need but I know it requires get_fields() Id am guessing I would need a method call to create the list of field names : class ModelA(models.Model): field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) field_a = models.CharField(max_length=100) class ModelB(models.Model): fields = models.CharField(max_length=100, null=True, blank=True, choices=field_names_of_modela()) def field_names_of_modela(): return [field.name for field in ModelA._meta.get_fields()] The above code wont work... Is there a way to get field names of another model as a list in this model? Thanks -
why django admin template doesn't load
Since I had started Django, I'm tackling some ridiculous problems. Recently, when I start a new project and I run it on the server, Django's admin CSS is not loaded. The last project I ran on the server, after a while it was okay, and the real Django admin template was there and the CSS was loaded and it was working. But this time again the same problem happened and I don't know how to solve it cause the projecthere is the photo is raw, with no special code. I would be glad if you can help me -
Django queryset evaluation and bulk_update with dependencies
Suppose I have the following model (vastly simplified, for the sake of the question): class DailyMetric(models.Model): value_1 = models.FloatField() value_2 = models.FloatField() ratio = models.FloatField() As the name suggests, there will be an entry for each day. However, value_1 and value_2 depend on the values from the previous day. Let's say, the calculation is as follows: def update_values(instance, previous_instance): if previous_instance: instance.value_1 = previous_instance.value_1 + 5 instance.value_2 = previous_instance.value_2 - 15 instance.ratio = instance.value_1 / instance.value_2 Naturally, if I update the value for the first of the previous month, I have to update all following instance. For performance reasons, I want to make use of 'bulk_update': # member method of the model class def update_following(self): following_entries = self.get_following_entries() if not following_entries.exists(): return for i in range(following_entries.count()): if i == 0: update_values(following_entries[i], self) else: update_values(following_entries[i], following_entries[i-1]) DailyMetric.objects.bulk_update(following_entries, ['value_1', 'value_2', 'ratio']) However, it seems, that update_values always gets the instance with the values stored in the database, even though its "python" representation has been modified in the previous iteration. If I cast the queryset to a list beforehand, it works as expected. But in my understanding a queryset is evaluated lazy, and by accessing one value, the query has to be executed … -
Gunicorn failes because ModuleNotFoundError: No module named celery
I have moved my django app from my local environment to a server. I installed all the dependencies that my local environment has. However, gunicorn is failing because it says: from celery import Celery "ModuleNotFoundError: No module named celery I have already installed Celery via pip (pip install celery). Run celery, celery-beat, and flower run in terminals successfully. Also, from the Python shell, I get the following: >>> from celery import Celery >>> Celery <class 'celery.app.base.Celery'> So it seems like Celery is installed and even working, but for some reason my app is failing to due celery not being recognized. Any help identifying the problem would be appreciated. -
Django dynamic field casting when annotate
Lets say I want to save this data in to db: { "fields": [ { "field_type": "number", "name": "field_1", "value": 8223, }, { "field_type": "string", "name": "field_2", "value": "demo" }, { "field_type": "bool", "name": "field_3", "value": true } ], "blockchain_id": 47, "name": "event", "block_number": 3916102, } Here value is dynamic based on field_type value. Here is my models: class Event(models.Model): blockchain_id = models.IntegerField() name = models.CharField(max_length=100) block_number = models.IntegerField() fields = models.ManyToManyField(EventField) class EventField(models.Model): TYPE_CHOICES = ( ('number', 'Number'), ('string', 'String'), ('bool', 'Boolean'), ) field_type = models.CharField(max_length=6, choices=TYPE_CHOICES) name = models.CharField(max_length=100) value = models.CharField(max_length=100) I am saving dynamic value as Character (you can suggest something better). Then when I am returing those values I want to cast based on field_type value. So far here is my query: Event.objects.filter(id=_id).annotate(fields_value=Case( When(fields__field_type='number', then=Cast('fields__value', output_field=models.IntegerField())), When(fields__field_type='string', then=Cast('fields__value', output_field=models.CharField())), When(fields__field_type='bool', then=Cast('fields__value', output_field=models.BooleanField())), output_field=Case(When(fields__field_type='number', then=models.IntegerField())))) Now I am gettings this error message Cannot resolve expression type, unknown output_field .Maybe I am missing something. How can I return value with casting based on field_type ? -
Write a custom django validation function
I have a field named bar i need to write a validation function to validate this bar in django what conditions can i apply to this and how should my function be? Note:Please dont share link of django validators models.py class Model: bar = models.CharField('Bar', max_length=255, blank=True, null=True) -
How to Update a field in Django
I want to Update only name field if only name is sent from frontend, update only image if only image is sent from frontend, update both if name & image is sent from frontend In Django data =request.data if data['name'] and data['image']: category= Category.objects.get(id=data['id']) category.name=data['name'] category.image=data['image'] category.save() elif data['name']: category= Category.objects.get(id=data['id']) category.name=data['name'] category.save() else: category= Category.objects.get(id=data['id']) category.image=data['image'] category.save() -
Can i use the views.py file to actually send emails?
I am trying to create a contact form in Django that actually sends emails for real. Can i put all the email configs in the views.py file itself? I want to do that because i want only the legitimate owners of emails to actually send emails. I do not people to send me emails using their friends email. -
Cutomize dj_rest_auth Password reset email
I want to send customized emails when a user request a password reset. I am using dj_rest_auth with django. Here is what I have done: 1. Defined a custom serializer that inherits from PasswordResetSerializer of dj_rest_auth class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'html_mail_template_name': 'registration/password_reset_email.html', } Then in settings.py pointed to this serializer: REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'users.serializers.CustomLoginSerializer', 'PASSWORD_RESET_SERIALIZER': 'users.serializers.CustomPasswordResetSerializer', } Then configured templates in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then I created templates folder in project root, created a registration folder inside it and placed password_reset_email.html inside it. This is what I found as an exact solution formy problem after googling some time,but this is not working for me. What did I miss? -
what is the need of ForeignKey( Room ) in the given code?
**> what is the use of the foreign key room needed in this code and what** **> happens when we implement this foreign key room in our code please help guys just a beginners in Django world ** > class Message(models.Model): > # user = > room = models.ForeignKey(**Room**, on_delete=CASCADE) > body = models.TimeField() > updated = models.DateTimeField(auto_now= True) > created = models.DateTimeField(auto_now_add= True) > > def __str__(self): > return self.body[0:50] -
django migrate primary OneToOneFiled ForeignKey + into composite foreign key
I've a model which is just a relation between two entities like this: class SomeModel(models.Model): a = OneToOneField(User,primary_key=True,...) b = ForeignKey(Car,...) As per design, it was correct, as I didn't want an User to have multiple Car. But in my new design, I want to accept multiple Car to an User. So I was trying something like this: class SomeModel(models.Model): class Meta: unique_together = (("a", "b"),) a = ForeignKey(User,...) b = ForeignKey(Car,...) But during migration, it asks me: You are trying to add a non-nullable field 'id' to somenmodel without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: I just wanted to remove that foreign key from OneToOneRelation and add a new id combining both. - How to resolve this? -
Recursive comment system in django
I have a comment system for my website and I pass all the comments with the relevant post but when I loop through the comments and show each comment it's children it shows them after it as independent comments. {% load custom_tags %} {% for comment in page_obj %} <div class="comments"> <h6><a href="{% url 'main:creator' comment.publisher.id %}">{{comment.publisher.name}}</a></h6> <span>{{ comment.created_on}}</span> <div> {{comment.text}} <br> </div> {% if comment.children %} <ul style="margin-right: 5%;"> {% include "post/comment.html" with page_obj=comment.children %} </ul> {% endif %} </div> {% endfor %} -
How to fix django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
Seen this question already asked but still no solution working for me. My docker-compose: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGREES_PASSWORD=password web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/books ports: - "8000:8000" depends_on: - db my requirements.txt Django>=3.2 psycopg2-binary>=2.8 my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER' : 'postgres', 'PASSWORD' : 'postgres', 'HOST' : 'db', 'PORT' : 5432, } } my dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /books COPY requirements.txt /books/ RUN pip install -r requirements.txt COPY . /books/ the error that is showing on my terminal File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution -
Error: blog.Comment: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
mysite-virtualenv) 10:43 ~/django-blog (master)$ ./manage.py migrate System check identified some issues: WARNINGS: blog.Comment: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlogConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'dja ngo.db.models.BigAutoField'. blog.Post: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlogConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'dja ngo.db.models.BigAutoField'. users.Profile: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the UsersConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'dj ango.db.models.BigAutoField'. Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, users Running migrations: No migrations to apply. -
AttributeError at /Customer/Visit 'WSGIRequest' object has no attribute 'is_ajax' in django
Please Help me im trying to learn ajax in django but when i running this simple test i got this error and i cant find the reason, my django version is 4.0 error AttributeError at /Customer/Visit 'WSGIRequest' object has no attribute 'is_ajax' This is my js file code: enter code here const alertBox = document.getElementById('alert-box') const imagebox = document.getElementById('image-box') const form = document.getElementById('visit-form') const customer = document.getElementById('id_Customer') const visit_date = document.getElementById('id_Visit_date') const price = document.getElementById('id_Price') const pic = document.getElementById('id_Pic') const csrf = document.getElementsByName('csrfmiddlewaretoken') const url = '' const handelAlert = (type, text) => { alertBox.innerHTML = '<div class="alert alert-"' + type + '"> ' + text + ' </div>' } pic.addEventListener('change', () => { const image_data = pic.files[0] const url = URL.createObjectURL(image_data) console.log(url) imagebox.innerHTML = '<img src="' + url + '" width="50%" >' }) form.addEventListener('submit', e => { e.preventDefault() const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('customer', customer.value) fd.append('visit_date', visit_date.value) fd.append('price', price.value) fd.append('pic', pic.files[0]) alert('df') $.ajax({ type: "POST", url: url, enctype: 'multipart/form-data', data: fd, success: function(response) { console.log(response) const sText = 'ثبت ' + response.visit_date + 'با موفقیت انجام شد' handelAlert('success', sText) setTimeout(() => { alertBox.innerHTML = "" imagebox.innerHTML = "" customer.value = "" visit_date.value = "" price.value = "" … -
Why i can't update image in django?
modle.py class Form(models.Model): name = models.CharField(max_length=40) email = models.EmailField() file = models.ImageField(null=True, blank=True) class Meta: db_table: 'django' # table name edit.py <form action="{% url 'update' user.id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="name" name="name" value="{{ user.name }}"> </div> <div class="mb-3"> <label for="exampleFormControlInput" class="form-label">Email address</label> <input type="email" class="form-control" id="exampleFormControlInput" placeholder="name@example.com" name="email" value="{{ user.email }}"> </div> <div class="mb-3"> <label for="exampleFormControlInput2" class="form-label">Image</label> <input type="file" class="form-control" id="exampleFormControlInput2" name="{{ user.file }}" > </div> <div class="mb-3"> <img src="{{ user.file.url }}" alt="" srcset="" style="width:100px"> </div> <button type="submit" class="btn btn-primary" id="liveToastBtn">submit</button> </form> view.py when i try to update from all the fields is all update and also remove old image but it doesn't save new image to directory please help me def update(request, user_id): user = Form.objects.get(id=user_id) form = UserForm(request.POST, request.FILES, instance=user) if request.method == 'POST': if form.is_valid(): if os.path.exists(user.file.path): os.remove(user.file.path) form.save() return redirect("listing") else: # mean form is invalid return render(request, 'edit.html', {'user': user}) -
Django: AttributeError: module 'collections' has no attribute 'Iterator'
Using django-admin startproject test gives error like AttributeError: module 'collections' has no attribute 'Iterator' even though I have django installed and could see list of commands by doing django-admin. Here is the full error . Traceback (most recent call last): File "/Users/Person/Dev/trydjango/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/management/templates.py", line 117, in handle django.setup() File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/__init__.py", line 16, in setup from django.urls import set_script_prefix File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/urls/__init__.py", line 1, in <module> from .base import ( File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/urls/base.py", line 8, in <module> from .exceptions import NoReverseMatch, Resolver404 File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/urls/exceptions.py", line 1, in <module> from django.http import Http404 File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/http/__init__.py", line 5, in <module> from django.http.response import ( File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/http/response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/serializers/__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/core/serializers/base.py", line 6, in <module> from django.db import models File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/db/models/__init__.py", line 3, in <module> from django.db.models.aggregates import * # NOQA File "/Users/Person/Dev/trydjango/lib/python3.10/site-packages/django/db/models/aggregates.py", line 5, in <module> from django.db.models.expressions import Case, Func, … -
django-tables2 exporting custom URL column
G'day All, Hope everyone is doing well. I have a table that I render with a custom column that is a hyperlink. The problem is when i export to CSV it just gives me the text of the hyperlink and not the hyperlink. I'm wanting to export the hyperlink instead of just the text, is this possible? (if i need to switch to xlsx export that's also fine) (worse comes to worse I can just make the text the full path) Custom column: document_link = tables.TemplateColumn('<a href="{{record.document_file.url}}/" target="_blank">{{record.document_file}}</a>', verbose_name="Document location") Thanks in advance, -
Use SQL VIEWS in Django
Is there any way to use the SQL Command CREATE VIEW in Django? If I Try To use regular syntax, or use from django.db import connection ... with connection.cursor() ... I get an Error.