Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to register a table which is created without using Django Model?
How to register the following table in apps.py or how to show this Table in admit panel? from django.db import connection cursor = connection.cursor() cursor.execute("CREATE TABLE appName_{} LIKE appName_table".format(str(request.user)+"_table")) -
How to develop a rest api without using serializer in Django Rest Framework?
I want to create a Student Register and Login Api without using serializer in django Rest Framework. So I want to know how I make CRUD operation for those api using ApiView Any one please solve this -
Check if the user who is making the request correspond to the connected user, inside "form_valid" django
I'm currently trying to improve my form, I would like to check if the connected user correspond to the user who publish the data is it possible to add a condition inside the form_valid to see if the user from the model correspond to user from the request before posting the form Model: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True) view : class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm I already tried to do that : def form_valid(self, form): if self.request.user.is_staff and self.object.user != self.request.user: return super().form_valid(form) if self.object.user != self.request.user: form.add_error(None, "You can't do that") return super().form_invalid(form) also if I'm not a staff user, I can't have access to the input to select users, it's automatically assigns <form action="" method="post"> <div style="flex-direction: column"> {% csrf_token %} <div style="margin-bottom: 10px"> {% if admin %} <label for="user">User name : </label> {{ form.user }} {% endif %} </div> I also thought of doing an sql query to see if the user making the query corresponds to the user registered for the task. no solution for the moment -
Do Server work while i dont connect? If yes how can i do?
I deployed my django app in ubuntu server. I want to give to API for mobile application. So i followed some source and i deployed. For I want to deploye django, I use gunicorn and ngnix. Server is working with this command: gunicorn --bind 0.0.0.0:8000 myapp.wsgi I can give API with this way. Everything is okey. But when i close cmd which connected to server, server stop. Can server work while i dont connect by my computer? Must not close cmd and my computer? Or can i do other way? -
Django & Bootstrap: On Load Modal
Good day I have the following issue, I have, as far as my knowledge allows me, I have tried using the bootstrap CDN and also the pip package installer method, but when I try get my modal to show then I cant get it work, could someone have a look at my code and let me know index.html {% load static %} {% load bootstrap5 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Landing Page</title> {% comment %} Bootstrap {% endcomment %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous" ></script> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> <script type="text/javascript"> $(window).on("load", function () { $("#myModal").modal("show"); }); </script> </head> <body> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <div class="modal hide fade" id="myModal"> <div class="modal-header"> <a class="close" data-dismiss="modal">x</a> <h3>Modal header</h3> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <a href="#" class="btn">Close</a> <a href="#" class="btn btn-primary">Save changes</a> </div> </div> {% comment %} header {% endcomment %} <header> <img src="" alt="" /> </header> {% comment %} Main Conntent {% endcomment %} <main> <div class="row"> <div class="text-center"> <button id="btnSubmit" type="submit" class="btn btn-danger py-2 px-5 text-center d-flex align-items-end" > Enter … -
Django send_mail: Only send Bcc Email when someone enters an email address
I'm using the Django Rest framework and send_mail to send out an email from a react form. There is two email fields but sometimes the bcc field does not get filled out and the email sending will fail. Is there a way to add an if statement or to tell django some other way to ignore bcc if there is no bcc value being sent? I'm getting this error in the backend log: anymail.exceptions.AnymailInvalidAddress: Invalid email address '' parsed from '' in `bcc`. views.py @api_view(['POST',]) def proposal(request): if request.method == "POST": serializer = PropEmailSerializer(data=request.data) if serializer.is_valid(): ClientName = request.POST['ClientName'] Sender = request.POST['Sender'] Bcc = request.POST['Bcc'] Facilities = request.POST['Message'] AgentPhone = request.POST['AgentPhone'] AgentName = request.POST['AgentName'] merge_data = { 'greetings': ClientName, 'facilities': Facilities, 'agentname': AgentName, 'agentphone': AgentPhone, } html_body = render_to_string("email-templates.html", merge_data) message = EmailMultiAlternatives( subject='Test', body="", from_email='noreply@test.com', to=[Sender], bcc=[Bcc] ) message.attach_alternative(html_body, "text/html") message.send(fail_silently=False) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
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.