Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Order page after selection of product
models.py ` class Product(models.Model): name = models.CharField(max_length=50 , verbose_name='العنوان') disc = models.TextField (null=True , verbose_name='وصف المنتج') price = models.DecimalField (max_digits=5 , decimal_places=0 , null=True , verbose_name='السعر') photo = models.ImageField (null=True, upload_to='static\product_images', verbose_name='صورة المنتج') active = models.BooleanField(default=True , verbose_name='حالة المنتج') category = models.CharField(max_length=50,null=False) slug = models.SlugField(blank=True, null=True) urls.py ` urlpatterns = [ path('', views.Product_list , name= 'home'), path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), path('product/<int:product_name>/order', views.Product_order , name= 'order'), path('qa/', views.Question_list , name= 'Question_list'), path('annoncement/', views.Blog_list , name= 'Blog_list'), path ('about/' , views.about , name='about'), `` views.py ` def Product_order (request, product_name): if request.method == 'POST': order = OrderForms(request.POST) return render (request , 'order.html' , {'order' : order,}) ` error UnboundLocalError at /product/2/order cannot access local variable 'order' where it is not associated with a value solution for my probleme -
How to make API requests after authenticating with django-allauth?
I've integrated Github and GitLab authentication in my Django app using django-allauth. After authentication, how do I get access to the request token to make API calls to Github and GitLab? I'm using django-allauth v0.51.0 and django v4.1.4. -
Django Vue3 access-control-allow-origin is not allowed
I have a Django rest-api project. Vue is used on the front of the project. I get the following error when requesting via Vue: print console: Access to XMLHttpRequest at 'https://api.iyziwell.com/api/user/register' from origin 'https://main.d398abgajqt044.amplifyapp.com' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'account', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://main.d398abgajqt044.amplifyapp.com', 'http://localhost:8082', ] CORS_ALLOWED_ORIGIN_REGEXES = [ 'https://main.d398abgajqt044.amplifyapp.com', 'http://localhost:8082', ] CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) request page = https://main.d398abgajqt044.amplifyapp.com -
How to iterate dictionary to template in Django
I have two loops that works perfect if I print the results. It gives me a list that show the name and the value but I have difficulties to show it in a template. It just shows the last results. for u in Performance.objects.raw('SELECT * FROM...') name = u.last_name + ' ' + u.first_name for e in Projekt_perf.objects.raw('SELECT stressz_profile.id...') total = e.total results = {'name':name, 'total':total} context = { 'results': results, 'name': name, 'total': total, } return render(request, 'performance/list.html', context)` This is the dictionary I get, it's OK: {'name': 'Someone01', 'total': 25} {'name': 'Someone02', 'total': 7} {'name': 'Someone03', 'total': 10} {'name': 'Someone04', 'total': 0} I like to have the dictionary above in the template and I tried these methods but I did not get all the elements just the last one. {% for r in results %} {{ r }} {% endfor %} {% for r in results %} {{ r.name }} - {{ r.total }} {% endfor %} What am I doing wrong? -
django javascript: Custom request header throwing CORS error and redirecting to OPTIONS
I am trying to create an API library in Django. This API will be called by javascript. Django-API and javascript is running in two different servers. The django API library is expecting a custom request header from javascript front end. I am parsing this header from django request object. Everything is fine when I am trying in postman. But when I am trying this from browser, browser rejects my custom request header. and it automatically calls OPTIONS method. Previously some cors issue was happening. And I solved it by adding: response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "*" Also already implemented: - django-cors-headers module installed - corsheaders.middleware.CorsMiddleware middleware installed - set ALLOWED_HOSTS = ['*'] & CORS_ORIGIN_ALLOW_ALL = True The current issue actually due to the custom header added in the request. Can anyone help please? I am in a do or fire situation. I tried various response headers from django. Is it related to back end or front end ? how to solve this? -
Django Inline Tabular admin: delete an object not working
I'm using Django admin.TabularInline class inorder to add multiple objects in a Foreinkey relationship as below: admin.py: class HeadFlowDatasetInline(admin.TabularInline): model = HeadFlowDataset extra = 0 class ProductAdmin(admin.ModelAdmin): list_display = ( ... ) search_fields = ( ... ) fields = ( ... ) inlines = [HeadFlowDatasetInline] def save_model(self, request, obj, form, change): obj.created_by = request.user obj.last_updated_by = request.user obj.save() def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() And for this purpose, this approach is working just fine. But the problem occurs when I'm trying to remove a HeadFlowDataset object from the add product object page. As shown in the picture below, there is a checkbox item in front of each HeadFlowDataset object, but checking it and saving does not work. I could not find any other way to make this work neither. Can anyone show me a way to do this? -
Django cannot authenticate or password hashing is wrong
I use a custom user model so I can authenticate using email instead of username. from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user( self, email, password, confirm_code=None, username=None, role=None, ): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.confirm_code = confirm_code user.save() return user def create_superuser(self, email, password, role, username=None): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.role = role user.is_staff = True user.is_active = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): EM = "EM" SM = "SM" DH = "DH" ST = "ST" ROLES = [ (EM, "Executive Management"), (SM, "Senior Management"), (DH, "Department Head"), (ST, "Staff Member"), ] objects = UserManager() role = models.CharField(max_length=2, choices=ROLES, default=US, blank=True) username = models.CharField(max_length=20, unique=True, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) slug = models.SlugField(blank=True, null=True) confirm_code = models.CharField(max_length=20, null=True, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) has_profile = models.BooleanField(default=False) email_verified_at = models.DateTimeField(auto_now=False, null=True, blank=True) code = models.CharField(max_length=8, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") class Meta: verbose_name = "User" verbose_name_plural = "Users" ordering = ["username"] db_table = "users" def get_absolute_url(self): return f"{self.slug}" USERNAME_FIELD = "email" REQUIRED_FIELDS = ["role"] When I register a user the user is created in the database correctly and the … -
How do i get information from my django project to my react project?
Js file ` import React, {useState, useEffact} from 'react' const CSearchPage = () => { let [users, setUsers] = useState([]) useEffact(() => { getUsers() }, []) let getUsers = async () => { let response = await fetch('http://127.0.0.1:8000/userApi/getUsers/') let data = await response.json() console.log(data) setUsers(data) }; return ( <div> <div className="users-list"> User List<br /> {users.map((user, index) => { <h3 key={index}>{user.usermane}</h3> })} </div> </div> ) } export default CSearchPage ` view.py ` from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Users from .serializers import UsersSerializer # Create your views here. @api_view(['GET']) def getUsers(request): users = Users.objects.all() serializer = UsersSerializer(users, many=True) return Response(serializer.data) @api_view(['GET']) def getUser(request, pk): users = Users.objects.get(uid=pk) serializer = UsersSerializer(users, many=False) return Response(serializer.data) ` model.py ` from django.db import models # Create your models here. class Users(models.Model): uid = models.CharField(primary_key=True, max_length=8, unique=True) username = models.CharField(max_length=35) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) search_permission = models.BooleanField() user_cud_permission = models.BooleanField() c_cud_permission = models.BooleanField() os_permission = models.BooleanField() class UsersPasswords(models.Model): uid = models.ForeignKey(Users, on_delete=models.CASCADE) password = models.CharField(max_length=12) ` I added corsheader in installed apps and the middelware as well. I have allowed all origins too. Still i am unable to get any results in react project. I … -
How to auto update django model field after a day?
How can i update is_new field tobe False after a day class post(models.Model): title = models.CharField(max_length = 250) body = RichTextField(blank= True, null =True) created_at = models.DateTimeField(auto_now_add=True) is_new = models.BooleanField(default=True) -
Django-rearart sequence of postgres id field with 0 instead of 1
I want to reset the sequence of a "postgresql" table to start from "0" in a django application. My code is: views.py sequence_sql = connection.ops.sequence_reset_sql(no_style(), [ModelName]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) print("sequence reset") The sequence is restarted successfully; but with "1". I want the sequence to start from 0. How can I achieve that? -
Change date format to "dd-mm-yyyy" in Django rest framwork
Hi below is my request payload and i am using normal serializer and i want to save date in "dd-mm-YYYY" format in DB { "start_date": "2022-10-10", "end_date": "2022-12-10" } Here is my serializer class StudentSerializer(serializers.Serializer): start_date = serializers.DateField() end_date = serializers.DateField() Note: I don't want to change the requested payload date format only change on saving the record by changing the format to "dd-mm-YYY". -
502 Bad Gateway | Gunicorn - ngnix - django
I wanted to that my dango app run in server and I tried with gunciron. When i run my app with gunicorn, server is working. I mean `# gunicorn --bind 0.0.0.0:8000 myapp.wsgi` is working But if i disconnect with server, server is not working. So i used ngnix. I followed this source https://github.com/satssehgal/URLShortnerDjango- . I did all them. I controlled my path but all path is right. What can i do for server work? -
Randomize Quiz Answers Order Django
hi everybody i want to randomize quiz answers in django this is models.py class Questions(models.Model): question = models.CharField(max_length=264, unique=True) point = models.PositiveIntegerField() def questionanswers(self): return self.question_answers.all() def __str__(self): return self.question class Answers(models.Model): question_id = models.ForeignKey(Questions, on_delete=models.CASCADE, related_name='question_answers') answer = models.CharField(max_length=20) is_true = models.BooleanField() def __str__(self): return self.answer and this is views.py question_list = Questions.objects.all().order_by('?')[:6] context['questions'] = question_list return context and this is template {% for answer in question.questionanswers.all %} <li class="col-sm-6" style="margin-bottom: 10px"> <button class="btn btn-primary" type="button" id="{{answer.id}}" value="{{answer.id}}">{{answer}}</button> </li> {% endfor %} </ol> </div> </div> {% endfor %} -
Get E-commerce products based on past searches
I am building an e-commerce store with django. I want the product page to return products based on the past searches of the user. If user A has always searched for cars and bikes, the product page would return more cars and bikes products more than other products. What is the best way to go about this? Do I save every search users make and run an algorithm to get results for that user or there are better ways to go about this. -
Django+React : CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response
I am using Django for my backend and React for my Frontend. When I try to send a POST request, I receive : Access to XMLHttpRequest at 'http://localhost:8000/package/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response. I have combined a lot of answers that I found such as How to use csrf_token in Django RESTful API and React? and Django and React: csrf cookie is not being set in request header but still no luck. 'corsheaders' is in my INSTALLED APPS Middleware settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] CORS settings: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ('cache-control',) Django view.py from django.shortcuts import render from django.views.generic.edit import CreateView from .forms import PackageForm from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie class PackageFormView(CreateView): form_class = PackageForm initial = {'key': 'value'} template_name = 'package_form.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) @method_decorator(ensure_csrf_cookie) def post(self, request, *args, **kwargs): form = … -
How to enable GEOS in Spatialite on Windows 10?
I am installing Spatialite for use in GeoDjango on a Windwos 10 64 bit system. I have already installed GEOS, PROJ, and GDAL from source in my command prompt. As spatialite requires using nmake on windows, I am using the Visual Studio 2017 command prompt to build it, however, in the README for libspatialite 4.2.0 it states that > cd c:\libspatialite-3.1.0 > nmake /f makefile.vc > nmake /f makefile.vc install Please note: standard definitions in 'makefile.vc' assumes: - enabling PROJ - disabling GEOS If you want to alter the default behaviour then make modifications in 'makefile.vc'. Also note that 'libspatialite-geos.def' contains those external symbols to be exported from the DLL when you build GEOS. as I am using GeoDjango for geographic queries I think that GEOS will be necessary. How can I enable GEOS in the makefile.vc? It doesn't seem clear to me how to do that. For convenience, here is the full makefile.vc below. # $Id: $ # # NMAKE Makefile to build libspatialite on Windows # !INCLUDE nmake.opt LIBOBJ = src\gaiaaux\gg_sqlaux.obj src\gaiaaux\gg_utf8.obj \ src\gaiaexif\gaia_exif.obj src\gaiageo\gg_advanced.obj \ src\gaiageo\gg_endian.obj src\gaiageo\gg_ewkt.obj \ src\gaiageo\gg_geodesic.obj src\gaiageo\gg_geoJSON.obj \ src\gaiageo\gg_geometries.obj src\gaiageo\gg_geoscvt.obj \ src\gaiageo\gg_gml.obj src\gaiageo\gg_kml.obj \ src\gaiageo\gg_relations.obj src\gaiageo\gg_shape.obj \ src\gaiageo\gg_transform.obj src\gaiageo\gg_vanuatu.obj \ src\gaiageo\gg_wkb.obj src\gaiageo\gg_wkt.obj \ src\gaiageo\gg_extras.obj … -
APIView post function not adding to database
I have my follow model: class Follow(models.Model): user = models.ForeignKey( "User", related_name="follower", on_delete=models.CASCADE) following_user = models.ForeignKey( "User", related_name="following", blank=True, on_delete=models.CASCADE) date_followed = models.DateTimeField(editable=False, default=timezone.now) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'following_user'], name="unique_followers") ] ordering = ["-date_followed"] def __str__(self): return f"{self.user.username} follows {self.following_user.username}" and serializer: class FollowSerializer(serializers.ModelSerializer): class Meta: model = Follow fields = ['user', 'following_user', 'date_followed'] Then in my views I have an APIView that creates the follow: class FollowingView(APIView): permission_class = [permissions.IsAuthenticated] queryset = Follow.objects.all() serializer_class = FollowSerializer def post(self, request): user = request.data.get('user') following_user = request.data.get('to_user') try: follow = Follow.objects.create( user=user, following_user=following_user) follow.save() serializer = FollowSerializer(follow) print(serializer.data) def __str__(self): return f"{self.request.username} follows {self.following_user_id.username}" return Response(serializer.data, status=status.HTTP_201_CREATED) except: return Response(status=status.HTTP_400_BAD_REQUEST) Not sure what is wrong. I am able to print the params but seems like the create function isn't going through. Appreciate any help! -
Share large python objects efficiently among requests in Django?
I'd like to share some large python objects in Django. They are just big tables of data that I'd like to quickly randomly access in memory. Think of just reading a dict that's, say 35M on disk. So, not huge, not small. I'm considering them immutable. That is, read in on initialization, never change them. I'm willing to restart the server to get changes. What is the best, most Django-friendly way to do this? This question is like mine. This answer describes how to use Django's low-level in-memory cache. Reading the documentation, there is an in-memory cache that is in-process and thread-safe. Perfect. However, only objects that can be pickled. I don't want my 35M python object pickled, that seems awkward. And then does getting it back out unpickle it again? Per request? That sounds slow. This blog post mentions django-lrucache-backend, that skips the pickling. However, it was last updated 2 years ago, and also says not to use it for "large data tables" (not sure why). Recommendations? -
the request in postman works but in angular it doesn't
enter image description here I send the bearer token returned by the login and it works enter image description here the token arrives but the api response is Authentication credentials were not provided. -
How to run "SELECT FOR UPDATE" instead of "SELECT" when adding data in Django Admin?
In PersonAdmin():, I overrode response_add() with select_for_update() so that write skew doesn't occur then only 2 persons can be added on Add person and overrode save_model() so that obj.save() works only when changing a person on Change person as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): # Here obj_count = super().get_queryset(request).select_for_update().all().count() if obj_count < 2: obj.save() return super().response_add(request, obj, post_url_continue) def save_model(self, request, obj, form, change): last_part_of_path = request.path.split('/')[-2] if last_part_of_path == "change": obj.save() # Here But, when adding a person on Add person as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": So, how can I run SELECT FOR UPDATE instead of SELECT when adding a person on Add person? -
Django: render django-countries's countries as a dropdown list (with search option)
I'm trying to make a drop down list, so users can: 1.- Select country they wanna see: from home, they'd be redirected to specific country. example: mydomain.com to: mydomain.com/mx 2.- to help them, they could also type and search specific country, and then would be redirected. I've this: forms.py: from django import forms from django_countries.fields import CountryField class CountryForm(forms.ModelForm): class Meta: model = CountryField fields = ['country'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['country'].widget.attrs.update({"class": "form-control"}) # or iterate over field to add class for each field for field in self.fields: self.fields[field].widget.attrs.update({'class':"form-control"}) html: {% extends '_base.html' %} {% load static %} {% block title %}Home page{% endblock title %} {% block content %} <form method="post" class="form-group"> {% csrf_token %} <div class="form-group col-md-12 mb-3"> <label for="{{ form.owner_name.label }}">{{ form.owner_name.label }}</label> {{ form.owner_name }} </div> <div class="form-group col-md-12 mb-3"> <label for="{{ form.car_type.label }}">{{ form.car_type.label }}</label> {{ form.car_type }} </div> <hr class="mb-4"> <button type="submit" class="btn btn-secondary btn-lg btn-block">Go to country</button> </form> {% endblock content %} -
Django signals pre_delete accessing request.user
Is there a way to access request.user within pre_delete signal? I found an answer but that was 10 years ago and doesn't work with the current version of Django. -
How to add a custom field to the Django admin login page
To authenticate, 3 fields are needed: user_id password account_id Each account_id defines an isolated space and the user_id is unique only inside its respective account_id. I've created a custom backend authentication and I can authenticate successfully. The problem is that the login Django Admin form has user_id and password fields by default. I would like to add the account_id field in the original Django form template by only subclassing AuthenticationForm, is it possible? There's a similar question here but he's using a custom login template: Add custom field to Django Admin authentication form Existing code.. Model: class HeliosUser(AbstractUser, DateModelBase): username = None user_id = models.CharField(max_length=255) USERNAME_FIELD = "user_id" REQUIRED_FIELDS = ["account_id", "role", "email"] objects = HeliosUserManager() email = models.EmailField() account_id = models.ForeignKey( "agent.Agent", on_delete=models.RESTRICT, ) ... Backend: class SettingsBackend(BaseBackend): def authenticate( self, request, user_id=None, account_id=None, password=None, **kwargs ): try: user = HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None if user.check_password(password): return user return None def get_user(self, user_id, account_id): try: return HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None Admin site: class HeliosUserAdmin(admin.AdminSite): site_title = "Helios Administration" site_header = "Helios Administration" index_title = "Helios Administration" login_form = HeliosAuthenticationForm admin_site = HeliosUserAdmin() Authentication form: class HeliosAuthenticationForm(AuthenticationForm): account_id = forms.ModelChoiceField(queryset=Agent.objects.all()) Thank's in … -
Is there any way to automatically set Debug True Django application
I have a Django API that is being deployed in PythonAnywhere. For that, I can not let the default option in settings.py as True: DEBUG=True However, the app also has a Swagger page using drf-yasg library. For that to work locally, I have to set the debug option as true. However is being troublesome to maintain it, and I often mistakenly commit it as True to the repository. Is there anyway I could manage this option so whenever I am running locally, it will automatically set it to True, but leave it as False by default? DEBUG=False -
Pass parameters or re use attributes in django serializer methods
i have this code: class InvoiceSerializer(serializers.ModelSerializer): val = serializers.SerializerMethodField() cost = serializers.SerializerMethodField() class Meta: model = Facturacion fields=["val", "cost", "others..."] def get_cost(self, object, va): print(va, "myvalue") return 1 def get_val(self, object): val = Va.objects.get(id=1) serializer = ValSerializer(valorUnitario) self.get_cost(self, object, (serializer.data)['val']) return (serializer.data)['val'] the (serializer.data)['valorUnitario'] is returning a number, i just want to pass this value to the get_cost function but it give me the message InvoiceSerializer.get_cost() takes 3 positional arguments but 4 were given. I dont want to make all the process of get_val again for optimization reasons, i just want to use the same data but in get_cost. Another form i was trying was this: def get_cost(self, object): return self.val val its supposed to be filled with the get_val method (and it shows correctly when i consume the api); but it gives the message: AttributeError: 'InvoiceSerializer' object has no attribute 'val' how can i re-use the attribute val?