Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add field from LDAP to user object
pretty new to software development so please bear with me. I need to show password_set_date within the user object of my app. Currently, when I console.log(sessionStorage.getItem(‘user’)) (from the front-end) I get something like this: {id: id, username: username, first_name: first_name, last_name: last_name, date: date} I need to add a password_set_date field to this object password_set_date is not a column in the postgres DB but is returned from LDAP. I’ve tried modifying the models.py AbstractUser model, views.py file & serializers.py file, but I honestly don’t understand them or their relationship. I don’t need to modify the authentication. Let me know if you need any additional information/code. Greatly appreciate your help! -
How to fix CORS - same domain, Django API and React site
I have a page developed in React deployed with vercel, which makes requests to a Django web server. I've put them under my domain: one is page.example.com and the other is api.example.com. However, when the page makes requests to api.example.com I get a CORS error. My settings look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', 'djoser', 'rest_framework.authtoken', "rest_framework_api_key", 'oauth2_provider', 'drf_api_logger', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware' ] I've tried CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_ALL_ORIGINS = True as well as CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://page.example.com"] CORS_ORIGIN_WHITELIST = ("https://page.example.com') , to no avail. -
Django with postgresql arrayfield of enum
I have a probleme to link my django application to my postgresql database. I have create a custom type currencies in postgresql and I use it as an array. // Type create type currencies as enum ('EUR'); // Usage currencies currencies[] not null In Django, I have made a Enum Currencies ans try to use it as a choices in a Charfield with no succes using the doc.. The django doc about Arrayfield class Currencies(models.TextChoices): EURO = 'EUR', 'euro' from django.contrib.postgres.fields import ArrayField currencies = ArrayField( base_field=models.CharField( choices=Currencies.choices, max_length=3 ), default=list ) -
Does flask's database take space in storage of the computer
does the flask's database, for example users.db consume space on the storage of the computer? I am asking this because I don't know if Django's media folder is worse and consume more space than flask's database when you try to store images there with b64encode. -
Use of mixins for CRUD in Django Rest Framework
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. How can I do CRUD operation with using mixins ? How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" ###I combine both Student and Course into one class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = … -
How to fix a problem trying to deploy a django app to Heroku
When I try to deploy my django app to Heroku with $git push heroku main I keep getting- ERROR: Could not find a version that satisfies the requirement apt-clone==0.2.1 (from versions: none) Please help! -
TypeError: history.push is not a function. In my opi udemy course
Im following tutorial on udemy and facing critical problem, what is stopping me from further coding.... There is no typeo... I have copied sourcecode. Im having problem with selecting payment method... Im 100% sure is about "type=radio" I just cant select it, and by pressing Continue - error above error is occurring.. TypeError: history.push is not a function submitHandler 20 | const submitHandler = (e) => { 21 | e.preventDefault() 22 | dispatch(savePaymentMethod(paymentMethod)) > 23 | history.push('/placeorder') | ^ 24 | } 25 | 26 | return ( function PaymentScreen(history) { const cart = useSelector(state => state.cart) const { shippingAddress } = cart const dispatch = useDispatch() const [paymentMethod,setPaymentMethod] = useState('paypal') if(!shippingAddress.address ) { history.push('shipping') } const submitHandler = (e) => { e.preventDefault() dispatch(savePaymentMethod(paymentMethod)) history.push('/placeorder') } return ( <FormContainer> <CheckoutSteps step1 step2 step3 /> <Form onSubmit={submitHandler}> <Form.Group> <Form.Label as='legend'>Select Method</Form.Label> <Col> <Form.Check type='radio' label='PayPal or Credit Card' id='PayPal' name='paymentMethod' checked onChange={(e) => setPaymentMethod(e.target.value)} > </Form.Check> </Col> </Form.Group> <Button type='submit' variant='primary'> Continue </Button> </Form> </FormContainer> ) }``` -
Django: How to filter a queryset by a another model in django
i have a model Course and another model Video that is a foreignKey to the Course model. Now what i want to do is this, i want to display all the videos related to a course and display the videos count along side the name of the course in a a list view not in the detail view. this is the code i have written but it keep showing an error views.py def my_courses(request): courses = Course.objects.filter(course_creator=request.user) lectures = Video.objects.filter(course=courses).count() context = { 'courses': courses, 'lectures':lectures, } return render(request, 'dashboard/my_course.html', context) error that the code above shows The QuerySet value for an exact lookup must be limited to one result using slicing. -
Django choices list conversion
I want to use a list I have created from a static json file as a menu option on my web page. This does not work when I makemigrations. I believe the issue is that choices is expecting the two field format, rather than the list I have created. How do I convert this? Makemigrations error: ValueError: too many values to unpack (expected 2) from django.db import models #Generic for models from django.contrib.auth.models import User #Required for dynamic user information from django.forms import ModelForm #Custom form #from django.contrib.postgres.fields import JSONField #Required to support json for lists - Obsolete? #from django.db.models import JSONField #Required to support json for lists - Also obsolete? from jsonfield import JSONField import json #json static data imports data = open('orchestration/static/router_models.json').read() #opens the json file and saves the raw inventory contents inventory = json.loads(data) #converts to a json structure #Constructor for the list of router models ROUTER_MODELS = [] #List of router models for routers in inventory["router_models"]: print(routers["model"]) ROUTER_MODELS.append(routers["model"]) #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) #Person who created the order created_at = models.DateTimeField(auto_now_add=True) #Date/Time order was created def __str__(self): return … -
Cannot archive a user account then got "Invalid password." error (Django GraphQL Auth)
With Django GraphQL Auth, I'm trying to archive a user account with the GraphQL below: mutation { archiveAccount( password: "test1test1", ) { success, errors } } And REQUEST HEADERS below: { "Authorization": "JWT my_jwt_access_token" } But, I got the error "Invalid password." as shown below: { "data": { "archiveAccount": { "success": false, "errors": { "password": [ { "message": "Invalid password.", "code": "invalid_password" } ] } } } } Actually, my password is correct and the account is verified and I properly set the JWT Access Token to "Authorization" in REQUEST HEADERS. Are there any ways to solve the error to archive a user account? -
Save Parent and Child in One hit to database
I have Three tables. class Parent(): pass class Child(): parent = models.ForiegnKey(Parent) class GrandChild(): child = models.ForiegnKey(Child) Now Parent can have many Childs and child have many GrandChilds, i mean 100's. Is there any way to save the Parent/Child/Grandchild at the same time ? So we get only 1 database hit and Parent/Child/Grandchild are all saved. I know there is transaction available in Django, but as per my understanding (I may be wrong) transactions are not the solution to this problem. -
Django and React: csrf cookie is not being set in request header
To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided: settings.py: ALLOWED_HOSTS = ['*'] ACCESS_CONTROL_ALLOW_ORIGIN = '*' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_METHODS = '*' ACCESS_CONTROL_ALLOW_HEADERS = '*' ''' SESSION_COOKIE_SECURE = True ''' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000'] setting SAMESITE protocol to anything else haven't made any change in views.py, we have login view (class based): class LoginView(views.APIView): permission_classes = [AllowAny,] serializer_class = serializer.LoginSerializer def post(self,request): data = serializer.LoginSerializer(data=request.data) print(data.is_valid()) if data.is_valid(): email = data.data['email'] password = data.data['password'] auth = authenticate(username=email,password=password) if auth: login(request,auth) return HttpResponse("Success",status=200) else: print(password == "") if email == "" and password =="": return HttpResponse('Both email and password field are empty',status=400) elif email == "": return HttpResponse('Email field is empty',status=400) elif password == "": return HttpResponse('Passowrd field is empty',status = 400) else: return HttpResponse("Both email and password fields are empty",status=400) in serializer.py, we got the login serializer: class LoginSerializer(serializers.Serializer): email = serializers.CharField(required=False) password = serializers.CharField(required=False,allow_null=True,allow_blank=True) in react (frontend side), here is how i am making a … -
Django instance return none from ImageField
How could I solve this problem? I want to create a model with an image and upload it to create a folder with the id of that object. When I try to upload an image in the same class I can't reference the id to add in the url. The path looks like: http://127.0.0.1:8000/media/foto_pacientes/None/image.png pacientes.models.py class Pacientes(models.Model): id = models.AutoField(primary_key=True) foto = models.ImageField(blank=True, null=True, upload_to=foto_paciente) def foto_paciente(instance,filename): print(instance) return '/'.join(['foto_pacientes', str(instance.id.id), filename]) However, when I try to upload an image using a ForeginKey I can get the desired id. As: http://127.0.0.1:8000/media/foto_pacientes/1/image.png imagens.model.py def imagens_historico(instance, filename): print(instance) return '/'.join(['historico', str(instance.id_historico.id_historico), filename]) class ImagensHistorico(models.Model): id_imagem_historico = models.AutoField(primary_key=True) imagem = models.ImageField(blank=True, null=True, upload_to=imagens_historico) id_historico = models.ForeignKey(Historicos, related_name='imagens', on_delete=models.CASCADE, blank=False, null=False) -
Getting rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0xff in position 260: invalid start byte
I am building a rest api using django rest framework.I am making a post request through postman and passing the body as a form data as given in the below image: The code in views.py file is: def addItem(request): if request.method == "POST": items = request.body itemStream = io.BytesIO(items) dataItems = JSONParser().parse(itemStream) serializedData = MenuSerializer(data=dataItems) if serializedData.is_valid(): serializedData.save() responseMessage={'message':"Items added successfully"} return JsonResponse(responseMessage) json_data=JSONRenderer().render(serializedData.error) return HttpResponse(json_data,content_type='application/json') Code of serializer.py is: from dataclasses import fields from .models import Menu from rest_framework import serializers class MenuSerializer(serializers.ModelSerializer): class Meta: model = Menu fields = '__all__' def create(self,validated_data): return Menu.objects.create(**validated_data) Code of models.py file is: class Menu(models.Model): item_name = models.CharField(max_length=20) image = models.ImageField(upload_to="media") category = models.CharField(max_length=20) price = models.IntegerField() discount = models.IntegerField() plate_size = models.IntegerField() -
ManyToMany field returns None instead of giving me the data
I am developing a restaurant management application in django. When I am trying to print the ordered items of a customer I am getting testapp.Menu.None testapp.Menu.None Only that many to many fiedls is showing none. Other are working fine. These are my models: categories=( ('Starters','Starters'), ('Maincourse','Maincourse'), ('Breakfast','Breakfast'), ('Desserts','Desserts'), ('Beverages','Beverages') ) class Menu(models.Model): name=models.CharField(max_length=200,null=True) category=models.CharField(max_length=200,null=True,choices=categories) price=models.IntegerField(null=True) date_created=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Customer(models.Model): name=models.CharField(max_length=200) email=models.CharField(max_length=200) phone=models.IntegerField() address=models.TextField(max_length=200) date_created=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Orders(models.Model): status=( ('Out of delivery','Out of delivery'), ('Pending','Pending'), ('Order recieved','Order recieved'), ) customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL) items=models.ManyToManyField(Menu) status=models.CharField(max_length=200,choices=status) date_created=models.DateTimeField(auto_now_add=True,null=True) This is my view.py file def customer_info(request,pk): customer=Customer.objects.get(id=pk) order=customer.orders_set.all() context={ 'customer':customer, 'order':order } return render(request,'customer_info.html',context) My html file <table> <tr> {{customer.name}} <br> {% for order in order %} {{ order.items }} {% endfor %} </tr> </table> Please help me to fix this. -
how to filter a time field in a list between two times
I have created an app where an interviewer can fill out forms and schedule multiple interviews. this is the model for the schedule: class ScientificSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) province = models.CharField(max_length=100, blank=True) and I wrote this view for it: class ScientificScheduleView(FormView): template_name = 'reg/scientific-schedule.html' form_class = ScientificScheduleForm def post(self, request): form = ScientificScheduleForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ScientificScheduleView, self).form_valid(form) it works fine. I want to add a statement to the form_valid function that checks if another schedule in that timespan already exists. for example imagine that this particular user has an interview from 8 a.m. to 10 a.m. He is not allowed to schedule another interview between 8 and 10. How do I make it check the user's previous interviews objects and see he is allowed to submit this form or not? I want something like this: def form_valid(self, form): if ScientificSchedule.objects.filter(user=self.request.user, province=form.instance.province, date=form.instance.date, start_time__in=[a list between two times from other interviews on that specific date]).exists(): return self.form_invalid(form) else: form.save() return super(ScientificScheduleView, self).form_valid(form) how can I filter it like this? -
Create a auto generated password field in a django model
I have a model named Customers. I want the admin to be able to add the details of each customer through admin panel. The details include username, password, company, email, etc. For password, I want to generate an auto randomly generated password field(not to be typed in admin forms), which can't be seen by admin and will be sent to the customer. I am new to Django and I can't figure out a way to do that. -
Updating chart.js with ajax
i'm trying to auto-update my chart js graph trough ajax , but my if statement always return the wrong awnser on the first iter , any idea why ? thank again. , tell me if you need anything more. setInterval(addData, 10000); //setting the loop with time interval function addData() { $.ajax({ url:'get', url: "/hello-world/", success: function(response){ let labels=String(response.labels); let datas=response.datas; console.log('check',String(label.slice(-1))); console.log('in',labels); ',myChart.data.labels.slice(-2)[1]); if (labels == String(label.slice(-1))){ console.log('same content'); }else{ console.log('updating content',labels,'to',String(label.slice(-1))); myChart.data.datasets[0].data.push(datas); myChart.data.labels.push(labels); myChart.update(); console.log('revisu',myChart.data.labels.slice(-2)[0],' : ',myChart.data.labels.slice(-2)[1]); if(myChart.data.labels.slice(-2)[0] == myChart.data.labels.slice(-2)[1]){ console.log("something's wrong"); myChart.data.labels.pop(); myChart.data.datasets[0].data.pop(); myChart.update(); }else{ }; myChart.update(); } } }); } -
How do I set up django on heroku for direct to s3 file uploads
There doesn’t seem to be any tutorials online about django direct to s3 on heroku. All tutorials are either flask or rails. I would like to know is there a tutorial or simple method for django? -
getting error {"error": "invalid_client"} when creating access token in django
I have created Application in my project and its successfully created. and I received Client ID and Client secret from this. but when I am entering command to get access token this gives me an error message {"error": "invalid_client"} I entered this command curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://<ip_address>:<port>/o/token/ In Windows CMD using my username password. I have added this in settings.py 'oauth2_provider' in INSTALLED_APPS OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' : [ 'django_filters.rest_framework.DjangoFilterBackend' ], 'DEFAULT_AUTHENTICATION_CLASSES' : ('oauth2_provider.contrib.rest_framework.OAuth2Authentication',), } But still getting {"error": "invalid_client"} In CMD. Unauthorized: /o/token/ [31/May/2022 18:08:17] "POST /o/token/ HTTP/1.1" 401 27 and above error in VS code's Terminal. How I get solution of it. -
How to count products in category django
i need to show how many items in each category,like i have 3 items in category Phones and i want to do this Phones(3). I tried to to some methods in models,but it doenst work def count_products(self): return Category.objects.all().count() also tried in views.py context = super().get_context_data(**kwargs) context['grade_info'] = self.get_ordered_grade_info() context['category'] = Category.objects.count() return context -
API for admin section django rest framework
I am new to DRF hence I wish to know that: http://x.x.x.x:8000/Admin => admin interface for Django Rest Framework. can this be accessed by using API for authenticated users? -
Django-Docker-PostgreSQL multiple db
I am currently trying to figure how can I setup multiple databases by means of the docker-compose.yml. With only one db everything works well, the docker-compose.yml with one db is: version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - postgres ports: - "8000:8000" db_migrate: image: "django_image:latest" command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: postgres:latest ports: - "5432:5432" environment: *database-variables volumes: - db-data:/var/lib/postgresql/data restart: unless-stopped pgadmin: container_name: pgadmin_container image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-admin@admin.com} PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin} PGADMIN_CONFIG_SERVER_MODE: "False" volumes: - pgadmin:/var/lib/pgadmin ports: - "${PGADMIN_PORT:-5050}:80" restart: unless-stopped volumes: db-data: pgadmin: But, when I change the docker-compose.yml with the below config and add to root dir the create-multiple-db.sh, the postgres db_migrate raises: Could not translate host name “postgres” to address: Temporary failure in name resolution The docker-compose.yml: version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" container_name: django_container volumes: *service-volumes command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" db_migrate: image: "django_image:latest" container_name: db_migrate_container command: python manage.py migrate … -
Python Can not found - Django, runserver err
I can't run my Django project, can you help? While py can run any py file in the terminal as py_any_project_name.py, when I type py manage.py runserver or python manage.py runserver, I get python not found error. Any ideas on the cause and solution? I'm using Python 3.10 and it's attached to the environment variables as the path.. For example i create an example.py file that includes print("Example"). py example.py Example py manage.py runserver Python can not found. -
"uid":"Invalid user id or user doesn't exist."
I am sending user registration credentials via postman in my Django project as below, and this returns me 201 response code. After that I am getting this link for activation as below Now I am getting uid and token from the URL as { "uid":"NjI5NWZmYmJkZTYzNTg1MDBjM2ZjYTIy", "token":"618-673ef2e1058d5f98fe41" } You can see my POST request to activate my account as below, as you can see in above image, after sending a post request with uid and token, it says { "uid": [ "Invalid user id or user doesn't exist." ] } And also I saw many uids on google, they are only of max length of 3 letters and my uid is greater than 10 letters. Is my uid is correct ? Thanks for your time!