Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React and Django app won't update changes unless I clear all my browsing data
I'm creating a react and django app. I have an issue where sometimes the only way changes I've made in the code actually get implemented on the website is if I go into chrome settings and clear all browsing data. Other things like... refreshing the page killing both the server run from "python manage.py runserver" and "npm run dev", then then restarting them in the terminal again ... don't update the changes. My question is what do I need to change (probably some setting or putting in some piece of code) so that I don't have to clear my browsing data every time. -
Django How to send signals for add or remove user from group?
I am trying to use signals for add and remove user from groups but I am not understanding where I am doing wrong. here is my code: @receiver(post_save,sender=settings.AUTH_USER_MODEL) def group(sender,instance,created,**kwargs): group = Group.objects.get(name='myauthors') if instance.is_blog_author == True: instance.groups.add(group) elif instance.is_blog_author == False: instance.groups.remove(group) -
how to get a record via the ManyToMany link
I want to get the email of the restaurant through the order model. How can I do this? My models.py: class Order(models.Model): cart_meal = models.ManyToManyField(CartMeal, null=True, blank=True) class CartMeal(models.Model): meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) class Meal(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) class Restaurant(models.Model): email = models.EmailField() I need to get to restaurant.email via order. I tried to do it this way, but it doesn't work: order.cart_meal.model.meal.restaurant.email -
How to redirect login with Allauth in Python/Django?
Im working with Python and Django. I have a manual registration/login, and also I've installed with Allauth a Gmail registration/login. When the user logins (with the manual login I created), it automatically executes a view which shows the differents things the user can do and information related to the user. The url is: http://127.0.0.1:8000/dashboard/9 screen capture here In relation with Gmail, the user can register and login. But, when it logins, sees the url http://127.0.0.1:8000/accounts/google/login/callback/?(...), which confirms it is logged in. screen capture here I understand I should create a view in the social_app app, in order to connect the Gmail user with the information in the database. Any ideas? Thanks! -
KeyError: 'id' django-import-export
I don't know where it is wrong, right in my code, please help I already wasted lot of my time... THANK YOU _/\_ admin.py from import_export import resources from import_export.admin import ImportExportModelAdmin class CapabilityResource(resources.ModelResource): model = Capability skip_unchanged = True report_skipped = True exclude = ('id',) import_id_fields = ('capscode', 'capsid', 'capsname', 'cfor', 'parent',) @admin.register(Capability) class CapabilityAdmin(ImportExportModelAdmin): resource_class = CapabilityResource fields = ['capscode', 'capsname', 'cfor', 'parent'] list_display = ['capscode', 'capsname', 'cfor', 'parent'] list_display_links = ['capscode', 'capsname'] models.py class Capability(models.Model): CFOR_CHOICES = [('WEB', 'WEB'), ('PORTLET', 'PORTLET'), ('REPORT', 'REPORT'), ('MOB', 'MOB')] capsid = models.AutoField(primary_key=True, auto_created=True, editable=False) capscode = models.CharField(_('caps'), max_length=50) capsname = models.CharField(_('includes'), max_length=1000, default = None, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.RESTRICT, db_column='parent', null=True, blank=True, related_name='children') cfor = models.CharField(_('cfor'), max_length=10, default='WEB', choices=CFOR_CHOICES) clientid = models.ForeignKey('onboarding.Bt', null=True, blank=True, on_delete = models.RESTRICT, db_column='clientid') csv data: capscode capsid capsname cfor parent NONE 1 NONE WEB DASHBOARDS 2 DASHBOARDS WEB 1 RP_MONITORING 3 RP MONITORING WEB 2 FACILITY 4 FACILITY WEB 2 versions: django-import-export==2.6.0 Django==3.2.4 python=3.8.10 Errors: Line number: 1 - 'id' NONE, 1, NONE, WEB, Traceback (most recent call last): File "/home/xyz/abc/envs/intelliwiz_env/lib/python3.8/site-packages/import_export/resources.py", line 650, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/xyz/abc/envs/intelliwiz_env/lib/python3.8/site-packages/import_export/resources.py", line 342, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/home/xyz/abc/envs/intelliwiz_env/lib/python3.8/site-packages/import_export/resources.py", line 329, … -
Django dynamically added forms - '<' not supported between instances of 'NoneType' and 'int'
I'm currently creating a site in Django which allows a user to enter in the details of a recipe they want to create and save it. This means the user needs to be able to dynamically add formset fields for things like ingredients and the steps of the recipe. I have implemented a way to dynamically add these fields using Javascript, but currently it only works with can_delete_extra and can_delete in the formset set to False, which I need to change because a) I don't want a delete checkbox to display on the formset forms when a recipe is being created (I have looked in to hiding this with no luck) and b) the user needs to be able to delete fields they don't want when they edit a recipe later on. The error message I'm being displayed is: '<' not supported between instances of 'NoneType' and 'int', occurring in: Desktop\recipe_site\recipe_env\lib\site-packages\django\forms\formsets.py, line 416, in add_fields. The following is my code. The Javascript is based on this post. create_recipe.html <h2>Ingredients</h2> {{ iformset.management_form }} <div id=ingredientform> {% for i_form in iformset %} <div class = ingredientinfo> {{ i_form.as_p }} </div> {% endfor %} </div> <input type="button" value="Add More" id="add_more_ingredients"> <script> let ingFormCount … -
How to render a foreign key field in Django
# Models class Vote(models.Model): """ A Class for Votes made by Users for a specific Poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) def __str__(self): return f'Vote by {self.user}' class PollerComment(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment') user = models.ForeignKey(Account, on_delete=models.CASCADE) vote = models.ForeignKey(Vote, on_delete=models.RESTRICT, default=1) created_on = models.DateTimeField(auto_now_add=True) comment = models.TextField(max_length=350) def get_vote(self): """ Get the vote made to the Poller of the user who commented """ self.vote_made = '' if self.vote.poller_choice_one_vote: self.vote_made = 'One' else: self.vote = 'Two' return self.vote_made # View @require_GET def render_single_poller(request, poller_id): # Retrieve comments comments_qs = PollerComment.objects.filter(poller_id=poller_id) context = { 'comments_qs': comments_qs, } return render(request, 'pollboard/single_poller.html', context) # Template {% for comment in comments_qs %} <div class="comment-choice">{{ comment.get_vote }}</div> {% endfor %} I'm trying to render the Vote a user made to his PollerComment which are linked via a ForeignKey field. I tried to apply a Model method in the template but somehow it doesn't render anything and neither is an Error raised. I am not sure if I have significantly complicated a simple thing here. -
Swift Upload image to Django Rest Framework
I have Django 3.2 backend with Imagefield tested on Admin Page working fine I can upload image. tested on Postman and its working fine I can upload image. when I try to upload from swift I got invalid_image I am Taking UIImage and converted using pngData and send it in URLSession: param["src"] contains UIImage let paramSrc = param["src"] as! UIImage if let fileData = paramSrc.pngData()?.base64EncodedString() { body += "; filename=\"myImg.png\"\r\n" body += "Content-Type: image/png\r\n\r\n\(fileData)\r\n" } I also try without base64EncodedString so it will be less size and still getting same error -
how to post data in django rest in a model that has Jsonfield
I have a task to create a simple post API to send a visitor messages through a contact form that contain fields like full_name,address,phone etc. But instead of creating a model, I have to use an already existing model which has a Jsonfield. Now what I need to do is to use that jsonfield which will have all the fields like name, address etc. class Core(models.Model): """ Model that saves the corresponding credentials for the slug. """ slug = models.CharField(max_length=255, null=False) example = models.JSONField(null=False, default=dict) def __str__(self) -> str: return self.slug If it was done in a regular way by creating a model, it would have been like this. class Contacts(models.Model): full_name = models.CharField(max_length=100,blank=True,default="") email = models.EmailField() phone = models.CharField(max_length= 16) address = models.CharField(max_length=255,blank=True,default="") message = RichTextField() def __str__(self): return self.email Now, how should I send these fields data in a dictionary without in that JsonField without creating a Contacts model? -
How to create a sharable Django repository on Github
Having trouble creating a Django repository on Github that everyone can use? I tried pushing the entire virtual environment at first, found out that it doesn't work like that, then I tried just pushing the Django folder, but even the manage.py is looking for a path that only exists on my PC. How can I push the Django project, so that my group members can pull it, work on it, test it, and be able to push their changes themselves? Do we all have to be using the same virtual environment? -
ModuleNotFoundError: No module named 'mysite' django application
Good morning, I have read other similar posts but I still cannot solve my problem. Could anyone point out to me into the right direction? From one moment to another I started getting the following error. I have not made any changes to the settings.py file. The last feature that I installed, was the Django avatar package which has been running without problems. The error that I get is the following: " ModuleNotFoundError: No module named 'mysite'" Settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-oqv&!@ek#@_p9d#_oe3uxyrm-k&pvht4fm6xlk1o53hxib4k+o' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'simple_investing.apps.SimpleInvestingConfig', 'django.contrib.admin', #Admin site 'django.contrib.auth', #An authentication system. 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', 'avatar', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such … -
Check that the object_list contains the given word
My main goal is to change the color of the text if there is a specific word on the object_list, in this case, "S///" so the text should be red, not green. I used the django documentation but I don't know why it doesn't work How is object_list looks like {% if "S///" in object_list %} <a style="color: red;">Second breakfast</a><br> {% else %} <a style="color: green;">Second breakfast</a><br> -
nginx certbot doesnt redirect to django server
Im trying to set-up SSL sertificate for Django. I set up it by this guide: https://www.youtube.com/watch?v=dYdv6pkCufk&ab_channel=TonyTeachesTech, in the guide django server just start working with SSL, but for me is not working, but rederecting domain from http to https, but not redirecting to django server. I dont even know what to do. I search in entire internet and find nothing. This is my nginx config: server { listen 80 default_server; server_name _; return 301 https://$host$request_uri; } server { server_name wavera.ru www.wavera.ru; # managed by Certbot return 301 https://$host$request_uri; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.wavera.ru/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.wavera.ru/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }server { if ($host = wavera.ru) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.wavera.ru) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 ; server_name wavera.ru www.wavera.ru; return 404; # managed by Certbot } i starting server by python3 manage.py runserver -
After creating user order while verifying the payment and redirecting user to the page it give me this error
code 400, message Bad request version ('zz\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93ÚÚ\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00') You're accessing the development server over HTTPS, but it only supports HTTP. -
trying to print python function output in html page using django
enter image description here here -
Nothing showed up when looping dict items on Django Python
I have a json dict that store my values: [{'serial': 'DKFU-V7ZE-RD9R'}, {'serial': 'HKDR-SX7Z-29KR'}, {'serial': 'VSW9-XD3Q-GZ2W'}] I tried to display all the key and value to a table on my django template but it doesnt showed anything. My Html: <div class="col-md-5 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Available Minis Serial Code</h4> <div class="list-wrapper pt-2"> <ul class="d-flex flex-column-reverse todo-list todo-list-custom"> {% for key, value in item_list.items %} <li> <div class="form-check form-check-flat"> <label class="form-check-label"> {{ forloop.counter }}. {{ key }} : {{ value }} </label> </div> </li> {% endfor %} </ul> </div> </div> </div> </div> My views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages import urllib.request from urllib.error import HTTPError import json # Create your views here. def index(request): return render(request,'AlertTraceApp/hi.html') def send(request): if request.method == 'POST': .... EmptyMiniSerial = [{'serial': dct['serial']} for dct in resp_dict2 if (dct['subject']) == None] #getting the serial value only print(EmptyMiniSerial) status_code = response.status if status_code == 200 or status_code == 201 or status_code == 204 : # request succeeded context = { 'item_list': EmptyMiniSerial, } return render(request, 'AlertTraceApp/mainpage.html', context) else: messages.error(request, 'username or password not correct') Does my syntax have any errors? When I run my app it doesn't showed me … -
Django form with repeated fields
I need to a django form with some fields unique (id_station and station name) and the fields: sensor_unity, id_sensor and sensor_name repeated. When form is loaded there are these fields and near the fields sensor_unity, id_sensor and sensor name there is a link to add another row of the same fields. I tryied with this tutorial: https://www.codementor.io/@ankurrathore/handling-multiple-instances-of-django-forms-in-templates-8guz5s0pc but my code doesn't work because I receive the error: ValueError: The view station.views.new_station didn't return an HttpResponse object. It returned None instead. [20/Sep/2021 18:00:16] "GET /station/new_station/ HTTP/1.1" 500 69039 This is my code: models.py from django.db import models nr_unities = [(x, x) for x in range(1, 10)] class Station(models.Model): id_station = models.IntegerField(blank=False) station_name = models.CharField(max_length=30, blank=False) units_number = models.IntegerField(choices = nr_unities, blank=False) nr_sensor_unity = models.IntegerField(blank=False) id_sensor = models.IntegerField(blank=False) sensor_name = models.CharField(max_length=50, blank=False) def __str__(self): return self.name forms.py from django import forms from .models import Station nr_unities = [(x, x) for x in range(1, 10)] class StationForm(forms.ModelForm): class Meta: model=Station fields = ['id_station'] #, 'station_name', 'units_number', 'nr_sensor_unity', 'id_sensor', 'sensor_name'] widgets = { 'id_station': forms.IntegerField(), 'station_name': forms.CharField(), 'units_number': forms.ChoiceField(choices = nr_unities), 'nr_sensor_unity': forms.IntegerField(), 'id_sensor': forms.IntegerField(), 'sensor_name': forms.CharField(), } id_station = forms.IntegerField(label='id della stazione') station_name = forms.CharField(label='nome della stazione', max_length=30) units_number = forms.ChoiceField(label='numero unita', choices … -
Get the boolean which values True within a model that contains two (x) booleans
I'm curious if (actually how) my below approach could be simplified. # Model class Vote(models.Model): """ A Class for Votes made by Users for a specific Poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) def __str__(self): return f'Vote by {self.user}' # View @require_POST def submit_comment(request, poller_id): form = PollerCommentForm(request.POST) # Get the choice made by the user of the request user_vote = Vote.objects.get(poller=poller_id, user=request.user) # Check booleans vote_one = False if user_vote.poller_choice_one_vote: vote_one = True [..] Is there a more "django-way" to make this a one-liner to get the field which is True in the view? (e.g. if there would be multiple fields to check. Note: only one will be true) -
How to set a daily id for a model in django
I have a model which people use its id to remember a record for later use. But as the id is getting bigger and bigger, it's getting harder for people to remember that large number. So i thought a short and daily version of that id is needed. That number should start from 1 everyday and having the short id and a date should give the right record. So i thought of adding an AutoField to model and reset it to start from 1 everyday. How can i implement that? If you think it is not the right way to implement that functionality, what do you suggest? -
heroku and django: heroku stop the function before it done
I deployed a "django" app on "heroku" and I have a function (inside views) in my app that take some time (3m-5m) before it make a return. the problem is: - when I deployed my app on "heroku" the function didn't make a return, I tested my app on my pc and it work fine. "heroku" not telling me any thing in logs there is no 'timeout' or anything. -
query django model with same modelfields
so i have this django model class terrain(models.Model): location=models.CharField(max_length=200) size=models.CharField(max_length=200) def __str__(self): return str(self.location) how do i get the location of diffrent terrains having the same size ,i used the filter but i have to specify the size for example data=terrain.objects.filter(size="big") can't i do this without specifying the size just by pasing the size field -
Django, Mysql Docker Project can't connect to database
My docker file is as below : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app COPY requirements.txt /app/ WORKDIR /app RUN pip3 install -r requirements.txt COPY . /app EXPOSE 8082 CMD ["python", "manage.py", "runserver", "0.0.0.0:8082"] And here is my db definitions in settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'knowledge_base_py', 'USER': 'root', 'PASSWORD': 'root' } } I run mysql separately outside a docker container because I want to use AWS RDS as a database in the production. When I run the docker run command, I receive a "django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)")" error. What should I do? -
Get the user instance from a profile model
Hella everyone, Alright I'm building an ecommerce website and stuck at a certain point, I got two models Seller and Product, as follows: class Seller(models.Model): seller = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=30) country = models.CharField(max_length=30) phone_number = PhoneNumberField() email = models.EmailField(max_length=300) def __str__(self): return self.seller.username class Product(models.Model): STATUS_CHOICES = [ ('New', 'New'), ('New', 'Used'), ] image = models.ImageField(default='dev1.jpg', upload_to='images/') condition = models.CharField(choices=STATUS_CHOICES, max_length=10) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() price = models.CharField(max_length=15) location = models.CharField(max_length=30) posted_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Now I have a form to save new Product as: class SellProductForm(forms.ModelForm): class Meta: model = Product fields = ('image', 'condition', 'title', 'description', 'price', 'location', ) The problem is in views.py: @login_required def sell(request): form = SellProductForm() if request.method == 'POST': form = SellProductForm(request.POST) if form.is_valid(): print('Ok') instance = form.save(commit=False) instance.seller = request.user instance.save() return redirect('index') context = { 'form': form, } return render(request, 'myapp/sell.html', context) At the end, I get the ERROR: "Product.seller must be a Seller instance." I understand the demand but I can't get myself to imagine the code and come up with a solution, for I'm giving it a User instance not a seller instance. -
Django vs ASP.NET is faster for a website with more than 5 millions pages
I want to create a website with millions of pages that only contain text like Google scholar. I have background knowledge in Python but I don't have any experience in asp.net. I want to know which language is faster and easier to create this website? -
How to avoid THOUSAND SEPARATOR in certain views in django?
I am using Django's THOUSAND SEPARATOR in the settings.py file for the entire project but due to this whenever the IDs of objects get greater than 1000 in my views e.g: 1200, they are read as 1.2 . How to avoid the THOUSAND SEPARATOR for certain views?