Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add the existing google analytics account to my website in python django
Actually i have multiple users in my website. Everyone have google analytics account, how to fetch the details of the account only by clicking the login with google analytics button. -
Current path didn't match any of these
I'm trying to make it so that after a user register, it will redirect to the login page again but I got an error. Base.html: <button class="button"><a href="{% url 'login' %}?next={{ request.path }}"> LOGIN </a></button> <div> {% if user.is_authenticated %} Hello, {{ user.get_username }} <a href="{% url 'logout' %}?next={{ request.path }}">Log Out</a> {% else %} {% if 'login' in request.path %} <a href="{% url 'login' %}?next={{ '/' }}">Log In</a> {% endif %} {% endif %} </div> project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('drinks.urls')), path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py: LOGIN_REDIRECT_URL = '/' STATIC_URL = '/static/' app/urls.py: from django.urls import path urlpatterns = [ path('register', registration_controller.index, name='register'), ] registration_controller.py: from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.shortcuts import render from django.conf import settings def index(request): msg = '' if request.method == 'POST': req = request.POST.dict() username = req['username'] password = req['password'] email = req['email'] try: user = User.objects.get(username=username) msg = 'Username or E-Mail is already Registered' except User.DoesNotExist: user = User.objects.create_user(username, email, password) user.save() msg = '' send_mail( 'Registration Successful', 'You are now an official member … -
Blocked Set-Cookie in development environment DRF SessionAuthentication + React
I have a very specific question that I haven't found within the many questions regarding this topic. I have a DRF + React web application which I recently changed from Token Authentication to Session Authentication for server side expiration. In production this works great, upon login I receive two Set-Cookies, a session id and a csrftoken. However, in my development environment, the Set-Cookies are blocked as This Set-Cookie was blocked because it had the 'SameSite=Lax' attribute but came from a cross-site response which was not the repsonse to a top-level navigation.. I tried changing the SameSite setting to none, in which case Chrome requires secure cookies, which I don't think is possible in my dev environment. I tried disabling Cookies without SameSite must be secure in chrome://flags. Listing localhost in CSRF_TRUSTED_ORIGINS solves the CSRF, but then the login issue remains. Although I don't think this is relevant, a lot of solutions here mention to add {withCredentials: true} to the requests, this however does not solve my issue as I do receive the Set-Cookie headers, they're just blocked... -
Django Superuser cant change user permission - change user type to staff
I am creating a Django Project with python 3.6 & Django V 2.2 . Now in the Django Admin panel ( Super User) cant convert a user type to staff . also it is not able to edit some user fields also. I have tried DB.Sqlite on my Local Host and PostgreSQL DB ( PG Admin on ) Apache2 Server. Kindly provide me any solution for my problem. I have been described all related codes below. also find the attached file for my problem. Django Admin shows success message. But No result on action (https://i.ibb.co/tDstxff/django-adminerror.png)Error after change user to staff My Project files are : models.py #ProApp/Models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models import Sum from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from datetime import date import datetime User = settings.AUTH_USER_MODEL #Create your models here class CustomUserManager(BaseUserManager): def _create_user(self, username, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password): if not username: raise ValueError('missing … -
Recreating a file-based POST request from Django-Rest-Framework test in curl
I have a test case using The test library from Django. In my test I have the following: class TestLoadCurve(TestCase): def setUp(self): self.client = Client() self.test_user = User.objects.create_user('test_user', 'a@b.com', 'test_user') self.client.login(username="test_user", password="test_user") def test_post_loadcurve_as_xlsx(self): response = self.client.post( reverse('loadcurves-list'), {'file': open("app/tests/loadcurve_files/loadcurve.xlsx", "rb"), "name": "testuploadloadcurve"}, ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And the (simplified) endpoint looks like this: class LoadCurveViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): ... def create(self, request, *args, **kwargs): up_file = request.FILES['file'] ... return Response(status.HTTP_201_CREATED) This test works. But I want to re-create the POST request that it makes using curl for some documentation. I have only made it so far: curl --user <myuser>:<mypass> -X POST -H --data-urlencode "payload={\"file\": $(cat app/tests/loadcurve_files/loadcurve.xlsx), \"name\": \"curlloadcurve\"}" http://localhost:5100/loadcurves/ Using the debugger I am able to stop the processing at the line up_file = request.FILES['file'], at which point I realize that both request.FILES and request.data are both totally empty. Am I not making the POST request correctly? I was following this answer Python version is 3.6.9 Django version is 3.1.3 -
Django - perform action on Profile while creating User
I was looking for solution for my problem here, but it didnt solve my problem. I want to create user's profile while their signing up. To signup I use CreateView class UserRegisterView(generic.CreateView): form_class = SignUpForm template_name = 'registration/register.html' success_url = reverse_lazy('login') #this method doesn't work and I get # `Profile.user" must be a "User" instance` def form_valid(self,form): Profile.objects.create(user=self.request.user) My Profile model looks like: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #rest of fields like bio, social urls etc My main point is to automatically create user's profile when their create their account. What is the best way to solve this? -
Validations errors are not raising in clean function, Why?
Well I'm using the Userprofile form with the UpdateView and the errors are not raising even if my condition is true. What is the possibility of this unwanted behavior. forms.py. class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ("avatar","username","first_name","last_name","age","gender") # fields = ("avatar",) Gender = ( ('one','Male'), ('two','Female'), ) widgets ={ 'age' : forms.TextInput(attrs={'class':'form-control'}), 'gender' : forms.Select(choices=Gender,attrs={'class': 'form-control'}), } # TRIED THIS AS WELL # def clean_age(self): # age = self.cleaned_data["age"] # print(age,'hm here') # if age < 18: # print(age,'hm here') # raise forms.ValidationError("You're age should be 18 plus") # return age def clean(self): cleaned_data = super().clean() age = cleaned_data.get('age') print('haye',age) if age < 18: print(age,'hm here') # raise forms.ValidationError("You're age should be 18 plus") age = "You're age should be 18 plus" self.add_error('age',age) raise forms.ValidationError("You're age should be 18 plus") Please tell me how can i fix this issue and raise errors on unvalid details. If more information is require then tell me in a comment section, I'll update my question with that information. -
foreign key mismatch - "app_employee" referencing "app_mycustomeuser"
I am working with a custom build user model in Django. My app name is app. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user') industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') i_id = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False) class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='inspector_releted_user') inspector_extrafield = models.TextField(blank=True) class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='admin_releted_user') admin_extrafield = models.TextField(blank=True) There was also a AUTH_USER_MODEL = 'app.myCustomeUser' in my settings.py. I have drop my full database, then I run makemigrations and it reported totally normal as No changes detected in app 'app'. But after that when I run migrate command it shows following error in my terminal: Operations to perform: Apply all migrations: app Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying … -
error 403 csrf token when using multiple post method with action attribute
i got a page how have multiple POST method , so i used the action attribute in ajax to recognize each of the post method , but when i tried to use it on the form how add a model into the database (client model), it said 403 error invalid or missing csrf token, but when i remove the action and let only the REQUEST.METHOD == 'POST', it work , so i didnt understand why the csrf token is not working when i use the action , i solved the problem by getting directly the values of input form but is better if i use the automated feature of django forms so their is my old code . ajax request: $(document).ready(function(){ var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); //$("#alert-container").hide(); //console.log(csrfToken); $("#btn-submit").click(function() { var serializedData = $("#ClientForm").serialize(); console.log("hey hey clients!"); $.ajax({ url: $("ClientForm").data('url'), data :{serializedData,action: 'client'}, type: 'post', success: function(response) { console.log(response.client.name); console.log($("#ClientList")) } }) $("#ClientForm")[0].reset() }); }); html form : <form class="contact-form" id="ClientForm" data-url="{% url 'addclient' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name" class="sr-only">Name</label> {{ form.name }} </div> <div class="form-group"> <label for="email" class="sr-only">Email</label> {{ form.email }} </div> <div class="form-group"> <button type="button" id="btn-submit" class="btn btn-success btn-md">Add Client </client> </div> </form> View.py: def … -
How to make obj.save() without reversing object values in the db in django
I have recursive function and obj.save() is inside it. how to prevent the query from db at every iteration. -
error "ORDER BY not allowed in subqueries of compound statements". In dango while using Union fuction
"ORDER BY not allowed in subqueries of compound statements." in Django while using Icontains to join two querysets, problem comes when i join a third query set Such as slug with some special characters My Views; if len(query)>78: myposts = Blogpost.objects.none() else: post_title = Blogpost.objects.filter(title__icontains=query) posts_content = Blogpost.objects.filter(content__icontains=query) posts_overview= Blogpost.objects.filter(overview__icontains=query) myposts = post_title.union(posts_content, posts_overview) if myposts.count() == 0: messages.warning(request, "No search results found. Please enter again.") context = {'myposts': myposts,'query':query} return render(request, 'blog/search.html', context)``` -
How to copy encoded password from one Django model into another?
For some reason, I initially save my users to a temporary table, and only later do I copy them to a table that uses Django's User. My question is: How do I copy the password field from the temporary table to the permanent table? Of course I do not keep the password as it is in the temporary table, but use the make_password function of Django. How do I enter it, when it's already encoded, into a password field in Django's user table, without it going through encoding again? Pseudo code for illustration: step one MyTempModel.objects.create(email=email, password=make_password(password)) step two PermanentModelUsedUser.objects.create(email=temp_user.email, password=temp_user.password) -
Download and print Image from ImageField of Django
I have an ImageField in models, which stores generated QR codes. I want to add a download button in my html page, which, when clicked, will allow the user to download the ImageField image as a png file. Please help me out with how I can achieve this. -
How to get a data and show in the template which is referenced with foreign key in Django models?
Used: pgAdmin 4 version 4.28 django.VERSION (3, 1, 4, 'final', 0) main_app/models.py class reportType(models.Model): report_type_x = models.CharField(max_length=30, blank=True) def __str__(self): return self.report_type_x class addForm(models.Model): report_type = models.ForeignKey(reportType, blank=True, null=True, on_delete=models.CASCADE) main_app/views.py def add_rep_view(request): obj = addForm.objects.all() args = { 'obj': obj, } return render(request, 'main_app/add_report.html', args) main_app/add_report.html <select class="form-control form-control-line"> {% for t in obj %} <option value="{{ t.report_type.id }}">{{ t.report_type }}</option> {% endfor %} </select> Blank options in the template with this way, but if I directly render reportType model to the template, it shows my options which I created. Foreign key is not working for me or I do not fully understand how to render it. Any help is appreciated, I am beginner in Djnago ;) -
Django filter duplicates data
i have this response from my endpoint on Django { "count": 4, "results": [ { "id": 1, "category_name": "Big Car", "car_name": "Chev 45" }, { "id": 2, "category_name": "Best Seller Car", "car_name": "Chev 45" }, { "id": 3, "category_name": "Cheapest Car", "car_name": "Chev 45" }, { "id": 4, "category_name": "Monster Car", "car_name": "Chev 44" } ] } How do i filter the result so it only displayed once? because the response has 3 diffrent data (same car name, but different category, i only want to display 1). Expected Result { "count": 2, "results": [ { "id": 1, "category_name": "Big Car", "car_name": "Chev 45" }, { "id": 4, "category_name": "Monster Car", "car_name": "Chev 44" } ] } without altering the query ? just filtering the result. -
RelatedObjectDoesNotExist at /post/ Post has no user
※ I'm not at good English. So I'm sorry if there are parts of my writing that you don't understand. I am trying to create a Simple Django Application. In the model, I want to store the paths to the files submitted by users by user. So I read Django document def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) and I imitated it because it was written this way. However, when sending the file RelatedObjectDoesNotExist at /post/ Post has no user. I get this error. Where I do mistakes? My code is as follows. posts/views.py def post(request): form_class = PostForm form = form_class(request.POST or None) if request.method == 'POST': form = PostForm(request.POST, request.FILES) files = request.FILES.getlist('file') if form.is_valid(): for f in files: file_instance = Post(file=f) file_instance.save() else: form = PostForm() return render(request, 'posts/post.html', {'form': form}) posts/models.py def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Post(models.Model): class Meta(object): db_table = 't_post' def validate_file(fieldfile_obj): filesize = fieldfile_obj.file.size megabyte_limit = 5.0 if filesize > megabyte_limit*1024*1024: raise ValidationError("Please make the file size smaller than %sMB" % str(megabyte_limit)) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) file = models.FileField( upload_to=user_directory_path, null=False, blank=False, validators=[validate_file, FileExtensionValidator(['mp4', 'mp3', 'jpeg', 'jpg', 'png'])], … -
How do you repeat card tags in django, forloop?
<div class="mt-5 mb-5" id="list"> <div class="row"> {%for i in library_list%} <div class="col-sm-12 col-md-4 mb-5"> <div class="card" style="width: 18rem; display: flex;""> <img src='{{i.url}}' width=" 200px" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{i.book_name}}</h5> <p class="card-text">{{i.explain}}</p> </div> </div> </div> </div> {%endfor%} </div> When you write the code, only one card is printed per line. How do I fix the code to allow multiple cards to be printed in one line? -
Heroku Django Template Date error 'str' object has no attribute 'year'
I got an error after deployed my app to Heroku but in my localhost work perfectly.How to solved this error? All codes running good in localhost. Error Error: 'str' object has no attribute 'year' But if I delete this line in my table and deployed again to heroku work's good. {% for CC in pending %} ......... <td><span>{{ CC.Date_resolved_inital|timeuntil }}</span></td> {% endfor %} This is my Date_resolved_initial DateTimeField format 2021-01-10 18:00:42.184844+08 -
How to use django-two-factor-auth in backend Django project?
I want SMS 2fa on login and ideally would use a project like django-two-factor-auth for it, but I can't figure out how to apply it to my backend, is it not designed to be used in backend projects? -
Clean_field functions are not working properly with updateview. How can we correct this behaviour?
Well I am creating user profile with signals and whenever new user registered, its profile will automatically created and now i want to filled the profil field according to user registration form fields. And then from user side when user go to its profile after login, He will see form which is filled with the information which he/she provided in the registration. If he wants to change some of his information then he can change that. Now the problem is we have to update user model as well as userprofile model in the same time according to the information that user provide in the profile form. right now in my code, conditions and checks are not working properly in forms.py.. views.py class UserProfile(models.Model): user = models.OneToOneField(auth.models.User,related_name='userprofile', on_delete=models.CASCADE) avatar = models.ImageField(("displays"), upload_to='displays', height_field=None, width_field=None, max_length=None,default ='user.jpg') create_date = models.DateTimeField(default = timezone.now) Gender = ( ('one','Male'), ('two','Female'), ) first_name = models.CharField(("first_name"), max_length=50,null=True) last_name = models.CharField(("last_name"), max_length=50,null=True) username = models.CharField(("username"), max_length=50,null=True) age = models.IntegerField(("age"),null=True) gender = models.CharField(("gender"), max_length=50,choices=Gender,null=True) def save(self,*args, **kwargs): if not self.username: self.username = self.user.username if not self.age: self.age = self.user.age if not self.gender: self.gender = self.user.gender if not self.first_name: self.first_name = self.user.first_name if not self.last_name: self.last_name = self.user.last_name super(UserProfile,self).save(*args, **kwargs) … -
i have Website with many users each users post the Ad separately and want to post the individual post to the users Facebook page
I have the website of existing users, user post the Ad to website after that user want to publish to there faceboook page separately, How to do this thing please help me out. -
Django: Link two models with common foreign keys
Im new to django and im currently making an admin panel where i can view user orders. I handle my orders based on the following OrderItem Model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) and their shipping info in the follwing ShippingAdress model class ShippingAddress(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) Views.py orders=OrderItem.objects.select_related('customer') context={ 'orders':orders, } return render(request, 'index.html', context) and in my html i want to print each customer's ShippingAdress data. Im thinking something like the following but im stuck and it doesnt work. {% for order in orders %} <td>{{order.customer.address}}</td> <td>{{order.customer.city}}</td> {% endfor %} What is the correct way to achieve this? -
Django WebSockets / channels automatically disconnects. Unable to send any messages
My django channels web socket automatically disconnects all the time and I have not been able to send a message. no matter what I do, the web sockets still disconnects, and so I also dont know which part of my code is causing the problem as I am entirely new to django. Can anyone advise? Thanks! Routing.py in mainproject files from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) chat app routing.py from django.urls import path, re_path from chat import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/(?P<person_name>\w+)/$', consumers.Consumer), ] consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer, WebsocketConsumer from asgiref.sync import async_to_sync class Consumer(WebsocketConsumer): def connect(self): self.person_name=self.scope['url_route']['kwargs']['person_name'] self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Joined Chat" } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.person_name+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) chatscreen.html {% extends 'base.html' %} {% load static %} {% block content %} <div style="height:500px;width:100%;overflow-y:scroll" id="div_data"> </div> <div> <input type="text" … -
Nginx - Django : After restart website doesn't work anymore but keep working for the admin part
I'm a bit embarrassed about this question because something doesn't work correctly and I don't understand why. Let me explain : I'm using all of this with docker. Each one has its own container. I update something on my project (new folder on the repository nothing related to the website) and once my production version (on the server) gets the update, Nginx and Django restart but from this exact moment: my homepage shows me Index of ../. So I tried to restart both containers but it changes nothing and something really strange is that if I go to the Django admin it works! So I don't understand what's happening here ... And I have run this for almost 1 year ... Here is my Nginx mysite.conf upstream django { server webserver:8000; } # redirect http traffic to https server { listen 80; listen [::]:80; # ignore cache frontend # location ~* (service-worker\.js)$ { # add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; # expires off; # proxy_no_cache 1; # } location / { root /var/www/app_frontend; try_files $uri $uri/ /index.html; } # server_name app.mydomain.com; # serve static files # location /static/ { # alias /static/; # } # serve media files # … -
Multi file upload using DRF -django rest framework
I am trying to upload multi-images to a single post which currently I am being able to upload only single image and get the confirmation through API. How can I make this to multi upload ? My models.py from django.db import models # Create your models here. class UploadedImage(models.Model): img = models.ImageField('Uploaded Image', upload_to='images') # stores uploaded image dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Created') my serializers.py from rest_framework import serializers from .models import UploadedImage class UploadedImageSerializer(serializers.ModelSerializer): class Meta: model = UploadedImage fields = ('pk', 'img', 'dt_created') my viewsets.py from django.shortcuts import render from rest_framework import viewsets from imageUpload.serializers import UploadedImageSerializer from imageUpload.models import UploadedImage # Create your views here. class UploadImageViewset(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = UploadedImageSerializer