Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS RDS rename database name
I have a database created with RDS and I want to rename it. But whenever I try to modify it through the AWS console, the option for the database name is gone. And when I try it through the shell, it's showing an error. I just need to rename the DB name from postgrestestdatabase to a new one. -
403 Error "Authentication credentials were not provided" in Safari, but not in Chrome, Edge, Firefox, etc. [Django + Next.js]
Currently i'm having problems running my page in Safari and iOS devices (even with chrome browser). The main problem is that Safari is returning 403 errors in some endpoints, but the token was sent and this is only happening in this browser. For example: get_quantites enpoint with status 200 -
How to filter based on another model in Django ModelViewSet?
I currently have a SiteViewSet using ModelViewSet that can list, retrieve, create, and update sites from the model Site. I want to add a filter to the same SiteViewSet that lists all the site objects where is_active is True - but this condition is based on the AdminConfiguration model. I was not able to find how to implement a filter in ModelViewSet based on conditions of another model. Is the filtered endpoint /v1/site/?is_active=True possible to implement in the same SiteViewSet with ModelViewSet or should I create a separate view via a more flexible APIView? SiteViewSet: class SiteViewSet(viewsets.ModelViewSet): model = Site lookup_field = 'uuid' pagination_class = PageNumberPagination serializer_class = SiteSerializer queryset = Site.objects.all() Site Model: class Site(models.Model): uuid = models.UUIDField( default=uuid.uuid4, unique=True) domain_name = models.CharField(max_length=255, unique=True) AdminConfiguration Model: class AdminConfiguration(models.Model): site = models.OneToOneField( Site, on_delete=models.CASCADE) always_active = models.BooleanField(default=False) subscription_ends = models.DateTimeField( default=set_default_expiration) @property def is_active(self): active_status = self.always_active or self.subscription_ends > timezone.now() return active_status -
When deploying updated Django code on server, the database resets
I have built an app built which uses Django as Rest API (Django rest framework). After having deployed the code on digital ocean using production grade services, everything works well. The database populates itself correctly . There is no reset of the server like on Heroku. Except, if I change a file and push the changes through gitlab which are then picked up by Digital ocean who automatically deploy the updated version of the server), the database resets to its original state. I have removed all migration files before pushing updates, but to no avail. I imagine it has to be something rather trivial but I can't find it. this makes it impossible for me to go into production -
why unable to import a model in django (most likely due to a circular import)?
I am working on a small application for learning purpose, and created a three models CustomUser, UserProfile and PollQuestion. CustomUser and UserProfile having OneToOne field. And UserProfile and PollingQuestion having ForeignKey relation between them, i am also posting and code snippet bellow:- CustomUser And UserProfile models:- from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from polls.models import PollQuestion # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False, unique=True) password = models.CharField(max_length=15, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def get_all_polls(self): all_polls = PollQuestion.objects.all().count() return 10 PollingQuestion:- class PollQuestion(models.Model): question = models.TextField(max_length=250) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) option_one = models.CharField(max_length=250, null=False) option_two = models.CharField(max_length=250, null=False) option_three = models.CharField(max_length=250, null=False) option_four = models.CharField(max_length=250, null=False) option_one_votes = models.IntegerField(default=0) option_two_votes = models.IntegerField(default=0) option_three_votes = models.IntegerField(default=0) option_four_votes = models.IntegerField(default=0) When i tried to run the command python manage.py makemigrations got following error:- Traceback (most recent call last): File "C:\Users\akcai\OneDrive\Desktop\deep_stuffs\PollingApplication\manage.py", line 22, in <module> main() File "C:\Users\akcai\OneDrive\Desktop\deep_stuffs\PollingApplication\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_li ne utility.execute() File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", … -
How can I cast a DateField() + TimeField() to local time in a Django QuerySet?
My model as these fields: date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() I would like to annotate the queryset with start_datetime and end_datetime, like so: class SessionQuerySet(models.QuerySet): def with_datetimes(self): return self.annotate( start_datetime=ExpressionWrapper( F('date') + F('start_time'), output_field=models.DateTimeField() ), end_datetime=ExpressionWrapper( F('date') + F('end_time'), output_field=models.DateTimeField() ), ) However, the output field in the query results in a naive datetime: >>> Session.objects.with_datetimes()[0].start_datetime <<< datetime.datetime(2021, 9, 20, 17, 0) I tried wrapping the above expressions in django.db.models.functions.Cast(), with output_field=DateTimeField(), but it casts to UTC and not the local timezone. Essentially what I need is the equivalent of the Postgres at time zone feature to convert a naive time to localtime. Is there a way to do that in Django? -
Django Admin Login --> Redirect on Login to another Page
Good evening, I am currently trying to solve a problem with Django Admin. I want to do this steps: 1.) If I visit localhost:8000/admin --> the Admin Login appears 2.) If I log in with credentials --> it should redirect me to localhost:8000/test_page and not to the localhost:8000/admin page. 3.) If I revisit localhost:8000/admin while I am logged in, it should show me the admin page. I was already looking in /python3.x/dist-packages/django/contrib/admin/sites.py but couldn`t find the code piece to make 2.) and 3.) work. Anyone got an idea or could help me ? Thanks :) -
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)