Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: app displays 400 error when deployed on server
Actually I have two problem here.I have one vps(bare minimum for testing) on which I have 2-3 apps.I have just deployed another app on it & got a free domain name from freenom.com.I use supervisor+nginx for hosting the app.For no reason I am getting this Bad Request (400) when I visit the domain.Generally this occurs when you don't put the the domain name in the ALLOWED_HOSTS list but I have set this up. The second problem is that I have DEBUG = True still it's just displaying the bare minimum error response instead of full stack trace hence I am not sure what errors I am actually getting & unable to debug it. No error logs in the gunicorn-error.log file. No error logs in the nginx-error.log file. No error logs in the nginx-access.log file. My gunicorn_start config #!/bin/bash NAME="hrms_app" DIR=/home/kunsab/projects/hrms_venv/hrms USER=kunsab GROUP=kunsab WORKERS=3 BIND=127.0.0.1:8081 DJANGO_SETTINGS_MODULE=hrms.settings DJANGO_WSGI_MODULE=hrms.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- supervisor config: [program:hrms_app] command=/home/kunsab/projects/hrms_venv/bin/gunicorn_start user=kunsab autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/kunsab/projects/hrms_venv/logs/gunicorn-error.log settings.py """ Django settings for hrms project. Generated by 'django-admin startproject' using Django 3.1.3. For more information … -
How to load only active data in Django Forms
I have a model that is referenced to my Profile by ForeignKey. During registration, I want to load this model that is active only. My Profile model: residence_status = models.ForeignKey("residencestatus.ResidenceStatus", verbose_name="ResidenceStatus", related_name="Profile", on_delete=models.CASCADE) My Residence Status Model: is_active = models.BooleanField(default=False, null=False) Created a separate py file to get the residence status and return as an object(Since there are a lot of models like this) def get_residence_status(): resObjs = ResidenceStatus.objects.all().filter(is_active=True) return resObjs Then on my forms, load it all on choices: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = "__all__" def __init__(self, *args, **kwargs): RESIDENCE_STATUS_CHOICE = {} resObj = get_residence_status() for x in resObj: print(x) RESIDENCE_STATUS_CHOICE['id'] = x super().__init__(*args, **kwargs) self.fields['residence_status'] = forms.ChoiceField(choices=RESIDENCE_STATUS_CHOICE) On my terminal, the result if print(x) and print(RESIDENCE_STATUS_CHOICES) are as follows: 特になし {'id': <ResidenceStatus: 特になし>} 特定技能外国人 {'id': <ResidenceStatus: 特定技能外国人>} '高度人材 {'id': <ResidenceStatus: '高度人材>} その他 {'id': <ResidenceStatus: その他>} However, the return on my template(select) is only "d" -
How to write a condition use django queryset
I write a if else statement to user but it not working. I get data form database use Post.objects.get(sno = delpk). Then i writer a condition request.user.username == Post.author def postdelapi(request): if request.method == 'POST': delpk = request.POST['delpk'] deletepost = Post.objects.get(sno = delpk) print(Post.author) if request.user.username == Post.author : deletepost.delete() else: HttpResponse('eroor') else: pass return redirect('home') -
Wishlist functionality in Django
I am trying to implement wish list functionality My requirement is In my website I have deals page, coupons page, promotions page. For deals page I have some list of products for each product it has on fav icon. If user clicks on fav icon it has drop down list by default deals and then create new list two columns and if user choose deals that product added to deals list. or else if user clicks on create new list user will create some list then that product added that new list. By list wise we have to shown in wish list template page. How can i achieve this please any one can help to achieve this thank you. -
Django How to user FormSet with ListView
I'm trying to use modelformset_factory with ListView to Update multiple rows in the model. It works fine just subclassing the FormView, but I would like to pagenate it. -
How to access a txt file in django via url for verification purposes
I have purchased an SSL certificate and I used an HTTP validation method where I need to store a text file under my server. I am supposed to store is as http://eblossom.lk/.well-known/pki-validation/ECB7.txt. I am hosting through Linode(Ubuntu) using apache2. However, for some reason, my website cannot access the folder and gives me an error saying that the URL is invalid. I know for a fact that if I type something like http://eblossom.lk/static/style.css, my static file appears, similarly, I need to allow my SSL certificate provider to get access to my .txt file the same way by. Note: FOLDER NAME CANNOT BE CHANGED I am sure something should be done with the settings.py file to allow access to open that folder, but I am not sure how. Any ideas? Thanks! -
Multiply input values into other input
I want to multiply numbers and the result shows in another input. I managed to obtain the value of each input with the following code, but from here I do not know how to advance and make it multiply and that the result is shown in the input of the "total". This is part of the code: $(` [name='unidadTrabajosFactura'], [name='precioUniTrabajoFactura'], [name='totalTrabajoFactura'] `).each( function(index, item){ var valores = $(item).val(); console.log(valores) }); in the console I get the following results: What I want to achieve is that the quantity value is multiplied by the unit price and show the result in in input of total An this is my form code <div class="job-form row mb-3"> <div class="col-md-1"> <label for="unidadTrabajosFactura" class="">Unidad</label> <input type="text" name="unidadTrabajosFactura" class="form-control" value="{{trabajo.unidad}}"> </div> <div class="col-md-5"> <label for="descTrabajosFactura" class="">Descripción</label> <input type="text" name="descTrabajosFactura" maxlength="200" class="form-control" value="{{trabajo.trabajo}}"> </div> <div class="col-md-2"> <label for="precioUniTrabajoFactura" class="">Precio Unitario</label> <input type="text" name="precioUniTrabajoFactura" class="form-control" value="{{trabajo.precio_unitario}}"> </div> <div class="col-md-2"> <label for="totalTrabajoFactura" class="">Total</label> <input type="text" name="totalTrabajoFactura" class="form-control" value="{{trabajo.total}}"> </div> These fields can be multiple as well as one Regards -
Filter the data generated from DB - Django
How to limit the generated list from database? I have a model that references to other models via ForeignKey. class ApplicantAccount: sns_name = models.ForeignKey("sns_names.SnsNames", verbose_name="SnsNames", related_name="ApplicantAccount", on_delete=models.CASCADE) With this line, all of the list inside SNS would be displayed in template. However, in my SNS model, I have added a boolean field is_active. I just want to render only the active SNS. How to do this? At first, I created a py file that would handle all the generated list like this: models: def get_sns(): # Get all active SNS Names snsObjs = SnsNames.objects.all().filter(is_active=True) return snsObjs Then on view, pass it to context then render it to template view.py: snsObjs = get_sns() context['snsObjs'] = snsObjs return render(request, 'forms/reg_form.html', context) But on my template, it displays everything. I just found out that even if I remove the code from views.py, snsObjs = get_sns() context['snsObjs'] = snsObjs it still generates all the list. -
Updating template with a form through context or fetch
I'm on a project and i need a way to get a django form as a response to a fetch request or maybe to re-render my template with the context dictionary updated with the form in it. I want to add the form to a modal box when the button is clicked. Thanks guys -
Trouble loading static files in Nginx + Digital Ocean Deployment
Django Beginner here.. Having some trouble loading my static files during final deployment on a Digital Ocean Droplet I'm using Nginx and Gunicorn. I've followed a tutorial from Traversy Media, but I can not get my static files to show up in the browser via my Digital Ocean ipv4. Upon inspecting it is throwing these multiple errors. Refused to apply style from 'http://162.243.162.127/btre/static/css/all.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET 162.243.162.127/:510 GET http://162.243.162.127/btre/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) Here are my nginx settings server { listen 80; server_name 162.243.162.127; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/realestate_project; } location /media/ { root /home/djangoadmin/pyapps/realestate_project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Here are my gunicorn settings [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/djangoadmin/pyapps/realestate_project ExecStart=/home/djangoadmin/pyapps/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ btre.wsgi:application [Install] WantedBy=multi-user.target I've tried running collectstatic in the terminal multiple times but it does not do anything.. Says it has '0 to collect'. -
Python re-write jupyter notebook to python script problem
I have a very simple RNN model which I can execute on Jupyter notebook without any problem, now I want to embed this model in my Django project, so I downloaded the .ipynb file then saved it as .py file, then I just put it in my Django project. However, the first problem is VSCode says I have unresolved import 'MLutils, the MLutils is my utility file in the same folder. The second problem is if I just run this file, I'll get this error RuntimeError: cannot perform reduction function argmax on a tensor with no elements because the operation does not have an identity but if I use the Run Cell Above button of the VSCode, I'll get the correct result. The code I want to run is this, called MLTrain.py import torch import torch.nn as nn import matplotlib.pyplot as plt from MLutils import ALL_LETTERS, N_LETTERS from MLutils import load_data, letter_to_tensor, line_to_tensor, random_training_example class RNN(nn.Module): # implement RNN from scratch rather than using nn.RNN # # number of possible letters, hidden size, categories number def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size #Define 2 different liner layers self.i2h = nn.Linear(input_size + hidden_size, hidden_size) self.i2o = nn.Linear(input_size + … -
Get first instance for each group in a model
So I love django but I keep bumping my head into the same or similar problem. That is, I have a model A with a FK to another model B, and I want the first model A instance for each model B. For example, I have the following models: class Room(models.Model): name = models.CharField(primary_key=True, max_length=16, blank=False) class Event(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=False) start = models.DateTimeField(blank=False) end = models.DateTimeField(blank=False) (...) It's basically, each Room has Events which have a start and end time. I want to get the next Event for each Room considering now - Q(start__gt=datetime.now()) I've tried a lot of things, I don't say everything because I have little experience with django.db.models.functions and I don't if that's way For reference, what I want to do in SQL is: SELECT * FROM api_event WHERE start > VAR_NOW GROUP BY room_id; Which returns this: +----+----------------------------+----------------------------+---------+-------------+ | id | start | end | room_id | course_id | +----+----------------------------+----------------------------+---------+-------------+ | 1 | 2020-10-15 15:30:00.000000 | 2020-10-15 17:00:00.000000 | 0-14 | DDRS14 | | 17 | 2020-10-13 15:30:00.000000 | 2020-10-13 17:00:00.000000 | 0-21 | DDRS14 | | 26 | 2020-10-16 12:30:00.000000 | 2020-10-16 14:00:00.000000 | 0-27 | CGJ7 | | 39 | 2020-10-14 … -
How to join tables from models that are not directly related
The title is kinda weird (sorry, I did not have any other idea on how to ask my question clearly) but let me explain it better here with an example, it will be more understandable. Lets start with the models: class A(): # Abstract class field_a = models.IntegerField(default=0) class B(A): # Inherit fields from A field_b = models.TextField(blank=False, null=False) class C(A): # Inherit fields from A + foreign key on B field_c = models.TextField(blank=False, null=False) foreign_key_to_b = models.ForeignKey("B", blank=False, null=False) class D(): # model with foreign key on A and B but not inheriting from A field_d = models.TextField(blank=False, null=False) foreign_key_to_a = models.ForeignKey("A", blank=False, null=False) foreign_key_to_b = models.ForeignKey("B", blank=False, null=False) And this is, in SQL, what I am trying to achieve: SELECT c.* FROM C c INNER JOIN B b ON b.id = c.foreign_key_to_b INNER JOIN D d part ON d.foreign_key_to_b = b.id WHERE d.foreign_key_to_a = 10 I am trying to get all C, depending on a condition on a field of D. To do so, I join D to B then B to C and get the fields I need. Since D has a foreign key to A, the object this foreign key is pointing to, can be one … -
Django. Non-ascii field doesn't create slug. I expect to get transliteration, but getting an empty field and error
I have simple Model with title and slug fields. I want to accept non-Latin characters as a title and transliterate them into Latin slug. Specifically, I want to transliterate Cyrillic characters, say 'Привет, мир!' into Latin 'privet-mir'. Instead of slug I'm getting following error: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[-a-zA-Z0-9_]+)/$'] Django Version: 3.1.5 Python Version: 3.9.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$'] Model from django.db import models from django.template.defaultfilters import slugify class Post(models.Model): title = models.CharField(max_length=70) slug = models.SlugField(null=False, unique=True, allow_unicode=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.BlogList.as_view( template_name=app_name + "/blog_list.html"), name='blog_list'), path('<slug:slug>/', views.BlogDetail.as_view( template_name=app_name + "/blog_detail.html"), name='blog_detail'), ] views.py from .models import Post from django.views.generic import ListView, DetailView class BlogList(ListView): model = Post class BlogDetail(DetailView): model = Post blog_list.html (for each post) <a href="{% url 'blog:blog_detail' blog.slug %}">{{ blog.title }}</a> blog_detail.html (short) <h1>{{ blog.title }}</h1> NoReverseMatch at /blog/ -
Learning django but i get an error in a simple poll app
I'm trying to learn django from scratch. So I found a tutorial online:Tutorial simple poll app and I followed it and it just replies: in the terminal: Not Found: /polls/ [30/Jan/2021 00:12:39] "GET /polls/ HTTP/1.1" 404 1957 On the http://localhost:8000/polls/ web page: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I went over all the syntax and it all matches up. please help me I don't know how to solve this probleme -
My register form will not save the image to my S3 Bucket
I am losing my mind and not sure whats going on. I created a register page and everything saves except for image. However if the user does log in even though the image didn't save. In the profile template they can upload it and it will save just fine. I need it to save on my register form. I also know this isn't idea for a user experience but this way is needed so a admin can set up users. I know my AWS S3 is set up correct with my IAM and in my settings.py file. I'm going to have my code below. View def register(request): # techs = Employee.objects.all() # empFilter = EmployeeFilter(request.GET, queryset=techs) # techs = empFilter.qs # copyTech = techs[0] if request.method == 'POST': user_form = UserRegisterForm(request.POST) if user_form.is_valid(): user_form.save() user_id = User.objects.get(username=user_form.cleaned_data['username']) user_profile = Profile.objects.get(user=user_id) pdb.set_trace() profile_form = ProfileRegisterForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() return redirect('clearview:login') else: profile_form = ProfileRegisterForm() user_form = UserRegisterForm() context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'users/register.html', context)enter code here form class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileRegisterForm(forms.ModelForm): CROP_SETTINGS = {'size': (300, 300), 'crop': 'smart'} locationName = … -
Sending additional info in post request
I am trying to implement a form with a "Contacts" datalist, I need to get the id number of the contact in order to process it in the db in Django but I don't want the id to be shown to the user, I want the datalist to have the "normal" info. The datalist code is the following: <div class="form-group"> <label class="form-label" for="contactOptions">Contact:</label> <input class="form-control" name="contact" list="contactOptions" placeholder="Type contact"> <datalist id="contactOptions"> {% for contact in contact_options %} <option> {{contact.id}}: {{ contact.info }} </option> {% endfor %} </datalist> </div> To sum up: Want to populate the datalist with the info of the contacts except the id. Need to get the contact id when using request.post in the views in Django. I have a JS file to manipulate the HTML if required. -
Populate Django SearchVectorField with bulk_create()
I'm trying to use the performance SearchVector, using SearchVectorField in model but it seems it is not possible to populate SearchVectorField on insert for some reason. All documentation I read only gives me either .annotate(search=SearchVector('...')) or .update(search_vector=SearchVector('...')) and I don't want to use either. Using annotate approach would be slower. Using "performance" update approach I need to first create the record and do a second query to populate the SearchVectorField. Because I'm using .bulk_create() it would make sense to insert SearchVector results on the fly since I have all the values already and not create another query to update SearchVectorField but for some reason it is not possible. Is it really not possible or am I missing something? -
Django Rest Framework: set serializer context for serializer that is not serializer_class
I'm having an issue in one of my viewsets where I need to use a different serializer for one particular endpoint. The issue is that I need to access the context and the method get_serializer_context on my viewset is not being called for this endpoint that uses a different serializer than the one defined in the viewset aswell. How can I call this method or find some other way of setting the context for this serializer in this endpoint? -
django extra fields on profile page
I already created a Django App, registration, login, and profile and edit profile pages. Everything is working fine, and now I need to add on the profile page more fields, such as phone number, home address, office address, city, estate, how can I add those fields in the profile and allow the user to fill in the data and store it on the database? Thank you! -
Django + Heroku + Cloudinary (for static files) not showing
I am using cloudinary as my static files storage. When I deploy to heroku, all the static files get uploaded successfully. However, when I visit my admin section, the css is "not found". Apparently it is loading the file with the wrong hash. Example, if the actual file is "base.98at7sdt7.css", what gets loaded is "base.8799894d3e.css" which obviously doesn't exist so it returns a 404. Any idea on what could be wrong? -
Why does text exceed bootstrap boundary?
I have some text and its inside an bootstrap media-body. When I load, the page the text passes the media box and overflows it, like so: Image Problem As you can see the text exceeds the boundary. So how would I fix that. My code is this: {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <a href="{% url 'user-posts' post.author.username %}"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> </a> <div class="media-body"> <div class="article-metadata"> <title>Post: "{{ object.title }}"</title> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }} | Appropriate for ages {{ post.appropriate_for_ages }} and up | <i class="fa fa-map-marker"></i> {{ post.location }}</small> &nbsp;{{ post.blog_view }} views {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content|safe }}</p> <hr> <div class="article-footer"> <style>.content-likes {display: inline-block;padding-right: 5px; }</style> <h4 class="content-likes">{{ post.likes }}</h4><h5 class="content-likes">likes</h5><br> {% if user.is_authenticated %} <a href='{% url "like_post" post.id %}'><i class="fa fa-thumbs-up" style="font-size:36px; color:green"></i></a> <a href='{% url "dislike_post" post.id %}'><i class="fa fa-thumbs-down" style="font-size:36px; color:red"></i></a> {% else %} <a onclick="alert('In order to … -
DeserializationError when adding fixture on server (loaddata)
I am trying to add my data to database in my server. I use exactly the same JSON file in my local machine and it works. But when I do the same in server it gives me Deserialization Error. The JSON file is so big that I can't show it here but I am sure there is no typo. I did all migrations and database works - I can add object from admin dashboard. How can I solve this error? The error I get: Traceback (most recent call last): File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/serializers/json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = … -
SMTPSenderRefused when sending email from Django app using Google Workspace
I'm getting the following error message when trying to send an email from my Django app using a Google Workspace account: Error message Screenshot of my Django settings: Django settings Access for less secure apps is enabled for this account in the Google Workspace settings. The IP address from which the email is sent is added to the Google Workspace relay settings (sorry for German screenshot): Relay settings What is missing? Google Support seems unable to help me. Thanks! -
Change label color of Django user form
I added a user module to my project and I used the default Django user model for that. I've to change the styling to suit my other pages. The background color is black. The problem is default labels and error messages (eg: "username", "password", "Enter the same password as before for verification") generated by Django is also black and not visible now. How to change the label colors so that they are visible again? I'm a newbie to both development & StackOverflow, apologies if I have used incorrect terms or tags in my question. Thanks in advance.screenshot of the login form (highlighted is my problem