Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change a form's data after already populating it in Django
This might be a duplicate but I tried lots of solutions and none worked for me. views.py class signup_view(View): def get(self, request): signup_form = SignUpForm() return render(request, 'signup.html', {"forms": signup_form}) def post(self, request): signup_form = SignUpForm(data=request.POST) if signup_form.is_valid(): email = signup_form.cleaned_data.get('user_email') password = signup_form.cleaned_data.get('user_pass') print("Original password is: ", password) hashed_password = make_password(password) print("Hashed password is: ", hashed_password) signup_form.inital['user_pass'] = hashed_password signup_form.save() request.session['username'] = email return render(request, 'main_page.html') else: return render(request, 'signup.html', {"forms": signup_form}) I have this django view that I populate with information from the post request, however, I need to make sure that both the password and the password confirmation (in the forms) are the same so that I can procced, I do that in the clean() function I'll post below. However, I need to save the hashed password on my database and not the actual password and I have no idea what I can do the change the contents of the form after I already verified that it's valid (not sure if I can even do this). class SignUpForm(forms.ModelForm): user_pass_check = forms.CharField(label="Password confirmation", widget=forms.PasswordInput()) class Meta: model = AppUser fields = ["user_email", "user_country", "user_pass"] widgets = {"user_pass": forms.PasswordInput()} def clean(self): cleaned_data = super(SignUpForm, self).clean() pass1 = cleaned_data.get('user_pass_check') pass2 … -
How to use django SelectBox in our templates
I want to design template with form that be same as Django SelectBox. Like this: How to use Django form, templates ,and js files for this purpose? -
django-admin startapp v/s python manage.py startapp [duplicate]
This question already has an answer here: When should you use django-admin.py verus manage.py? 2 answers What is the difference between django-admin startapp and python manage.py startapp? They both create apps and the files are also same so what's the difference between these two? -
Many to many relationship model on Django
I have two tables called User and Courses and I want to show the relationship between them my implementing a many-to-many relationship model. I want to implement 3 model classes in total as so: # user/model.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_status = models.BooleanField(default=False) is_newbie = models.BooleanField(default=False) #courses/model.py from django.db import models from register.models import User class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) class StatusHasCourse(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Courses, on_delete=models.CASCADE) How do I implement this so only the relationship between User that have is_status = True are only accessed in the StatusHasCourse model? -
How can I efficiently concatenate two nested ForiegnKey relationships?
In a Django 2.2 model, I have the following setup: class Kiosk(Model): newspapers = ForeignKey('Newspaper') class Newspaper(Model): articles = ForeignKey('Article') class Article(Model): pass Now, I can get all articles of one newspaper sold in a kiosk like so: kiosk = Kiosk.objects.first() articles = kiosk.newspapers.first().articles What I want to do is get one QuerySet (or RelatedManager) spanning all articles in all newspapers sold by a kiosk. I can of course achieve this by iterating over the newspapers and concatenating the articles lists in a for loop, but that seems inefficient. How can I get this from the ORM? -
How to make Dynamic Slug URL in Django with <slug: > URL Dispatcher
For example, I have a model Service, and that service has a title: # services\models.py class Service(models.Model): title = models.CharField(max_length=100) Here's what urls looks like: # services\urls.py from . import views urlpatterns = [ # /services/ path('', views.index, name='index') # /services/name-of-service/ path('<slug:service_title>', views.service_detail, name='service_detail') ] I'm wanting the index to display a list of my services: # services\views.py from .models import Service def index(request): services = Service.objects return render(request, 'services/index.html' {'services': services} How would you write the script for the "service_detail" view? # services\views.py #... def service_details(request, ?): ? return ? -
How to set the VATLAYER_ACCESS_KEY in Saleor eCommerce Platform?
Saleor Django eCommerce Platform. I have just started setting up and learning Saleor and I am stuck setting the VATLAYER_ACCESS_KEY. I get the following error (Could not fetch tax rates. Make sure you have supplied a valid API Access Key. Check the server logs for more information about this error.). I have registered for a key API at VatLayer https://vatlayer.com/ I have set the key "this key is an example" in the common.env file as VATLAYER_ACCESS_KEY=2bb221d7fbce9fd274791959e120999d. Is this the correct location to set the key or should it be in the saleor/settings.py file and are there additional settings I need to apply to enable VatLayer? Any assistance would be greatly appreciated. Thank you. -
Nginx 502 bad gateway for deploying Django Project even it works with uwsgi
the nginx web server is successfully installed and working. But I get 502 bad gateway error. When I check the socket file path I can't see any file. /home/bilal/uwsgi/sites/testproject.ini -> [uwsgi] home = /home/bilal/my-first-project/venv chdir = /home/bilal/my-first-project wsgi-file = /home/bilal/my-first-project/projectname/wsgi.py socket = /home/bilal/uwsgi/testproject.sock vacuum = true chown-socket = bilal:www-data chmod-socket = 660 /etc/nginx/sites-available/testproject -> server { listen 80; server_name <domain> <www.domain>; location / { include uwsgi_params; uwsgi_pass unix:/home/bilal/uwsgi/testproject.sock; } } When I try to connect to server with ip address I get welcome to nginx page because ip isn't written for server_name. But when I try to connect to server with domain I get this error: 502 Bad Gateway nginx/1.14.0 (Ubuntu) I think this problem is about the .sock file but I don't know how can I handle it. -
Django populating form field from another model
i have two apps first is inputs and second is boq inputs contains a model building boq contains a model boq model My inputs model looks like class building(models.Model): building = models.CharField(max_length=300) My boq model looks like class boqmodel(models.Model): code = models.IntegerField() building =models.CharField(max_length=300) level = models.CharField(max_length=300) activity = models.CharField(max_length=300) subactivity = models.CharField(max_length=300) duration=models.IntegerField() linkactivity= models.CharField(max_length=300) linktype= models.CharField(max_length=300) linkduration=models.IntegerField() plannedstart=models.DateField() plannedfinish=models.DateField() actualstart=models.DateField() actualfinish=models.DateField() i have aform in boq class boqform(forms.ModelForm): class Meta: model = boqmodel fields=['code', 'building', 'level', 'activity', 'subactivity', 'duration', 'linkactivity', 'linktype', 'linkduration', 'plannedstart', 'plannedfinish', 'actualstart', 'actualfinish'] Now in my boqform for field building i need the form to have a dropdown from values in building model -
How do I transform a python dictionary to an HttpRequest appropriately?
I have a builtins.dict dictionary that looks like this: request = {"data": {"var": "hello", "content": "jello"}} I am writing a test for an API endpoint in django. I am calling the post method of that class and sending this request to it, and I am accessing the data in the request using request.data. But of course that won't work, because the request that goes into my post function is actually a django.http.HttpRequest, not a builtins.dict. How do I make it so that my request argument is a HttpRequest and not a dict so my function can consume it right? -
how do I outputting multiple foreign key values in django model forms
So i have been experimenting with django and its inbuilt databases and seem to have gotten stuck in displaying multiply foreign keys the refered models.py : from django.db import models # Create your models here. class flight(models.Model): fl_no =models.CharField(max_length=6,primary_key=True) inbound= models.CharField(max_length=15,blank=True) dest= models.CharField(max_length=15,blank=True) park_bay= models.CharField(max_length=3) airline= models.CharField(max_length=15) dep_time= models.TimeField() arr_time= models.TimeField() def __str__(self): return self.fl_no the referencing models.py: from django.db import models from postlog.models import flight # Create your models here. class FlightStatus(models.Model): Yes = 1 No = 2 CLEANING_CHOICES = ( (Yes, 'Yes'), (No,'No'), ) fl_no= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='fli_no') park_bay= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='desti') dep_time=models.ForeignKey(flight,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.PositiveSmallIntegerField(choices=CLEANING_CHOICES) my html code: {% extends 'base_template1.html' %} {% load static from staticfiles %} {% load crispy_forms_tags %} <!DOCTYPE html> {% block title %} Status {% endblock %} {% block content %} <button type="button" class="butra button1ra" data-toggle="modal" data-target="#Add_Modal">Add Flight Status</button> <!-- Adding a Flight Status --> <div class="modal fade" id="Add_Modal" tabindex="-1" role="dialog" aria-labelledby="Add_ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="AddModalLabel">Flight Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post"> {% csrf_token %} {{ form|crispy }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Add Details</button> </div> … -
Django error: "Related Field got invalid lookup: icontains" despite using proper double-underscore syntax
I'm using Django 2.2.6 and Python 3.7.0, and I'm getting the infamous "Related Field got invalid lookup: icontains" error. The weird thing is, I believe I am using the proper double-underscore syntax to access the CharField in the model behind the ForeignKey field (in this case, location_type__type in the search_fields of LocationAdmin). Any thoughts on this one? models.py class Location(models.Model): long_name = models.CharField(max_length=255, blank=True, null=True) location_type = models.ForeignKey(LocationType, models.DO_NOTHING, blank=True, null=True) abbreviation = models.CharField(max_length=15, blank=True, null=True) short_name = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'location' def __str__(self): return self.long_name class LocationType(models.Model): type = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'location_type' def __str__(self): return self.type admin.py class LocationAdmin(admin.ModelAdmin): list_display = ['long_name', 'location_type', 'abbreviation', 'short_name'] search_fields = ['long_name', 'location_type__type', 'abbreviation', 'short_name'] class LocationTypeAdmin(admin.ModelAdmin): list_display = ['type', 'description'] search_fields = ['type', 'description'] -
Issue while sending response for multiple data in Django Get
I am executing GET request for DJANGO REST API call with comma separated values. http://localhost:8080/xyz/abc/123,456,789 in views.py i am splitting this value and sending the response listVal=values.split(",") for val in listVal: do some processing update dictionary dict.update(newdict) print(dictionary) i am getting all 3 values printed here return response(dictionary) But , i am getting only the last value i.e 789 of the comma separated values and for other 2 i am not getting any response in json data. Is returning response suitable for multiple values or it takes only one value at a time. -
Django executing python script in web
I am trying to run my tensorflow script so that the result image will be exported and will be use to my site. At first, I'm using flask but I decided to shift to django because the script is too slow read and sometimes it won't run. That's why, I use django. But then, the script still wont run. Please, need help... At first, I'm using flask but I decided to shift to django because the script is too slow read and sometimes it won't run. That's why, I use django. But then, the script still wont run. Please, need help... Files that the tensorflow script needed were placed at the same location where views.py, urls.py are in. views.py # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys import easygui # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util from api import object_counting_api from django.shortcuts import render def mandaluyong(request): # Name of the directory containing the object detection module we're using path = easygui.fileopenbox() MODEL_NAME = 'inference_graph' IMAGE_NAME = path # Grab path to … -
VSCode autocomplete for Django QuerySet.filter(property__regex='^This not autocomplete')
How to autocomplete property of Django QuerySet.filter in VSCode? Just like it works in Pycharm as follow, I think it's really useful, because Django use too many python magic that will make developer confused -
I cant delete img on server when delete post or delete img in post with summernote-django
I cant find the way delete img on server when upload via summernote-django. (in short: I can run summernote-django nows. but in template when i del img in post. img on server not delete sync) my code : my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), my form.py from django import forms from django_summernote.widgets import SummernoteWidget from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content',) widgets = { 'content': SummernoteWidget(), } my views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm Thank you so much. -
get_object() that depends on `request` in UpdateView
I am writing a class-based view to allow users to edit their profile. Since I want the users to access this view with a URL of the type my_profile/edit/ rather than something like profile/<int:pk>/edit/, using a view based on UpdateView is quite cumbersome since getting the user profile object requires to access the request object, and get_object does not directly have access to it. My two questions: Shall I use UpdateView in this case? If so, what would be the best way to override get_object(self, queryset=None)? My best attempt so far is the following: class EditProfileView(UpdateView): model = UserProfile _request = None def get_object(self, queryset=None): return get_user_profile(self._request) def dispatch(self, request, *args, **kwargs): # can also override setup() in newer Django versions self._request = request return super().dispatch(request, *args, **kwargs) This looks clean enough to me except that if one day the Django framework decides that get_object should be called early in the workflow of the view generation, this piece of code could break. -
filter query not working when searching on foreign key in django
I've 2 classes in models.py - Users and authUser - 1st has app related info while 2nd has generic user info both are connected with a foreign key on username. I'm getting the user request info from 'request.user.username' and I'm trying to search in my users table to get app related info bsed on the logged in user. It's returning an empty queryset. I've tried - print(Users.objects.filter(username__username = request.user.username)) ----xx--- print(Users.objects.filter(username = request.user.username)) ----xx--- print(Users.objects.filter(Q(username__username = request.user.username))) ----xx--- print(Users.objects.get(username__username = request.user.username)) Even - tmp = (Users.objects.all()) for each in tmp: print(each.username) ----xx--- print(each.username__username) models.py class Users(models.Model): userid = models.AutoField(db_column='UserID', primary_key=True) # Field name made lowercase. username = models.ForeignKey('AuthUser', models.DO_NOTHING, db_column='Username', unique=True) # Field name made lowercase. ownedfridges = models.TextField(db_column='OwnedFridges', blank=True, null=True) # Field name made lowercase. friendedfridges = models.TextField(db_column='FriendedFridges', blank=True, null=True) # Field name made lowercase. personalnotes = models.TextField(db_column='PersonalNotes', blank=True, null=True) # Field name made lowercase. eff_bgn_ts = models.DateTimeField() eff_end_ts = models.DateTimeField() class Meta: managed = False db_table = 'Users' class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table … -
django.core.exceptions.ImproperlyConfigured: DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.?
I created an app called djecommerce. Got an error in urls.py saying ImproperlyConfigured here's the code from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the 6th line it showing the error near path In the wsgi.py it showing error of no module found 'djecommerce' near application word. Here's the code import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djecommerce.settings') application = get_wsgi_application() -
Issue with setting the context for Stripe Publishable Key in Django view.py
I am trying to set up stripe in Django. I have set up the context with the publishable_key and am calling the stripe payment screen with this context, but I still get the error "You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key. I've researched other examples and my code seems to be the way to do it, but I'm struggling with this now. def charge(request): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='gbp', description='A test charge', source=request.POST['stripeToken'], ) context = {'publishkey':publishkey} return render(request, 'charge.html', context) -
In django which model feilds is required for data which having comma like in csv file 1 colunm having multiple data i.e. French, Japanese, Desserts
I am creating CRUD api in django rest framework sqlite3 database. I want to create model for restaurant which having some feilds which is [Restaurant ID, Restaurant Name, Cuisines, Average Cost for two, Currency, Has Table booking, Has Online delivery, Aggregate rating, Rating color, Rating text, Votes] i have csv file which is already having data but which model feild is required for Cuisines because under Cuisines colunm having multiple list csv file rows and columns please check Cuisines column and what type of model feild is required for this column -
Why extending base HTML to other templates not wokring?
I have a base.html that I want to extend to other templates. I started with contact.html. But the weird situation is that the moment I extend the base.html in contact.html, I loose my form fields. To re-assure that I can re-produce the issue, I removed the {% extends 'base.html' %} from the contacts.html and refresh the browser, I could see my form fields again. I have no idea what's missing. Below is the base.html content. base.html {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap NavBar</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link href="{% static 'css/topics.css' %}" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="navbar navbar-expand-md navbar-dark bg-dark mb-4" role="navigation"> <a class="navbar-brand" href="#">Bootstrap NavBar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'BLOG:contact' %}" target="_blank">Contact</a> </li> <li class="nav-item"> <a class="nav-link disabled" … -
Django ORM to get annotated sum of related models records. (trying to use subquery in vain.)
I am currently building an image-based e-commerce website. Images are tagged with some products, and I need to get total revenue made from selling products tagged in each images. """ models.py """ class Image(AbstractImageModel): """ Images are linked to Product model via intermediary LiveProduct table. """ ... products = models.ManyToManyField( "catalogue.Product", through="ProductInImage", related_name="listed_images" ) ... class ProductInImage(TimeStampedModel): """ Intermediary model that connects Image with Products """ image = models.ForeignKey("images.Image", models.CASCADE) product = models.ForeignKey("catalogue.Product", models.CASCADE) class OrderLine(models.Model): """ An order line """ order = models.ForeignKey( 'order.Order', on_delete=models.CASCADE, related_name='lines', verbose_name=_("Order")) ... product = models.ForeignKey( 'catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_("Product")) quantity = models.PositiveIntegerField(_("Quantity"), default=1) ... line_price = models.DecimalField(_("Line Price"), decimal_places=2, max_digits=12) What I am trying to get is an Image.objects queryset, annotated with total revenue made from all products tagged on each image. I have been doing something similar to the following lines, but can't seem to get in working. # to use in subquery line_qs = OrderLine.objects \ .filter(product__id__in=OuterRef("product_pk")) \ .values("line_price_excl_tax") \ .aggregate(revenue=Sum("line_price_excl_tax")) # queryset that I need: must be annotated with revenue made from all products, for each image qs = Image.objects.all() qs = qs.annotate(revenue=Subquery(line_qs.values("amount"))) Thank you very much in advance; I really appreciate your help. -
How to filter a ManyToManyfield in Django View
Como filtrar as questões relacionadas com os usuários que façam parte da categoria correspondente? views.py questoes = Questao.objects.filter(idCategoria__in=[request.user.usuario.idCategoria]) models.py class Categoria(models.Model): idCategoria = models.CharField(primary_key=True) class Usuario(models.Model): idCategoria = models.ManyToManyField(Categoria) -
Problems with virtualenv when changing to another computer with Django and Postgresql
Warning: I am very new to Django. I did the following tutorial, which uses a SQLite database. I then created a postgresql database and changed the project so that it uses this instead. Everything works well when I am on a Mac: https://realpython.com/get-started-with-django-1/ There are 2 potential problems that may be linked. FIRST PROBLEM: When I run the Django Project, I keep getting an error message on the Mac saying: You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. After running 'python manage.py migrate' and then restarting the Django server, the message does not go away. This seems a bit weird but doesn't stop it from working. SECOND PROBLEM: I then check the code into GitHub. This excludes the virtual environment (venv) and the pycache files. I am using parallels. I have checked the IP address of the Mac and I can ping it from windows, so there shouldn't be any problems connecting to the database. I change the HOST setting in the setting.py file to point to the Mac. I install the code onto windows and try to recreate …