Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's dbshell and sqlmigrations
The output of the initial default sqlmigrate from Django works when running it with manage.py but applying the output of sqlmigrate does not work with sqlplus [the default for manage.py dbshell]. When creating triggers (e.g) select count from user_sequences loop is terminated by a /; could this be the issue? I've searched through the source code but cannot understand how Django is applying these differently than using its shell and sqlmigrate. -
How to slove a MultiValueDictKeyError in Djangos Rest API upload?
I am currently setting up a file upload with React for the frontend and Django for the backend. I want to upload a file and some jason data. When submitting the data to my django backend i get the following error message: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'data' The error message refers to 'data' in the utils.py file, wehere I define my multipart parser. models.py (Django) class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',null=True, validators=[validate_file_extension_audio]) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) serializers.py (Django) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = '__all__' A MultiPartParser is used to pass file + data. api.py (Django) class StoryViewSet(viewsets.ModelViewSet) (Django): serializer_class = StorySerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Story.objects.all() permission_classes = [ permissions.IsAuthenticated ] def perform_create(self, serializer): serializer.save(author=self.request.user) utils.py (Django) class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # find the data field and parse it data = json.loads(result.data["data"]) qdict = QueryDict('', mutable=True) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) In actions story.js (React) import axios from "axios"; import { tokenConfig } from './auth'; import { createMessage, returnErrors } from "./messages"; import {ADD_STORY} … -
set django setting django-graphql-jwt samesite options
I'm trying to make an authentication system for my react front-end i want to use cookie authentication for it but i cant set cookies SameSite attribute i couldn't find anything on package's site isn't there any setting for it ? https://django-graphql-jwt.domake.io/en/latest/settings.html like that ? """JWT_COOKIE_SECURE = True""" Can anyone help me ? -
Django: strange filtering Database for None-Values behaviour
I'm facing a very strange situation when making a Database Request from Django. I have a model, chat, wich has a field named expired, which can be null. The goal is to filter all the elements from the Chat-Database where expired is not None. Running the following quick test: for chat in Chat.objects.all(): print(chat.expired is None) gives me: True True True True True False So there are Chat-objects which expired-fields are not none. But when filtering: print(Chat.objects.filter(expired__isnull=False)) it gives me: <QuerySet [<Chat: 1, type: G>, <Chat: 2, type: G>, <Chat: 3, type: G>, <Chat: 4, type: G>, <Chat: 5, type: G>, <Chat: 6, type: P>]> while the following: print(Chat.objects.filter(expired__isnull=True)) gives: <QuerySet []> Both Query outputs cant be right, since in the first test we can see that there are 6 Chat-objects, not all with expired-fields set to None, but the first Query gives six Elements. The second gets Zero, although there are elements with expired-fields to None. What is the Problem? Thanks in Advance! Edit The Model: class Chat(models.Model): TYPE_CHOICES = [ ('P', 'private'), ('G', 'group'), ] name = models.CharField(max_length=100, default="private") type = models.CharField(max_length=2, choices=TYPE_CHOICES, default='P') image = models.ImageField(null=True, blank=True) expired = models.DateTimeField(null=True, blank=True) -
serialize model to use with Chart.js in Django
even though I have seen a lot of resource about similar topics, nothing has been to solve my issue. the closest were How do I JSON serialize a Python dictionary? and django model serialization. I am trying to plot a model on my frontend with Chart.js and I cannot get my view to be serialized yet being able to fit the arguments for the graph to know what needs to be plotted. I attach my model.py, view.py and htlm page as well as the error that I get. models.py class Classification(models.Model): Class = models.CharField(max_length=10, primary_key=True) inventory_dollars = models.FloatField(default=0) def __str__(self): return self.Class class ClassificationSerializer(serializers.ModelSerializer): class Meta: model = Classification fields = "__all" views.py class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard/charts.html', {}) class ChartData(APIView): authentification_classes = [] permission_classes = [] def get(self, request, format=None): labels = Classification.Class default_items = Classification.inventory_dollars data = { "labels" : labels, "default": default_items } return HttpResponse(json.dumps(data), content_type = 'application/javascript; charset=utf8') html {% extends 'dashboard/base.html' %} <script> {% block jquery %} var endpoint = '/api/chart/data' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data1){ labels = data1.labels defaultData = data1.default setChart() }, error: function(error_data){ console.log(error_data) }} ) function … -
How to render a js function that comes from django view as str?
I'm trying to implement a payment api to my django project. The api returns a dict when i send a request. The content of dict is like that; ...'checkoutFormContent':'<script type="text/javascript">if ...</script>'... How to render this js function in my template? -
Django - How to capture & record selected images
I am trying to filter out inappropriate images using a visual interface. Inappropriate images are subjective, which is why I want a user to select only the appropriate images (selecting multiple at a time) and press 'Finish' once selection is complete. The user's inputs should be stored in the database similar to this: user_x = image1, image2, image4 ...... user_y = image6, image2, image3 ...... . . Here's what it currently look's like: Image Filtration I am a complete beginner to Django and I am not sure how to do this. Any help would be greatly appreciated. filter.html (Template to display images) <div class="container-fluid my-container"> {% filter_images_normal 3 as images %} <div class="row no-pad display-flex my-row"> {% for image in images %} <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col"> <input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}"> </div> {% endfor %} </div> <button type="button" class="btn btn-primary btn-lg btn-block">Finish</button> </div> filter_images.py (template tag to select distinct random images from folder) @register.simple_tag def filter_images_normal(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_filter/images/normal/' path = '/app_filter/static/app_filter/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] # print(random.sample(files, count)) print(rand_dir) return [rand_dir … -
saving the form data into db using django modelforms
I want to save the model form data into database. But whatever data is enter on the form it is not throwing any error it is showing same page. I just add the csrf_token into template. because i have model form and it is showing proper template. but data is not saving through template page. Here is my View: def auth_register(request): form = forms.SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST or None) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = Register(first_name=first_name, last_name=last_name, email=email, password=password) user.save() messages.success(request, 'Form submission successful') return HttpResponse('data has been saved :') return render(request, 'auth-register.html', {'form':form}) Model snippet is: class Register(models.Model): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=50, blank=False) password = models.CharField(max_length=12, blank=False) Forms snippet is : class SignUpForm(forms.ModelForm): class Meta: model = Register fields = ['first_name','last_name','email','password'] Template is : <body> <form action="" method="post"> {%csrf_token%} <div class="loader"></div> <div id="app"> <section class="section"> <div class="container mt-5"> <div class="row"> <div class="col-12 col-sm-10 offset-sm-1 col-md-8 offset-md-2 col-lg-8 offset-lg-2 col-xl-8 offset-xl-2"> <div class="card card-primary"> <div class="card-header"> <h4>Register</h4> </div> <div class="card-body"> <form method="POST"> <div class="row"> <div class="form-group col-6"> <label for="frist_name">First Name</label> <input id="frist_name" type="text" class="form-control" name="frist_name" autofocus=""> </div> <div class="form-group … -
replace() takes no keyword arguments
I'm trying to find the first day of the month in python from_date = to_date.replace(day=1) but i got this error : replace() takes no keyword arguments -
Django: Signal not automatically not creating attribute to User
I have a problem using Djangos Signals while creating a User and a Profile. I'm trying to create a Profile upon creating a User, but I keep getting the error: AttributeError at /user/create/ 'User' object has no attribute 'profile' So here is my User Model: from django.db import models from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def _str_(self): return "{} {}".format(self.first_name, self.last_name) and here is my Profile Model: from django.db import models from django_countries.fields import CountryField from django.contrib.auth import get_user_model User = get_user_model() from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' My User Serializer: from rest_framework import serializers from django.contrib.auth import get_user_model from ..models.model_user import * class UserIndexSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] extra_kwargs = {'password': {'write_only': True}} def create(self, … -
Django website deployement debug= false cause template error
i am trying to host a django ebsite.And i set debug-false on settings.py,when i load my website it have probblem on template.templates allignments are not in correctorder.anybody please help me to solve it? -
Change E-mail configuration in setting.py
I have configuration to e-mail in setting.py: EMAIL_HOST = 'Host' EMAIL_PORT = 'NrPost' EMAIL_HOST_USER = 'User' EMAIL_HOST_PASSWORD = 'Pass***' EMAIL_USE_TLS = True EMAIL_USE_SSL = False And with correct data it work. But now I have data in DATABASES. Where I can change value email_host etc. from database? -
How can Get two fields in one Model.py by use foreign key in django
**> How can Get two fields in one Model.py by use foreign key in django? > I want Fields are Course_Name, Branch_Name in Institutes Model and Show My other Courses Model** **This is the Model one >>>** ''''' class Institutes(models.Model): InstituteNo = models.AutoField(primary_key=True) Institute_Name = models.CharField(max_length=300) Course_Name = models.CharField(max_length=300) Course_Code = models.CharField(max_length=100) Branch_Name = models.CharField(max_length=300) Branch_Code = models.CharField(max_length=100) Course_Duration = models.CharField(max_length=100) '''' **#How can Retun Two Fieldsclass Meta: And def __str__(self): only one Value is show in Both Columns.** ''' class Meta: verbose_name_plural = "CourseName" def __str__(self): return self.Course_Name ''' This is the Model two ''' class Courses(models.Model): CourseNo = models.AutoField(primary_key=True) Institute_Name = models.ForeignKey(Facultys, verbose_name="Institute Name", default="0", on_delete=models.CASCADE) Course_Name = models.ForeignKey(Institutes, related_name="CourseName", default="0", on_delete=models.CASCADE) # Show one Filed Here Branch_Name = models.ForeignKey(Institutes, related_name="BranchName", default="0", on_delete=models.CASCADE) # Show Seccond Filed Here Year_or_Sem = models.CharField(max_length=100) ''' **> the output is show same value both drop down...but i want both drop down value Course_Name, Branch_Name** -
Creating a model and linking an existing model by id with a nested serializer
Can I use a nested serializer to link an object created by the parent serializer, to an existing model? I have 2 simple models, Client and Account. Let's say they both have just an id, and a name, the Account also has a (not null) foreign key to the Client. I create 2 serializers, and I nest the ClientSerializer in the AccountSerializer, as I want to see data about the Client when looking at the Account. class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' class AccountSerializer(serializers.ModelSerializer): client = ClientSerializer(required=False) class Meta: model = Account fields = '__all__' This works fine for reads, but if I wanted to POST to create an account, can I do this with the AccountSerializer as it stands? Trying the following: serializer = AccountSerializer(data={ "client_id": 1, "name": "new account" }) I get the error {'client': [ErrorDetail(string='This field is required.', code='required')]}, even though the nested ClientSerializer is required=False. If I try this: serializer = AccountSerializer(data={ "client": {"id": 1}, # Client of id 1 already exists "name": "new account" }) Then I'll get {'client': {'name': [ErrorDetail(string='This field is required.', code='required')]}}, even though I wouldn't want to create a Client nor edit the client's name. I just … -
Django testing - logging in with Selenium not working
I'm trying to test the login page of a django app using Selenium - but I keep getting the error message 'Your email and password do not match'. from django.test import LiveServerTestCase from selenium import webdriver from accounts.models import User class TestInitiationFlow(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.user = User.objects.create(email='user@test.co.uk', admin=True) self.user.set_password('Test1234') self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.get(email='user@test.co.uk')) def tearDown(self): self.browser.quit() def test_initiating_new_project(self): # The user navigates to the homepage of the app # And sees the login screen self.browser.get('http://localhost:8000') # The user enters an email and password username_input = self.browser.find_element_by_id('id_username') password_input = self.browser.find_element_by_id('id_password') submit_button = self.browser.find_element_by_id('submit_button') username_input.send_keys('user@test.co.uk') password_input.send_keys('Test1234') # The user presses enter and is taken to the startup screen submit_button.click() self.assertEqual(self.browser.current_url, 'http://localhost:8000/startup') Any help gratefully received! -
Says 'django.contrib.auth.models.DoesNotExist' even though item created
I've created a population script to test my website - please see below - but I get the following error message: django.contrib.auth.models.DoesNotExist: User matching query does not exist. Given that I've created a hypothetical user, I'm not sure why this is? Some of the indentation formatting below is incorrect - I couldn't get the original formatting to copy over correctly for some reason - but it is correct in the original. Any suggestions would much appreciated. Thank you. Jeff import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mynowandthen.settings') django.setup() from django.contrib.auth.models import User from nowandthen.models import Picture, Comment, UserProfile def populate(): banana_user = [ {'username': 'Banana', 'email': 'Banana@cat.com', 'password': 'Banana1234'}, ] johann_user = [ {'username': 'Banana', 'email': 'Banana@cat.com', 'password': 'Banana1234'}, ] wmffre_user = [ {'username': 'Wmffre', 'email': 'Wmffre@cat.com', 'password': 'Wmffre1234'}, ] maryhill_comments = [ {'user': banana_user, 'body': 'wowo I love this photo - reminds me of when I used to live there!'}, {'user': johann_user, 'body': 'I love Maryhill - its such a pretty part of Glasgow lol'}, {'user': wmffre_user, 'body': 'gonnae no dae that lol', 'user_id': 3}], fireworks_comments = [ {'user': banana_user, 'body': 'amazing fireworks - thanks for sharing :)'}, {'user': johann_user, 'body': 'love fireworks, love this, love YOU!'}, {'user': wmffre_user, 'body': 'whoop!'}] … -
testing views in django: unable to set session variable
This is the first time i'm writing tests for my functions and having a tough time figuring out the right way of doing it. in urls.py path('/b/', views.main), in my views.py, i have def main(request): if "user_id" not in request.session: return HttpResponseRedirect('/') user = Users.object.get(id=request.session['user_id']) d = datetime.datetime.now() - user.last_password_change_date if d.days > 90: return HttpResponseRedirect('/b/my-profile/change-password/?message=90') return render(request, 'backoffice/main.html', { 'user': user, }) in my tests.py file from django.contrib.auth.models import User from django.test import TestCase, Client class TestMain(TestCase): def setUp(self): self.client = Client() def test_backoffice_landing_page_with_session_GET(self): session = self.client.session session['user_id'] = [1] session.save() response = self.client.get('/b/') self.assertEqual(response.status, 200) however this throws me error stating TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' Since, I'm just starting to learn testing django application. I want to test if user gets redirected if session is not available, and is allowed is user_id is available in request.session -
Django signals did not emited
I am stuck in a problem. I am trying to send signal from where I got message from websocket. Websocket message comes, but receiver never gets signal Here is my code plugins/init.py default_app_config = 'plugins.apps.PluginsConfig' plugins/apps.py from django.apps import AppConfig class PluginsConfig(AppConfig): name = 'plugins' def ready(self): import plugins.signals plugins/signals.py plugin_install_started = Signal(providing_args=['message']) plugin_install_error= Signal(providing_args=['message']) @receiver(plugin_install_started, dispatch_uid='ws_plugin_install_started') def handle_plugin_install_start(sender, message, **kwargs): event = 'plugin_install_start' group_name = signal_receive(event, sender) #plugin_group print("got message from install_started") @receiver(plugin_install_error, dispatch_uid='ws_plugin_install_error') def handle_plugin_install_error(sender, error, **kwargs): event = 'plugin_install_error' group_name = signal_receive(event, sender) #plugin_group print("got signal from install_error") And this is the where I try to send signals plugins/consumers.py def receive(self, text_data): text_data_json = json.loads(text_data) if text_data_json["command"] == "install": print(got message from websocket --> install) plugin_install_started.send(sender=self, message=text_data_json) elif text_data_json["command"] == "error": print("got message from websocket --> error") plugin_install_error.send(sender=self, message=text_data_json) When I send install command I can see below "got message from websocket --> install" "got message from install_started" but when I send error command result is below. So signal does not emmitted. plugin_install_error.send(sender=self, message=text_data_json) returns an empty list while plugin_install_install.send(sender=self, message=text_data_json) returns a Signal object "got message from websocket --> error" -
GeoDjango - classview does not register template name
I am trying to display a geographical db on a leaflet map using geodjango. However the view just ignores the template i pass it, I know that this code should work with a regular django class view. models.py: from django.contrib.gis.db import models class WorldBorder(models.Model): name = models.CharField(max_length=50) mpoly = models.MultiPolygonField() views.py: from .models import WorldBorder from djgeojson.views import GeoJSONLayerView class MapLayer(GeoJSONLayerView): template_name = 'world/map_layer.html' model = WorldBorder geometry_field = 'mpoly' properties = ['name'] def get_queryset(self): return WorldBorder.objects.filter(name='Spain') urls.py: urlpatterns = [ path('my_map/', MapLayer.as_view(), name='data'), ] however no matter what is inside of the html file all I get what I load this page is just the json of this object. Am i doing something wrong ? -
in django, On select of dropdown get selected value in views without submit
On change in dropdown, I need to get "cc_value" value in views.py without click on submit button. I referred few blog there they have mentioned that we need to write ajax code for this issue But is there any other way in Django to get the value of the selected option in dropdown without using ajax. In purchase_settings.html <form method = "post" id="Purchase_setting" > <div>Company Code:<br/> <select name="cc_value" id="cc_value"> {% for cc_value in user_setting_list.9 %} <option value="{{cc_value}}">{{cc_value}}</option> {% endfor %} </select> </div> <div >Purchase Organisation:<br/> <select name="purch_org_value"> {% for purch_org in user_setting_list.10 %} <option value="{{purch_org}}">{{purch_org}}</option> {% endfor %} </select> </div> <button class="button" type="submit">SAVE</i></button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#cc_value").change(function () { var company_code = $(this).val(); $.ajax({ type: "GET", data: { 'ccvalue': company_code }, success: function (data) { $("#purch_org_value").html(data); } }); }); </script> in view.py def user_settings(request): .... // need to get cc_value in views on select without submiting form cc_value1 = request.GET.get('ccvalue') //on select of dropdown i m not getting value.I just tried giving cc_value = request.GET.get('cc_value') print(cc_value1)//none # user setting form user_setting_list = user_setting.user_settings_form(client,login_username,db_username) print(user_setting_list) context = { 'user_setting_list':user_setting_list } return render(request, 'purchase_settings.html',context) -
Validating a contact name in python
Suppose I have three fields in my CSV sheet: Conditions: 1) If contact Name is not given then the other two will also be not given. 2) if contact Name is given then: a) Both the values would be given b) one of the values from Contact Number and Contact Email would be given Possible Scenarios: Case 1: Contact Name Contact Number Contact Email Adhiraj Blank adhi@gmail.com Adhiraj 9999999999 Blank Output 1: This should not pop an error as This is a unique contact. Case 2: Contact Name Contact Number Contact Email Adhiraj 9819999999 adhi@gmail.com Adhiraj 9999999999 adhi@gmail.com Output 2: This should result in an error as the first entry and second entry conflicts. Case 3: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9999999999 Blank Output 3: No Error Case 4: Contact Name Contact Number Contact Email Adhiraj Blank adhi@gmail.com Adhiraj Blank raj@gmail.com Output 4: No error Case 5: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9819999999 Blank **Output 5 **: Error Case 6: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9819999999 Blank Raman 9819999999 Blank Output 6 : Error for the third row So, these were the combinations I could … -
Django models DateTimeField index on Date
Is it possible to index only the date aspect of a models.DateTimeField in Django? I cant seem to find it in the documentation, and i'm not sure if doing something like this works class Meta: indexes = [ models.Index(fields=['created_at__year', 'created_at__month', 'created_at__day']), ] -
Celery Flower opens 21 connections to Redis
I am using celery Flower on Heroku with a free dyno to monitor my tasks and noticed that it opens 21 Connections to my redis instance causing troubles with the max connection limit. Does someone know, how to limit the connections to a minimum? -
How to render a javascript function that comes from view as a str?
I'm trying to implement a payment api to my django app. It returns a dict when i do a request. The content of this dict is like that; {...,'checkoutFormContent':'<script type="text/javascript">if (typeof ...</script>'...} How can i render this js function in template? -
Django drf executing function once a day
I have apartments for rent, and each apartment has status (free or not) And my main purpose is to execute function (that changes apartment's status) once a day because of complexity of algorithm. Any solutions will be fine)