Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How do I migrate a project in Django which is made in Flask?
I have a developed a project in python using Flask and Sqlalchemy as the ORM. How do I migrate the project into Django? I have gone through a couple of blogs but couldn't really understand how it should be done. How do I migrate it in Django? -
Django count column using raw
Is there anyway how can I count my paid column in my query? It is possible? thanks in advance The error says : AttributeError: 'Cursor' object has no attribute 'paid' def dictfetchall(cursor): desc = cursor.description return[ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def sample(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid", [blank]) row = dictfetchall(cursor) datas = cursor.paid print (datas.count()) -
Django Rest - Posted data creating new rows in Foreign key referenced tables
I am trying to post data to my orders model. It has several foreign keys. When I tried to post data, it is trying to create objects in the referenced models also. My models.py: from django.db import models from django.contrib.auth.models import User from accounts.models import Profile class Nursery(models.Model): name = models.CharField(max_length=30,unique=True) state = models.CharField(max_length=40) city = models.CharField(max_length=40) profile = models.OneToOneField(Profile,on_delete=models.CASCADE) class Plants(models.Model): name = models.CharField(max_length=30,unique=True) image = models.ImageField(upload_to='static/plants') price = models.IntegerField() nursery = models.ForeignKey(Nursery,on_delete=models.CASCADE) class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Plants,on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now=True) order_id = models.UUIDField(auto_created=True) is_purchased = models.BooleanField(default=False) cost = models.IntegerField() quantity = models.IntegerField() nursery = models.ForeignKey(Nursery,on_delete=models.CASCADE) So, I tried posting data into Order model, and it gave error Plant name already exists meaning that it is trying to create a row in Plants and Nursery models also. My serializers.py: from .models import Plants,Order,Nursery from rest_framework import serializers class NurserySerializer(serializers.ModelSerializer): class Meta: model = Nursery fields = "__all__" class PlantSerializer(serializers.ModelSerializer): nursery = NurserySerializer() # nursery = NurserySerializer() class Meta: model = Plants fields = ['name', 'price','image','nursery'] class OrderSerializer(serializers.ModelSerializer): user_name = serializers.CharField(source='user.username', read_only=True) product = PlantSerializer() nursery = serializers.CharField(source='nursery.name', read_only=True) class Meta: model = Order fields = ['user_name', 'product','date_ordered','order_id','is_purchased','cost','quantity','nursery'] Views.py: class PostOrder(APIView): def post(self, request, format=None): print(request.data) serializer … -
Python problem with RSA decrypting web-user password
i got a problem about decrypting a password from webfrond. I try to get password after decrypting a data,but i always get a turn which is :<bound method _UrandomRNG.read of <Crypto.Random._UrandomRNG object at 0x7f9385ea04c0>> here are my codes of decrypt-part in Django Frame. from Crypto import Random from Crypto.PublicKey import RSA import base64 from Crypto.Cipher import PKCS1_v1_5 def decrypt_pass(password): with open('crypto_info/my_private_rsa_key.pem', 'rb') as f: privkeystr = f.read() f.close() random_generator = Random.new().read RSA.generate(1024, random_generator) rsakey = RSA.importKey(privkeystr) cipher = PKCS1_v1_5.new(rsakey) return cipher.decrypt(base64.b64decode(password), random_generator) def user_login(request): random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) rsa_private_key = rsa.exportKey() rsa_public_key = rsa.publickey().exportKey() with open('crypto_info/my_private_rsa_key.pem', 'w') as f: f.write(rsa_private_key.decode()) f.close() with open('crypto_info/my_publick_rsa_key.pem', 'w') as f: f.write(rsa_public_key.decode()) f.close() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print('password_raw: ', password) print('rsa_publick_key: ', rsa_public_key) print('rsa_private_key: ', rsa_private_key) ********** Here, i just want to get my web password! password = decrypt_pass(password) print(password) ********** user = authenticate(request, username=username, password=password) if user is not None: login(request, user) status_code = 0 return JsonResponse({'code': status_code, 'url': '/'}) else: return HttpResponse('haha') return render(request, 'registration/user_login.html', {'pub_key': rsa_public_key.decode()}) -
Django - Alternative for FileSystemStorage in Production Environment
I am fairly new to django and I want to deploy my app. I have used FileSystemStorage to store my files in a Media folder in my django app however I've also read that it should not be used in a production environment. My code is essentially the same as the one shown in the geeksforgeeks website. Why can't I use FileSystemStorage in a production environment and what can I use instead? -
I am getting problem in reverse url of python django for creating the web application
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I have tried a number of different variants please take a look at my code: I have a urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from django.urls import path from .views import home_page, about_page, room_page, login_page, register_page urlpatterns = [ url(r'^$', home_page), url(r'^home/$', home_page), url(r'^about/$', about_page), url(r'^room/$', room_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^products/', include("products.urls", namespace='products')), url(r'^youadmin/', admin.site.urls), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py-myapp from django.conf.urls import url from .views import ( ProductListView, ProductDetailSlugView, ) urlpatterns = [ url(r'^$', ProductListView.as_view(), name='list'), url(r'^(?P<slug>[\w-]+)/$', ProductDetailSlugView.as_view(), name='detail'), ] A card.html <div class="card" style="width: 18rem;"> {% if instance.image %} <a href="{{ instance.get_absolute_url }}"><img src="{{ instance.image.url }}" class="card-img-top" alt="{{ instance.title }} logo"></a> {% endif %} <div class="card-body"> <h5 class="card-title">{{ instance.title }}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="{{ instance.get_absolute_url }}" class="btn btn-primary">view</a> <!-- <a href="{% url 'products:detail' … -
What are the settings.py credentials for SMS in DJANGO of integrating the third party API like SMSBOX, other than TIWILIO
WHAT WILL BE THE CREDENTIALS IN settings.py, TO SEND THIS SMS VIA THIRD PARTY API. LIKE WHERE TO GIVE # HOST_NAME, PASSWORD, API_KEY? message = SmsMessage(body='Project Created', from_phone='+923117593775', to=['+923411727228']) message.send() -
Exclude assigned objects from edit form one to one relationship in django admin forms
I have two models named RecId and Record in OneToOne relationship, models.py class RecId(models.Model): rec_id = models.CharField(max_length=255) def __str__(self): return str(self.rec_id) class Record(models.Model): rec_id = models.OneToOneField(RecId, on_delete=models.CASCADE, null=True, blank=True) desc = models.TextField() user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) def __str__(self): return str(self.rec_id) My problem is, In default, django admin Record edit form edit field (RecId field) shows all the rec_ids in RecId table. But I need to show only records that can be assigned to a Record (because the relationship between two tables is OneToOne, one id can only be assigned to one record) I tried to do that by using formfield_for_foreignkey() method but currently stucked with the query admin.py @admin.register(Record) class RecordAdmin(admin.ModelAdmin): list_display = ['rec_id', 'desc', 'user'] search_fields = ['rec_id', 'user'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "rec_id": kwargs["queryset"] = RecId.objects.all().exclude(... The query ...) return super(RecordAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) I tried to query it by using ~Exists(Record.objects.filter(rec_id__eq=OuterRef('pk'))) an hour or two ago and it didn't work. So any help is greatly appreciated. -
Django (DIFFICULT!) Why is my send interest request not appearing? Its like the variables I defined are not working
ValueError at /HomeFeed/slug-1/detail/ The QuerySet value for an exact lookup must be limited to one result using slicing. interest_list = InterestList.objects.get(interestuser=account) Hi everyone this is a big problem and I'll be super grateful if you can help me identify the problem haha: There are multiple errors in my code and this error is only one of them... Ok heres the story: In my project, people get to post blog posts, and people that read the blog post and like it can send an "interest request" maybe to comment more about the blog post and the maker of the blog post can accept or reject that interest request. Its basically something like a friend request, except the request you are sending are your "thoughts" in a form. I am trying to tilt my code while building my relationship system to fit into this "submit interest system". Ok so I have 4 models in total, one for the posts, one is my user account model, one is the interest list and the second one is the interestrequest. Theres 4 major functions, accept the request, decline the request (if you are the blog post maker) and send and unsend the request (if you … -
django: unsign values without original value
I am working on a Django app and using Django's Signer to sign my pk's in urls this is my code from django.core.signing import Signer signer = Signer() value = signer.sign(1) this gives me 1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550' and then I am using this value in my templates like <a href="edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/">Edit</a> However, I can strip the value to get the only signed value but when I need to unsign it back to use in my query, it needs the original value to unsigned. How can I unsign this value without using the original value? I don't want my URLs to look like this edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/ (Remove original pk with ':'). Thanks for any help.