Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Publish a custom Django Flatpage at a set date and time
I have a custom Flatpage model: from django.contrib.flatpages.models import FlatPage class MyFlatPage(FlatPage): publish = models.DateTimeField() so that I can add a publish date in the future. Now, I don't have a proper list of flatpages on the front end, my use for frontpages is more like 'one-offs', where I specific the URL and all that. For example, 'about', '2019prize', 'Today's walk', stuff like that. How can I set these pages I create to be displayed only after the publish date has arrived? I know that I can filter them by looking up something like pages.(Q(publish__lte=now)). Where and how should I put that code though? -
django API, "Incorrect type. Expected pk value, received str."
my models class City(models.Model): city_name = models.CharField(max_length=40) def __str__(self): return self.city_name class Place(models.Model): place_city = models.ForeignKey(City, on_delete=models.CASCADE) place_name = models.TextField(max_length=40) place_available_slots = models.IntegerField(default=None, blank=True, null=True) def __str__(self): return "%s - %s" % (self.place_city, self.place_name) my serializers class PlaceUpdateSerializer(serializers.ModelSerializer): class Meta: model = Place fields = '__all__' my views: class PlaceUpdateAPI(APIView): def put(self, request): place = Place.objects.get(place_name=request.data.get("place_name")) serializer = PlaceUpdateSerializer(place, request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) and error is : { "place_city": [ "Incorrect type. Expected pk value, received str." ] } I tried to put data but here is the error. The place_city is a foreign key can someone guide me how to put data through API in Foreign Key. -
If page is unpublished go to the next available page
I'm creating a webcomic using Django. I have a status choice field in my model: 1 to publish a page and 0 to unpublish it. STATUS = ( (0,"Draft"), (1,"Publish")) I have created two functions: the first one to go to the previous page and the second one to go to the next page. def get_previous(self): previous = Page.objects.filter(status=1).get(number=self.number - 1) if previous.number > 0: return reverse('comic_page', args=[previous.chapter.slug, previous.number]) return None def get_next(self): last = Page.objects.filter(status=1).last() next = Page.objects.filter(status=1).get(number=self.number + 1) if next.number <= last.number: return reverse('comic_page', args=[next.chapter.slug, next.number]) return None It works as expected when all the pages are published, but when one of the pages is unpublished it doesn't go to the next available page but just refreshes the page. I tried creating another queryset with only unpublished pages and then checking if the page exists in that queryset and jumping 2 page numbers instead of 1 but it did not work. def get_previous(self): previous = Page.objects.filter(status=1).get(number=self.number - 1) unpublished = Page.objects.filter(status=0) if previous in unpublished: previous = Page.objects.filter(status=1).get(number=self.number - 2) return reverse('comic_page', args=[previous.chapter.slug, previous.number]) if previous.number > 0: return reverse('comic_page', args=[previous.chapter.slug, previous.number]) return None Any suggestions are appreciated, thank you! -
Change the extra field data in Many-to-many relationship in Django
I have a Many-to-many relationship with additional fields and I want to be able to change data in these fields (e.g. the status of friendship). How can I do that? All the info I found is about how to just read these data. class Profile(models.Model): # other fields friends = models.ManyToManyField("self", blank=True, through='Friendship', through_fields=('user', 'friend'), symmetrical=False, related_name='user_friends') class Friendship(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships1') friend = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships2') status = models.PositiveSmallIntegerField(default=0) class Meta: unique_together = [['user', 'friend']] I tried this and that didn't work, though no error was shown: user = User.objects.get(username=request.user) watched_user = User.objects.get(id=watched_user_id) Friendship.objects.filter(user=user.profile, friend=watched_user.profile).status = 5 user.save() I can't call Friendship.save() as it has no self. And also I tried this and again no effect and no error: user.profile.friends.set([watched_user.profile], through_defaults={'status': 5}) user.save() And this gives me an error that there's no friend field and shows me the fields of Profile, not Friendship: user.profile.user_friends.get(user=user.profile, friend=watched_user.profile).status=5 Please help me! -
On click event not working while creating chart on dynamic data using chart.js in javascipt
data table in frontend, data will show selecting range of date, we need to creating bar graph and show graph while clicking row like- total cars, active vehicles etc. I'm using Django framework -
Django Models data storing
it's my first time working with Django models, I need help with my project. I have created 1 model with only field experience, job type, salary. Now I want another model which stores the table fields. Can anybody please help me? -
Append header in a vue axios request
I have a django backend and a Vue 3 frontend. For handling some request, my backend needs an 'Id-Client' header in the headers of the request. Developing my BE everything worked like a charm, but now that I'm writing the FE I'm encountering some issues. As I said before, I need to append and header to my headers in every request. So the first step was the following: // Note that the idClient is dynamic and can change. this.$axios.setHeader('Id-Client', idClient) const data = await this.$axios.$get(url) But I can't get it to work, if I try to send that request, my get request becomes (I don't know why) a OPTIONS request and I get the error "cross origin resource sharing error: HeaderDisallowedByPreflightResponse" Instead if I remove the set header // this.$axios.setHeader('Id-Client', idClient) const data = await this.$axios.$get(url) The server just respond me correctly giving me the error that the request is missing the 'Id-Client' in the header. I also have a few request that don't need the 'Id-client' header and those request work, so I don't think is a CORS problem. -
set a global setting during django startup
The figure shows my django structure. I don't have a django app according to django glossary. When django starts, I want to load a system configuration, for instance query the value of DSHELL in /etc/adduser.conf, then save it to a place where view.py can access. How would I implement it? I tried the following options: I looked at Django settings, but it discourages altering values in settings.py at runtime. From what I understand, Django Applications is saying I need to have a django app in order to use AppConfig.ready() which sets something global settings. Unless my folder structure is very wrong, I don't want to change it or switch to a django app. I'm using django 3.1 on Linux. -
Why the form doesn't show field errors and submits the form blank or invalid?
I'm creating a form where a field has a regex validator. But when I submit a blank form, it doesn't prompt the user for required field or validation error. It just redirects the user to 'ValueError at /data/ The InitialData could not be created because the data didn't validate.' The Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/data/ Django Version: 3.2.4 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account'] Installed 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'] Traceback (most recent call last): File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Sonu\Projects\Billing\rough\account\views.py", line 10, in initialview fm.save() File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py", line 460, in save raise ValueError( Exception Type: ValueError at /data/ Exception Value: The InitialData could not be created because the data didn't validate. models.py: from django.db import models from django.core.validators import RegexValidator # Create your models here. class InitialData(models.Model): pattern = RegexValidator(r'OOPL\/D\/[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=12, blank=False, primary_key=True, validators=[pattern]) forms.py: from django import forms from django.forms import ModelForm, fields from .models import InitialData class TrackReportForm(forms.ModelForm): class Meta: model=InitialData fields='__all__' views.py: from django.shortcuts import render from .forms import TrackReportForm from .models import InitialData … -
Django/Python Validate Google Sign with backend server using Oauth2
I am trying to validate a google sign in from my android app with my Django Backend server. I am getting the following error File "/lib/python3.8/site-packages/google/oauth2/id_token.py", line 146, in verify_oauth2_token idinfo = verify_token( File "/lib/python3.8/site-packages/google/oauth2/id_token.py", line 126, in verify_token return jwt.decode(id_token, certs=certs, audience=audience) File "/lib/python3.8/site-packages/google/auth/jwt.py", line 275, in decode raise ValueError("Could not verify token signature.") ValueError: Could not verify token signature. google.py from google.auth.transport import requests from google.oauth2 import id_token from django.conf import settings class Google: """Google class to fetch the user info and return it""" @staticmethod def validate(auth_token): idinfo = id_token.verify_oauth2_token(auth_token, requests.Request(),settings.CLIENT_ID) #using this line to debug the error print(idinfo) try: idinfo = id_token.verify_oauth2_token(auth_token, requests.Request(),settings.CLIENT_ID) userid = idinfo['sub'] print(userid) except: return "The token is either invalid or has expired" What am I doing wrong? Please help. I am stuck with this issue for like 2-3 weeks now. -
I have imported the module but still shows ModuleNotFoundError: No module named 'router'
I am getting no router error but I have clearly imported the module from django.contrib import admin from django.urls import path,include from api import views from rest_framework import routers router=routers.DefaultRouter() router.register('api',views.SubscriberModelViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('',include('router.urls')), ] -
Django-rest-resetpassword not submitting new password into the database
I'm trying to implement password reset using Django-rest-resetpassword package. urls.py path('account/password-reset/', include('django_rest_resetpassword.urls', namespace='password_reset')), I followed the procedure in the website https://pypi.org/project/django-rest-passwordreset/ I'm able to send password reset message to the user email and the user recieves token. But the problem I'm having is that when I enter the token for the password confirmation the program tells me that it's successful but I'm not able to login with the new password. when I check the password reset table in the database nothing appears.The new password isn't entering Into the database. Am I missing any critical step? -
How to add images to each product variation in Django?
Hey guys I have these 2 models, class PrdtVariation(models.Model): prdt = models.ForeignKey(Prdt) size = models.CharField() color = models.CharField() class PrdtImage(models.Model): prdt = models.ForeignKey(Prdt) prdt_vr = models.ForeignKey(PrdtVariation) images = models.FileField(upload_to=get_img_path) I want to have images for each of the variation (not looping through every variations and adding the same images to all the variations) while creating the product, is this the correct model format for such a task? Like the 1st image uploaded should be related to the first variation, likewise. Can someone help with this? I have created this serializer create fn, but it just loops through all the variations and add the same images to every variation. variants = validated_data.pop('variants') images = self.context['request'].FILES.getlist('images') for variant in variants: prdt_variation = # create the variants for img in images: PrdtImg.objects.create(prdt=prdt, prdt_vr=prdt_variation, images=img) How to create a proper db table to and a function to accompolish such a task? Thank you -
Django forms IntegerField value validation
I create form with IntegerField. Is posibility to validate input values on it, from defined list? This is a API form, wich connect to another DB. It's not based on model in project. My form looks like that: from django.core.exceptions import ValidationError def validate_users(value): users_list = [10012, 16115, 10505] if value not in users_list: raise ValidationError('Wrong number') class PribilagesForm(forms.Form): mslk_module_choices = (('1', 'one'), ('2', 'two'),) workerId = forms.IntegerField(label='Nr. ewidencyjny', validators=[validate_users]) moduleName = forms.ChoiceField(label='Moduł', choices=mslk_module_choices) When I input value from out of range validate_users, and submit form, i got ValueError, not information about wrong insert value. -
How to get DJANGO obtain my dht11 or mlx90614 infrared reading sensor value on webpage?
I'm stuck at the moment, please give me a lead for dealing this matter !! I got the codes for both sensors, but I'm not sure how to connect it with the django framework... My idea basically is Sensor -> Raspberry pi -> Django -> Website -
Django DRF partial update array of objects
What's the most elegant method of doing a partial update of an object array using DRF? What I want to achieve is: Type validation, Class based view (UpdateAPIView), Object owner validation. models.py class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) short_desc = models.CharField(max_length=255, null=True, blank=True) serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' frontend $.ajax({ type: 'PUT', dataType:'json', data: {'arr_changes': arr_changes}, headers: { 'X-CSRFToken': "{{ csrf_token }}" }, url: "{% url "update_books" %}", success: function (data) { window.location.reload(); } }); output: [{ "id": 1, "title": "Book 1", }, { "id": 2, "title": "Book 2", "short_desc": "Lorem ipsum" }] views.py class UpdateArticle(APIView): authentication_classes = [authentication.SessionAuthentication] def get_object(self, obj_id): try: return Article.objects.get( id=obj_id, user=request.user ) except (Article.DoesNotExist, ValidationError): raise status.HTTP_400_BAD_REQUEST def put(self, request, *args, **kwargs): ---- partial update with serializer ---- What is the best and easiest way to do it? -
Django Model Forms ( Template Doesn't Exist)
I'm working on Django model forms. I have created forms.py and added the following: from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price' ] And I have rendered this out in my views.py as it follows: def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "products/product_create.html", context) and I have added urls.py: from django.contrib import admin from django.urls import path from pages.views import home_view , contact_view, about_view, social_view from products.views import product_detail_view, product_create_view urlpatterns = [ path('', home_view, name='home'), path('contact/', contact_view), path('admin/', admin.site.urls), path('about/', about_view), path('create/', product_create_view), path('product/', product_detail_view), path('social/', social_view), ] I have migrated everything and saved all files, but when I want to go to my create URL, I get this error: TemplateDoesNotExist at /create/ products/product_create.html Request Method: GET Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: products/product_create.html Exception Location: C:\Users\Invoker\dev\trydjango\env\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Invoker\dev\trydjango\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Invoker\\dev\\trydjango\\src\\sadra', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\Invoker\\dev\\trydjango\\env', 'C:\\Users\\Invoker\\dev\\trydjango\\env\\lib\\site-packages'] Server time: Wed, 23 Jun 2021 08:20:29 +0000 I have created a template as well: {% extends 'base.html' %} {% … -
Testing ASGI Django
We have been developing our REST API with Django and Django-rest for some time, and we are using Django-behave for the integration test which seems to use django.test runner to run the tests. However, we have switched from Django 2.2 to 3.2 to support async calls as we have many I/O calls to other components. We use gunicorn/uvicorn in production as our ASGI server and in production, everything seems to run nice and smoothly. But the behave tests which we use in our pipeline (Gitlab CI) started to fail - to be specific: views don't return response from time to time (all code gets executed just fine, and it just gets stuck on return Response() and the request timeouts for the client). We suspect that it's because behaves uses WSGI and not ASGI server to run our Django instance... so the question is... can we run behave with ASGI server, can we specify django.test runner, to run as ASGI? -
Django - Unable to test with two databases (postgres with gis extension and mongoDB (Djongo)
I'm not able to test two databases using Django's unittests. My databases configuration: DATABASES = { 'default': {}, 'postgres': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': "<name>", 'USER': "<user>", 'PASSWORD': "<pass>", 'HOST': "localhost", 'PORT': 5432, }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '<name>', 'ENFORCE_SCHEMA': True, } } my simple test: from django.test import TestCase class TestFormModel(TestCase): databases = {'postgres', 'mongodb'} def test_generate_persistent_data_indexes(self): assert True Error that I'm getting: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' I migrated both databases When I set postgres database as a default I'm getting: self = <django.db.backends.utils.CursorWrapper object at 0x1132de580> sql = 'SELECT "user_userdata"."id", "user_userdata"."user_profile", "user_userdata"."data", "user_userdata"."is_persistent" FROM "user_userdata" ORDER BY "user_userdata"."id" ASC', params = () ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x112d96f70>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x1132de580>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E django.db.utils.ProgrammingError: column user_userdata.data does not exist E LINE 1: ...r_userdata"."id", "user_userdata"."user_profile", "user_user... E ^ venv/lib/python3.8/site-packages/django/db/backends/utils.py:84: ProgrammingError My MongoDB model: class UserData(djongo_models.Model): id = djongo_models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_profile = djongo_models.UUIDField() data = djongo_models.JSONField(default={}) is_persistent = djongo_models.BooleanField(default=False) objects = djongo_models.DjongoManager() -
django form filter field queryset
How do I filter form's field queryset? After a little search I found that this way it's done. But I am getting an error here. class TbPeopleEntranceRightForm(forms.ModelForm): def __init__(self, user=None, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) print(self.user) self.fields['user'].queryset = self.user class Meta: model = TbPeopleEntranceRight fields = ['user', 'area', 'room'] 'TbUser' object has no attribute 'all' -
You are trying to add a non-nullable field 'post' to stream without a default; we can't do that
I have models.py class Stream(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stream_following') user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() and function def add_post(sender, instance, *args, **kwargs): post = instance user = post.user followers = Follow.objects.all().filter(following=user) for follower in followers: stream = Stream(post=post, user=follower.follower, date=post.posted, following=user) stream.save() when I'm trying command py manage.py makemigrations I have an issue. You are trying to add a non-nullable field 'post' to stream without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: How to solve that? I put on default smth. However in function add_post I have added date=post.posted Thanks! -
Add a date picker to an already existing html form with Django
I have this template that i use for my Django app : <head> <meta charset="utf-8"> {% load static %} <link rel="stylesheet" href="{% static 'GenerateXL/form.css' %}"> <title> app title </title> </head> <body style="margin-top: 30px; margin-left: 30px;"> <h1 style="text-align:center"><span style="font-family:Georgia,serif"><span style="color:#006600"> django app </span></span></h1> <div class="wrapper"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="left"> <h3> import file <h3> <br> <input type="file" title="Upload SPORT" name="sport" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" name="sportt" style="border: 1px solid green; padding: 5px; border-radius: 2px; cursor: pointer;"> </p> **<!-- I would like to add a datepicker -->** </div> <div class="right"> <h3> Authenticate <h3> <div class="wrapper"> <div class="left"> <h5> Connect to proxy : <h5> <input type="text" title="Id_proxy" name="nnn" placeholder="nnn" style="border: 1px solid black; padding: 5px;" required="required"> <input type="password" title="Password_proxy" name="MDP_proxy" placeholder="mot de passe proxy" style="border: 1px solid black; padding: 5px;" required="required"> </div> <div class="right"> <h5> Connect SP : <h5> <input type="text" title="Id_Sharepoint" name="Login_sp" placeholder="Login Sharepoint" style="border: 1px solid black; padding: 5px;" required="required"> <input type="password" title="Password_sharepoint" name="MDP_sp" placeholder="mot de passe Sharepoint" style="border: 1px solid black; padding: 5px;" required="required"> </div> </div> </div> </form> </div> I want to add a date picker (actually two of them) in the specified location in the code, the dates would then … -
Given a particular id of a model object how to extract all details of its many to many field in Django?
my models.py class ChapterNames(models.Model): chapter_names = models.CharField(max_length=100, unique=True) def __str__(self): return self.chapter_names class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_ids = models.ManyToManyField(ChapterNames) chapter_details = models.TextField(default='') mentor = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True) isDraft = models.BooleanField(default=True) ratings = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_details Here chapter_names has been added as many to many field and i want to extract all details chapter names given a particular id of liveclass_details model my views.py def ChapterNames(request, id): liveclass_id = models.LiveClass_details.objects.filter(id=id) print(liveclass_id.values_list('chapter_names')) pass Here i amdoing something like this but is again giving me a queryset of chapter__ids please help me acheiving it , thanks in advance -
What should I choose Django or Node.js
I want to do Web Development and I have covered the frontend part and I'm going to the backend part. So, which language should I choose Django or Node.js? I already know the basics of Python and its libraries like Numpy, Pandas, Matplotlib. And if I will choose JavaScript I can be a MERN Stack developer but I don't know the "J" of javascript what should I do? And I want to do some data science and machine learning later. Help Me -
dynamic URL routing in Django with React
I am building an E-Commerce site. My requirement was I want to change the domain based on user visiting location(IP/any other media). ex: if a user visits my website from the USA the domain should be: domain.com/usa. or else a user visits my website from India my domain should be: domain.com/india. How can I implement this type of logic in Django? Technologies I am using: Django with React.