Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Multiselect package is sending [object, Object] instead of key and value
I am trying to pass data in my django backend from react frontend. I am able to pass the data using some Multiselect from react. But the problem is I am sending label and value but when I try to print my data in frontend and check the data what it is passing I got the result like [object Object] instead of [mylabel MyValue] and I just want to pass the option value. I am new to react so don't know much about setState things. Can someone help me to do this? Or any other easy way to pass multiple data in my api it would be much appreciated like I select HD and SD then in my backend I should get both value. #This is my react code check the deliveryOption, setDeliveryOption import axios from "axios"; import React, { useState, useEffect } from 'react' import { LinkContainer } from 'react-router-bootstrap' import { Table, Button, Row, Col, Form } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import FormContainer from '../components/FormContainer' import { MultiSelect } from "react-multi-select-component"; import Select from 'react-select'; const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/create/products/"; const options = [ { label: "HD π", β¦ -
How to direct a user from a page in a Django app to a static web page found on the same server
Assume that I have my Django app running at '/var/project/my_django_project/' and I want to direct the user to '/var/project/static_website/index.html' when a button is clicked in a template located at '/var/project/my_django_project/templates/my_template.html'. How can I achieve this? -
login with phone number in django
I get this error when making changes self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' model from django.db import models from django.contrib.auth.models import AbstractUser class Userperson(AbstractUser): gender_choice = [ ('M', 'male'), ('F', "female") ] roles = [ ('seller', 'Seller'), ('shopper', 'Shopper'), ('serviceman', 'Serviceman') ] fullname = models.CharField(max_length=100, verbose_name="Fullname") phone = models.CharField(max_length=20,verbose_name="Phone",unique=True) image = models.ImageField(upload_to="userphoto/fullname", blank=True, null=True, verbose_name="userPhoto") phone_auth = models.BooleanField(default=False) gender = models.CharField(choices=gender_choice, blank=False, null=False, max_length=50) role = models.CharField(choices=roles, max_length=50) # ? USERNAME_FIELD = 'phone' #REQUIRED_FIELDS = ['fullname'] admin from django.contrib import admin from .models import Userperson @admin.register(Userperson) class personadmin(admin.ModelAdmin): list_display = ['fullname', 'phone', 'image', 'phone_auth'] What should I do to solve the problem? -
COMBINING DJANGO QUERYSETS WITH RELATED FOREIGN KEY FIELS
I have three models which are listed below. In a view called workstation view I need to show all products that match two criteria. I need to show all "Dispensings" where the status is "Pending" and the "Dispensing.product.form" equals the allocated workstation form. I am not sure of the quickest and best way to do this. The code is below app name = "prescriptions" class Dispensing(models.Model): class Status(models.TextChoices): RECEIVED = 'A', _('Order received') OWING = 'W', _('Owing') PAYMENT = 'C', _('Invoice sent') PENDING = 'D', _('In production') #CHECKED = 'C', _('Approved for release by pharmacist') DISPATCHED = 'E',_('Dispatched') script_status = models.CharField(max_length=2,choices=Status.choices,default=Status.RECEIVED,) product = models.ForeignKey(Product,related_name='product',on_delete=models.CASCADE) app_name = 'product class Product(models.Model): form = models.ForeignKey(Form, related_name='products', on_delete=models.CASCADE, blank=True,null=True) app name = "equipment" class Workstation(models.Model): created_on = models.DateField(default=((timezone.now())+(datetime.timedelta(hours=11))),blank=True,null=True) name = models.CharField(max_length=200, db_index=True, blank=True,null=True) asset_id = models.CharField(max_length=200, db_index=True, blank=True,null=True) product_types = models.ForeignKey(Form,related_name='forms',on_delete=models.CASCADE,blank=True,null=True) app name = "list" class Form(models.Model): description = models.CharField(max_length=255) I have removed the unnecessary fields. Both dispensing and Workstation are linked separately to Form. I need to query all dispensings where dispensing.product.form equals workstation.form. I just can't think of a simple query to do this. The view is below: class WorkstationDetailView(DetailView): model = Workstation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['workstations'] = Workstation.objects.all() β¦ -
Can anyone please help me figure out what is causing this error
enter image description here My app shows error after build succeeded, and the log file shows an error from the procfile -
foreign key in django and postgresql ,
i am trying to export the model from the database which is postgresql to an Excel file and the issue here is the Foreign key fields exported as an ID integer , How can i change it to string for enter image description here -
Im trying using class modelForm in django
My models.py from django.db import models # Create your models here. class modelBlog(models.Model): title = models.CharField(max_length=200) description = models.TextField() body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) def __str__(self): return ('{}.{}').format(self.id, self.title) class comment(models.Model): blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE) name = models.CharField(max_length=200) komentar = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) My forms.py from .models import modelContact, comment from django import forms class CommentForm(forms.ModelForm): class meta: model = comment fields = [ 'name', 'komentar', ] widgets = { 'name': forms.TextInput(attrs={'class':'form-control'}), 'komentar': forms.Textarea(attrs={'class':'form-control'}), } AND views.py def detail(request, id): blog = modelBlog.objects.get(id=id) form = CommentForm() if request.method == 'POST': nama = request.POST['nama'] comment = request.POST['komentar'] new_comment = blog.comment_set.create(name=nama,komentar=comment) new_comment.save() messages.success(request, 'Komentar berhasil ditambahkan') return redirect('blog:detail', id) judul = blog.title context = { 'title':judul, 'blog':blog, 'form':form } return render(request, 'blog/detail.html', context) i got error ValueError at /blog/1/ ModelForm has no model class specified. Request Method: GET Request URL: http://localhost:8000/blog/1/ Django Version: 4.0.2 Exception Type: ValueError Exception Value: ModelForm has no model class specified. -
One test database is not created when two database are used
I have two databases to use in django project. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": "mydb", "USER": "root", "PASSWORD": config("DB_PASSWORD"), "HOST": "127.0.0.1" "PORT": 3306, 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'TEST': { 'NAME': 'test_{0}'.format(config("DB_NAME")), }, }, 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mydb_extern", 'USER': "root", 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': "127.0.0.1", 'PORT': 3306, } } I am using two datbases mydb and mydb_extern When I am testing with python manage.py test, it makes test_mydb However there comes error like django.db.utils.OperationalError: (1051, "Unknown table 'mydb.t_basic'") So problem is, t_basic is exist on in mydb_extern not in mydb testscript copy the mydb to test_mydb testscript try to search the t_basic from test_mydb Why does it happen? and why testscript doesn't make the second database? -
Error H12 "Request timeout" on heroku for django application
I am getting the H12 "Request timeout" error when I am working with large data in a CSV file and when the data in the CSV file is less the app is working fine. The logs that I am getting is : 2022-02-27T06:05:20.963369+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/" host=youtube-channel-list.herokuapp.com request_id=36c5fe9b-21c5-40de-8804-a75786dfd32e fwd="27.97.65.233" dyno=web.1 connect=0ms service=30699ms status=503 bytes=0 protocol=https I updated my Procfile also as: web: gunicorn channelList.wsgi --timeout 120 --keep-alive 5 --log-level debug --log-file - But still, the same error is coming. What exactly do I need to do? If you need more information, I am ready to provide it. -
todo_details() missing 1 required positional argument: 'id'
**Question ** todo_details() missing 1 required positional argument: 'id' Code views.py def todo_details(request, id): todo = Todo.objects.get(id=id) context = { "todo": todo } return render(request, "todo/todo_details.html", context) 0001_initial.py operations = [ migrations.CreateModel( name='Todo', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('due_date', models.DateField()), ], ), ] -
django.db.utils.IntegrityError: duplicate key value violates unique constraint DETAIL: Key already exists
I have created a server that delivers updates to devices using django. This is my Model: class updates(models.Model): name_device = models.CharField(max_length=200)#name of device number_ip = models.CharField(max_length=200)#number of ip name_update = models.CharField(max_length=200)#name of update date_send = models.CharField(max_length=200)#date of update status = models.CharField(max_length=200)#status of update Every time I call the function in code: #The function creates a new update in the "updates_updates" table def create(name_device,number_ip,name_update,date_send,status): updates.objects.create(name_device=name_device,number_ip=number_ip, name_update=name_update,date_send=date_send,status=status) I get erro every time on a different "key" for example: django.db.utils.IntegrityError: duplicate key value violates unique constraint "updates_updates_namedev_key" DETAIL: Key (name_device)=(car) already exists. -
Getting Issues in urls in Django, in subdirectory or suburl
I am trying to run Django inside WordPress like WordPress at main url www.wptesting.com and Django at suburl www.wptesting.com/django . Django main root url Is working fine at www.wptesting.com/django but its suburl e.g., admin is not working as it should be www.wptesting.com/django/admin . However, whenever I tried to request admin url it goes converts into www.wptesting.comhttp%3a//wptesting.com/django/admin I am running WordPress and Django with Apache and mod_wsgi , my conf file for apache is as follows : <VirtualHost *:80> WSGIScriptAlias /django /path_to_project/wsgi.py ServerName wptesting.com ServerAlias www.wptesting.com DocumentRoot /var/www/html/wordpress <Directory /var/www/html/wordpress/> AllowOverride All Order allow,deny allow from all # Options Indexes FollowSymLinks # Require all granted </Directory> <Directory /path_to_project/> Options Indexes FollowSymLinks Require all granted </Directory> </VirtualHost> I have asked one question earlier about configuring Django from subdirectory of WordPress with Apache and wsgi -> you can see the question here Also If I tried to access any url which is not in Django project then it is giving the standard 404 not found error but when I try to access any valid url like admin it is giving the error mention above. Edited : My Urls.py file : from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic import β¦ -
Execute Multiple Cursor in Single Function
I want to execute multiple cursor in single function, here's the function in my views.py def index(request): cursor = connection.cursor() cursor.execute('''select count(name) from report sr where is_active=0 group by is_active ''') abcd = cursor.fetchall() connection.close() return render (request, 'index.html',{'abcd':abcd}) I've tried on my own like this but it doesn't seem to work, so please help me out on how to implement this def index(request): cursor = connection.cursor() cursor.execute('''select count(name) from report sr where is_active=0 group by is_active ''') abcd = cursor.fetchall() connection.close() cur = connection.cursor() cur.execute('''select count(name) from report sr where is_active=1 group by is_active ''') abcd = cur.fetchall() connection.close() return render (request, 'index.html',{'abcd':abcd},{'cur':cur}) -
Slug size too large
I tried to deploy my app on heroku, but have following error. Compiled slug size: 869M is too large (max is 500M). I am wondering if i can increase the slug size by chancing Dyno types (ex. change free to standard)? -
Sending header for authentication in the mutation causes error
Using Graphene-Django and Django-Graphql-Jwt, the mutation causes errors with the authentication header. But it works well without the authentication header. class HelloMutation(graphene.Mutation): """Mutation that says hello""" hello = graphene.String() class Arguments: pass @login_required def mutate(self, info): return f'Hello, { info.context.user.username }' -
Django search fields under Createviews
I have datalist like Search field created in django template using ajax autofill with function views. Now I want to work the datalist in Classbased views, It's possible to do in createviews with autofill?? Or can someone give me an idea on how to do?? Thanks I tried using Foregnkey but not totally like a Search field... Datalist in frontend autofill <div class="col-sm-4"> <label>Employee Id</label> <input name="emp_id" id="emp_id" class="form-control" list="emp_list" required> <datalist id="emp_list"> {% for emp_id in elist %} <option data-value="{{ emp_id.Employee_Id }}" | "{{ emp_id.Group }}" value="{{ emp_id.Employee_Id }}"> </option> {% endfor %} </datalist> </div> <div class="col-sm-4"> <label>Group</label> <input type="text" name="group" id="group" class="form-control"> </div> AJAX <script> $('#emp_id').on('change', function () { var value = $('#emp_id').val(); var val = ($('#emp_list [value="' + value + '"]').data('value')); var parts = val.split(" | "); $('#emp_id').val(parts[0]); $('#group').val(parts[1]); }); </script> -
How to raise multiple ValidationError in Django
I saw this post: How to raise multiple ValidationError on Django? However I have some questions. In the accepted answer, andilabs writes: raise ValidationError({ 'field_name_1': ["Field not allowed to change"], 'field_name_2': ["Field not allowed to change"], }) Do the values have to be in a List even though it is just one string? If so, anyone know why? Or where in the documentation it says so? I have not found it in https://docs.djangoproject.com/en/3.0/ref/forms/validation/#raising-multiple-errors. The below code works for me and in my html template I can do {{ form.user.errors }} to have it show up in a div on submission. For who wants to know what context I am using it in, I am using it in a Form view, and inside it I have a def clean(self) method, where I override the parent clean(). Some code for reference: class RegisterForm(forms.Form): user = forms.CharField() **the fields and stuff** def clean(self): error = {} cleaned = super().clean() if 'user' not in cleaned_data: error['user'] = ['Username is empty'] **check if other fields are not there, check password length minimum, etc.** if len(error) != 0: raise ValidationError(error) return cleaned -
django choices in usercreationform
I tried a lot of ways to add a choice field on the registration field, but only the forms.ChoiceField is not showing up. class NewUserForm(UserCreationForm): Choices = (('I', "International"), ('K', "Korean")) EXAMPLE = forms.CharField(max_length=30) you_are = forms.ChoiceField(choices=Choices) class Meta: model = Student fields = ("username", "password1", "password2", "you_are") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) if commit: if user.you_are == "K": user.lang = "KR" user.save() return user Then the EXAMPLE part shows up, but not the you_are part. Are there any problems with my code? Or do I have to use a different way to include forms.ChoiceField? -
Modifying request body according to inputs read from a csv file
I have to read CSV file from AWS S3 bucket say it has 5 columns. Column 1,Column 2,...,Column 5. I have fetched the column names using below code. column_names=[] client = boto3.client('s3', aws_access_key_id = access_key, aws_secret_access_key = secret_access_key) csv_from_aws_s3 = path df = pd.read_csv(path) for col in df.columns: column_names.append(col) print(column_names) Some column details are static and some dynamic. Say (eg Designation)Column1= static & (eg Salary)column2 dynamic. Specified by user input, taken by any UI Text Editor. Now I have to make api-calls to GET and POST static & dynamic part from the csv files and store it in an SQL database. I am using django-rest-api. With some research I came across Requests lib that is suitable for this problem. If I'm missing some information required for this question please mention in comment. -
Having problem in displaying Django messages on HTML template
base.html <body data-spy="scroll" data-target=".navbar"> {% include "navbar.html" %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" role="alert"> {{ message }} </div> {% endfor %} {% endif %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' views.py def login_view(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): login(request, form.get_user()) messages.info(request,'η»ε ₯ζε!') return redirect('index') else: messages.error(request,'εΈ³ζΆη‘ζζε―η’Όι―θͺ€! θ«ι試!') context = {'form':form} return render(request,'customer/login.html',context) For the login view, I may want to display the error message 'εΈ³ζΆη‘ζζε―η’Όι―θͺ€! θ«ι試!' if the user entered the incorrect username or password. When I try to enter the incorrect username or password, the error message could not be shown on the template even though I had added {% if messages %} in the base.html. However when I check the code of the template it has been included but do not know why could not be shown with the alert tag so can anyone help me find out what I am missing? -
Connecting ElasticSearch to Django using "django-elasticsearch-dsl" results in ConnectionError when attempting to create/rebuild index
I am trying to call a local ES instance running on docker. I used the following instructions to setup my ES instance: https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode I am able to play around with my instance on Kibana at http://0.0.0.0:5601/app/dev_tools#/console. Everything works upto here. Now I am trying to define some sample documents using django models and index them through the library; I am following the instructions here: https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#install-and-configure First, I add pip installed and added django_elasticsearch_dsl to INSTALLED_APPS Next, I added in settings.py: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } Then I create a sample model and document that looks like this: # models.py from django.db import models class Car(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=30) description = models.TextField() type = models.IntegerField(choices=[ (1, "Sedan"), (2, "Truck"), (4, "SUV"), ]) # documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Car @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Car # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ β¦ -
Docker python:3.9.10-slim-buster image can not install backports.zoneinfo using pip
I have tried Containerising an django project. I was using python:alpine image. The app needed backports.zoneinfo to be installed as requirement. While running pip install -r requirements.txt its showing error when it try to install the backports.zoneinfo. requirements.txt asgiref==3.5.0 backports.zoneinfo==0.2.1 Django==4.0.2 sqlparse==0.4.2 Then I have opened docker container in interactive mode and tried pip install backports.zoneinfo. There also its showing same error. I have tried the same commands in python:3.9.10 image. It was working fine and the package got installed. This error can be reproduced using any of slim, alpine images. I have went through couple of fixes. But it wasn't working. Few of the fixes that I have tried are given below. I have tried these inside the container. pip upgrade pip upgrade wheel apt/apk install gcc apt/apk install gzdata pip install python-dev-tools apt/apk install gcc-c++ To reproduce the error Command docker pull python:alpine docker run -it python:alpine sh pip install backports.zoneinfo Error Collecting backports.zoneinfo Downloading backports.zoneinfo-0.2.1.tar.gz (74 kB) |ββββββββββββββββββββββββββββββββ| 74 kB 692 kB/s Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (PEP 517) ... error ERROR: Command errored out β¦ -
Associate user by email
I want to override the pipeline to associate user's with their email for accounts that are only active. But I need the backend for a regular login. settings.py AUTHENTICATION_BACKENDS = ['social_core.backends.google.GoogleOAuth2','django.contrib.auth.backends.AllowAllUsersModelBackend',] # Extends default user with additional fields AUTH_USER_MODEL = 'pages.Profile' SOCIAL_AUTH_USER_MODEL = 'pages.Profile' # social auth configs for google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/calendar'] SOCIAL_AUTH_JSONFIELD_ENABLED = True SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline','approval_prompt':'force'} SESSION_COOKIE_SAMESITE = None SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'pages.pipeline.save_token' ) views.py def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return redirect('home') else: messages.error(request,'User blocked',extra_tags='login') return redirect('login') else: messages.error(request,'username or password not correct',extra_tags='login') return redirect('login') else: form = AuthenticationForm() return render(request, 'registration/login.html',{'form':form}) -
Display different data based on name (Django)
I'm making an online food delivery website using Django. I have this table showing each restaurant's name and business hours. If the user clicks the restaurant's name, I want the new page to display the menu of the restaurant. How do I do this? Below is my code for models.py class Restaurant(models.Model): photo = models.ImageField(upload_to="images/") name = models.CharField(max_length=50, primary_key=True) phone = models.CharField(max_length=15) hours = models.CharField(max_length=100) website = models.TextField() category = models.CharField(max_length=20) def __str__(self): return self.name class Menu(models.Model): restaurant_name = models.CharField(max_length=50) item = models.CharField(max_length=20, default='item') price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.item Below is my code for menu.html <div class="container"> <table class="table text-center"> <thead> <tr> <th scope="col">Item</th> <th scope="col">Price</th> <th scope="col">Add to Cart</th> </tr> </tr> </thead> <tbody> <tr> <td> {{ }} </td> <td>$ {{ }}</td> <td><button class="btn">Add</button></td> </tr> </tbody> </table> </div> -
How to save user preferences without logging user in flutter app
I am working on a flutter app that requires some user data to be saved on server side. But I don't want user to log in using username/password or any social account. Is there a way in flutter to identify the user/device without explicit login ? There seems to be a anonymous login using Firebase but I am looking for a generic solution without any specific backend. I am using Django as my backend.