Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django media image not found when there is a trailing slash at the end
I added users avatar today and applied it for my current 15 users or so when i was migrating, i just found out that the path wan't specified correctly so I had a look at my admin page to see what went wrong. The wrong avatar url which all users currently have: ...DefUser.png/ The correct one: ...DefUser.png With the trailing slash it gives error, without gives the correct image. Is there anyway to fix that?! If not then How can i change the avatar image of all the current existing -15- users and make them all point to the same image? The code models.py class User(AbstractUser): ... avatar = models.ImageField( upload_to='users/img/avatar/', default="users/img/avatar/DefUser.png/") settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' AUTH_USER_MODEL = 'users.User' LOGIN_URL = '/signup/' urls.py: from django.conf.urls.static import static from django.conf import settings from django.urls import path, include ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
what does the plus sign mean in return redirect('/details/+product_id')
just need a brief expalanation , i stumbled over this randomly in a Django example, but couldn't find explanation def contact(request): if request.method == 'POST': product_id = request.POST['product_id'] product= request.POST['prodcut'] name = request.POST['name'] email = request.POST['email'] if request.user.is_authenticated: user_id = request.user.id has_contacted = Contact.objects.all().filter(prodcut_id=product_id, user_id=user_id) return redirect('/details/+product_id') i'm just lookin for the signification of using "+" in the redirect, if someone know Thank you very much -
Passwordless user registration in Django
How can I customize Django's default user model to password less authentication similar to Whatsapp? Only (use mobile number and OTP to verify) -
Elastic Beanstack Deployment w/ Django Docker Postgresql
AWS Elastic Beanstalk has an option to deploy Django apps, I don't want to use this option because I want to have the flexibility of using Docker. So I am choosing to deploy my Django app through the elastic beanstalk Docker platform instead. However, there isn't much documentation on how to configure a Django app with Docker for AWS EB and I cant find an example on github. My question is: What do I need to configure in my Dockerized Django app to run on AWS EB ? NGINX, Gunicorn, or both ? Is there an example of this somewhere I could look at. -
Django - How to trigger signals on multi type user create with one AbstractUser model
So I had this custom user model on my project. I want the user can register as a Profile and Client. I created two different models extended from my custom User model. The problem is, every time I sign-up from the client form, it also saved to the Profile model, And the opposite. Let say on my accounts app: # model.py class User(AbstractUser): username = models.CharField(max_length=100, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) gender = models.CharField(choices=GENDER, max_length=10) class Meta: db_table = 'auth_user' def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... email = models.CharField(blank=False, null=False, max_length=100) phone = models.CharField(blank=True, null=True, max_length=14) class Meta: verbose_name = 'Influencer Profile' def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And then inside my client app: # model.py from accounts.models import User class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... company_name = models.CharField(max_length=50, unique=True) class Meta: verbose_name = 'Client Profile' def __str__(self): return f'{self.username} Client Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And my signals.py looks like: accounts/signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And one more signals on my clients app: @receiver(post_save, sender=User) … -
django display category name
I want to display the category name of a product when I enter it, how can I do this? How can I get the category name of each product? my model : class Category(MPTTModel): parent = TreeForeignKey('self', models.CASCADE, related_name='children') sub = models.BooleanField(default=False) name = models.CharField(max_length=300, ) ... class Product(models.Model): category = models.ManyToManyField(Category, related_name='category_product') .... my view : def test(request, id): products = get_object_or_404(Product, id=id) return render(request, 'home/new.html', {'products': products }) my template: <div class="card"> <h2>{{ products.name }}</h2><br><br> <p>{{ products.price}}</p><br> <p>{{ products.discount }}</p><br> </div> -
How to get primary key from template in django?
Here I am trying to get user_to_toggle id but that is coming none and i guess this is because i am doing something wrong. I am confuse that how can i get user_to_toggle id. I am getting his username but i want user id too. Here is my code. views,pyy class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request, *args, **kwargs): user_pk_to_toggle=kwargs.get('pk') #this is returning None. username_to_toggle = request.POST.get("username")#this is returning me username of toggle user. profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id ,username_to_toggle) return redirect(f'/profiles/{username_to_toggle}') follow_to_toggle.html <form class='form' method='POST' action="{% url 'profiles:toggle'%}"> {% csrf_token %} <input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}hello{% endif %}"> <button class='btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow {% else %}Follow{% endif %}</button> </form> if more code is required than tell me i will update my question with that information. -
Only one of the two model forms work, the second one is not working properly
I have two model forms in the same view relating to the same object model. They have different objectives, that's why I keep them separate. However, the first one changes the transaction_type attribute after saving, the other one does not. If I change the order and put the fasttransactionform first, it will change the transaction_type but then the fastcollectionform will not change the transaction_type. I appreciate your help, thanks in advance. views.py fastcollectionform = CollectionModelFormFast(request.POST) if fastcollectionform.is_valid(): transaction = fastcollectionform.save(commit=False) transaction.transaction_type = "Tahsilat" transaction.save() return redirect(request.path) fasttransactionform = TransactionModelFormFast(request.POST) if fasttransactionform.is_valid(): transaction = fasttransactionform.save(commit=False) transaction.transaction_type = "Harcama" transaction.save() return redirect(request.path) -
Django paginating a list: TypeError: Object of type Page is not JSON serializable
I'm having troubles in paginating objects in my view. Suppose I have this view: def my_view(request): # operations... predictions = MyModel.objects.filter(user_id=request.user.id) paginator = Paginator(predictions, 5) page = request.GET.get('page', 1) try: predictions_pages = paginator.get_page(page) except PageNotAnInteger: predictions_pages = paginator.get_page(1) except EmptyPage: predictions_pages = paginator.get_page(paginator.num_pages) context['predictions'] = predictions_pages request.session['context'] = context return HttpResponse("ok") I get this error: TypeError: Object of type Page is not JSON serializable Following the approach suggested in this great answer, I tried this: predictions_pages2 = list( map(lambda pred: pred.as_dict(), list(predictions_pages)) ) context['predictions'] = predictions_pages2 And this does not return any error, however the behavior is not as intended. Suppose I have 100 predictions, so I should have 20 pages of 5 items each. And with the first approach this holds, I have 20 Pages but there is that one error of JSON serialization. With this second approach, what I have in my template under request.session.context.predictions is a list with only 5 items, which I suppose are the items of the first page, but I don't get all the other items. Indeed, printing: print(len(predictions_pages2)) print(type(predictions_pages2)) I get: 5 <class 'list'> I don't really understand what I'm doing wrong, can you please help me? In my template, for the pagination, … -
Difficulty adding unique event listener to created <div> elements via a for loop
I'm working on a project to learn some JavaScript, the goal is to serve up emails dynamically in a single page web application. The HTML of the application has been created using the createElement JS method. So far I have managed to display the "inbox" page with all of the emails in it, as illustrated below: I'm currently attempting to make each of these individual emails clickable through the use of an addEventListener. The issue that I'm having is that whenever I click any of the emails, the first email in the inbox (id:1, subject:Test Email) is rendered and it is not possible to view any of the others. I can see that the same email.id is being applied to the event listener for all of the created divs, despite all of the divs being created correctly, with all of the information from the corresponding emails. Here is the load mailbox JS, which renders all of the emails within the inbox: function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#single-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // GET request fetch(`/emails/${mailbox}`) .then(response => response.json()) .then(emails => … -
Why is that some data is not being created during django testing
I am testing my django application. I have created JobSeeker and Employer data in the setUp method. Now the test_edit_job_seeker_data is failing with an error. It says no resource was found. Which I am guessing the JobSeeker data was never created but the Employer data was created. Here is the code for the testcase. class TestViewsLiveServer(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() date_str = "2020-09-15" temp_date = parse_date(date_str) # Create a list of employer objects Employer.objects.create( firstname="Patrice", lastname="Chaula", phone_number="+263782841339", physical_address="4790 Mkoba 12, Gweru, Midlands", email_address="chaulapsx@gmail.com", job_title="Carpenter to adjust my kitchen unit", job_description="I am searching for a carpenter to fix my kitchen unit.", status=False, date_needed=temp_date ) date_str = "2020-09-20" temp_date = parse_date(date_str) Employer.objects.create( firstname="John", lastname="Doe", phone_number="+263782841339", physical_address="4790 Mkoba 12, Gweru, Midlands", email_address="johndoe@gmail.com", job_title="Motor mechanic for engine overhaul", job_description="I am currently looking for a motor mechanic for my engine overhaul.", status=False, date_needed=temp_date ) # Create a list of job seeker objects JobSeeker.objects.create( firstname="Patrice", lastname="Chaula", phone_number="+263782841339", physical_address="4790 Mkoba 12, Gweru, Midlands", email_address="chaulapsx@gmail.com", job_title="Carpenter to create me something", status=False, date_applied=temp_date ) date_str = "2020-09-20" temp_date = parse_date(date_str) JobSeeker.objects.create( firstname="John", lastname="Doe", phone_number="+263782841339", physical_address="4790 Mkoba 12, Gweru, Midlands", email_address="johndoe@gmail.com", job_title="Motor mechanic for engine overhaul", status=False, date_applied=temp_date ) def test_edit_employer_data(self): url = self.live_server_url + reverse("edit-employer", kwargs={"pk": 1}) self.browser.get(url) … -
GDPR (DSGVO) relevant concerns for website
we would ask for your professional assessment of data protection issues that arose during the development of a website. This is intended to establish, mediate and manage networks through which locally produced goods can be displayed and distributed. For this purpose, a user can register on our website with an email address and username, set up a network and provide key data about his offer, which is then displayed to all other visitors. A contract between the provider and a registered consumer is not explicitly managed by us. However, we do provide a chat that users can use to clarify everything else. There is also a public blog for each network, in which only certain people are allowed to create amounts, as well as a newsletter from us that everyone can subscribe to. All of our services are free of charge, but a PayPal button for voluntary donations should be implemented. In the course of development, the following questions came to mind: Do you have to pay attention to something special when implementing a chat, for example special encryption? Should a user be allowed to delete his posts directly and permanently without us being able to restore them within a … -
Django: '<' not supported between instances of 'model_instance' and 'model_instance'
I am trying to find the first and highest value in my table for each ID, and if the if-statement is true; add it to my counter. Views.py keep_track = 0 # if the first weight is less than the highest weight, add +1 to the counter keep_track for fruit in Fruits.objects.all(): one = Fruits.objects.all().first() two = Fruits.objects.all().order_by("-weight").first() if one < two: keep_track += 1 print(keep_track ) I thought this would be doable, but I do not quite understand why I receive the following error message: TypeError: '<' not supported between instances of 'Fruits' and 'Fruits' Any suggestions out there? -
Django stripe webhook 403
I have built webhook to receive confirmation of payment. @csrf_exempt def stripe_webhook(request): print('fired') api_key = config_by_name('stripe_secret_key') stripe.api_key = api_key payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event(payload, sig_header, config_by_name('stripe_webhook')) except ValueError as e: return HttpResponse(status=400) except SignatureVerificationError as e: return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] print(session) return HttpResponse(status=200) return HttpResponse('Thanks') I am using stripe cli for testing at local machine. For some reason inside the stripe cli I can see that my local server is giving 403. But I can't see any debug messages inside the django, any errors. Just like nothing came. -
How to integrate Opencv and Django
I have a Django Model that a accepts a video from a user and saves to the media folder. Then I converted the uploaded video to frame using opencv but the opencv script does not convert the video but rather it saves the uploaded video to media. I want a frame to be save to the media folder not a video from django.db import models from datetime import datetime from django.core.files.base import ContentFile import cv2 import tempfile import io import os from PIL import Image class MyVideo(models.Model): name= models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) # action = models.CharField(max_length = 50, choices = ACTION_CHOICES) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") # mod = models.FilePathField def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): #Opens the Video file cap= cv2.VideoCapture(self.videofile) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: self.cv2.imwrite(('new_image'+str(i)+'.jpg'),frame, save = False) super().save(*args, **kwargs) i+=1 cap.release() cv2.destroyAllWindows() -
How to use checkboxes to select or discard objects linked to another object by ForeignKey?
models.py class ShoppingList(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) # and so on.. class Item(models.Model): shopping_list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE) # and so on.. So in line with the DRY principle, I'm trying to add items to the 'wishlist' (where you can add as many items as you can), and the actual 'shoppinglist' (where you can deselect items) in one html (just different urls and functions). In terms of the two's model, it's just ShoppingList with different set of operations to them (add and select/delete, respectively). Here's what I got in list.html: # snip... <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form1.as_p }} {% for item in items %} {{ item.quantity }} {{ item.name}} {{ item.description }} {{ item.image }} {% if doc_type is 'shoppinglist' %} <input type="checkbox" name=item.name> {% endif %} {% empty %} {% endfor %} {{ form2.as_p }} {{ form3.as_p }} <input type="submit" value="Submit"> </form> # snip.. So if I accessed the html through views with the context of 'doc_type':'wishlist', the extra checkboxes won't appear, but if I access it with 'doc_type':'shoppinglist' the checkboxes appear. Now the part I'm lost is how to collect those checkbox inputs and relate them to the items they're with. Or some other way. … -
Return custom response in django rest
I have registration in django rest and after that it returns data to me in response. Is there a way to somehow change the response and hide some data, such as a password? Views class CreateUserView(generics.CreateAPIView): """Отображение регистрации пользователя для всех прав доступа""" queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = CreateParticipantSerializer -
skip_unchanged and report_skipped in django import-export
The django import-export documentation says report_skipped= True Controls if the result reports skipped rows Default value is True skip_unchanged= False Controls if the import should skip unchanged records. Default value is False I Don't quite understand what they are trying to say, I have used them(copy-pasted without understanding).Can someone please explain what they are used for. Thank you. -
make an async transaction with django
i have a code structure like below. When I run the application, I get an error like the following. How can I fix this? database postgresql raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. @require_POST @csrf_exempt def webhook(request): webhook_received_json = json.loads(request.body) queryset = CryptoInfo.objects.filter(symbol=webhook_received_json['symbol']) table_data = serializers.serialize('json', queryset) for pair_list in json.loads(table_data): if pair_list['fields']['symbol'] == webhook_received_json['symbol']: # position update entryPrice asyncio.run(get_position_update(futures_api_key=pair_list['fields']['futures_api_key'], futures_secret_key=pair_list['fields']['futures_secret_key'], symbol=pair_list['fields']['symbol'],)) async def get_position_update(futures_api_key, futures_secret_key, symbol): client = Client(futures_api_key, futures_secret_key) data = client.futures_position_information() for sym in data: if sym['symbol'] == symbol and sym['positionAmt']: await CryptoInfo.objects.filter(futures_api_key=futures_api_key, futures_secret_key=futures_secret_key, symbol=sym['symbol']).update( entryPrice=sym['entryPrice']) return get_position_update -
workon command does nothing in vscode
I am learning Django and new to web development. I have installed django, installed and created venv using windows cmd. Now i am in vscode and after importing project file I was trying to run/activate the venv(virtual environment) using workon command in vscode terminal but nothing happens. Please help me.I am really new to backend stuff. Thanks Issue image: enter image description here -
Python Django 'User' has no objects
from django.shortcuts import render, HttpResponse,get_object_or_404 from .models import Post # Create your views here. def post_index(request): posts = Post.objects.all() return render(request,'post/index.html',{'posts':posts}) def post_detail(request, id): post = get_object_or_404(Post, id=id) context={ 'post':post, } return render(request,'post/detail.html',context) def post_create(request): return HttpResponse("Burası Post create sayfası") def post_update(request): return HttpResponse("Burası Post update sayfası") def post_delete(request): return HttpResponse("Burası Post delete sayfası") Thats my view.py code but I am always get this message "Class 'Post' has no 'objects' member" How can I solve this problem? -
mod_wsgi is problematic with Django and venv. Can't be loaded as python module. ModuleNotFoundError: No module named 'django'
I'm trying to setup Django project with Apache and mod_wsgi and couldn't get it to work. Searched all answers, but nothing helped. python-home=/var/www/example.com/venv python-path=/var/www/example.com/myproject Location of wsgi.py - /var/www/example.com/myproject/myproject/ Here is my apache config. Protocols h2 http/1.1 WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess example python-home=/var/www/example.com/venv python-path=/var/www/example.com/myproject <VirtualHost *:80> ServerAdmin riden@example.com ServerAlias www.example.com ServerName example.com DocumentRoot /var/www/example.com/myproject/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/example.com/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> Alias /favicon.ico /var/www/example.com/myproject/static/images/favicon/favicon.ico Alias /static /var/www/example.com/myproject/static <Directory /var/www/example.com/myproject/static> Require all granted </Directory> WSGIProcessGroup example WSGIScriptAlias / /var/www/example.com/myproject/myproject/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} =example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> Here is the error. [28] [mpm_prefork:notice] [pid 959] AH00163: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1g mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [53] [core:notice] [pid 959] AH00094: Command line: '/usr/sbin/apache2' [03] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] mod_wsgi (pid=969): Target WSGI script '/var/www/example.com/myproject/myproject/wsgi.py' cannot be loaded as Python module. [08] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] mod_wsgi (pid=969): Exception occurred processing WSGI script '/var/www/example.com/myproject/myproject/wsgi.py'. [32] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] Traceback (most recent call last): [79] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] File "/var/www/example.com/myproject/myproject/wsgi.py", line 12, in <module> [87] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] from django.core.wsgi import get_wsgi_application [04] [wsgi:error] [pid 969] [remote 1.2.3.4:58356] ModuleNotFoundError: No module named 'django' Checklist of things … -
Django automatically generates settings with pathlib instead of os.path
I am quite new to django but after some time, my django projects started getting generated with pathlib. This is a problem for me, because there are not many tutorials and questions about it. It is causing a few errors. Right now this one has been emerging. expected str, bytes or os.PathLike object, not LazySettings with problem in a traceback a = os.fspath(a) in anaconda3/envs/venv/lib/python3.8/posixpath.py, line 76, in join Question is, how do I get rid of this without damaging my existing project? Alternativaly, could you link me to an article/docs that explain this in detail? Thank you -
How to read video from django db with opencv
I have a Django restful api endpoint that stores a client uploaded video to the database on a folder called video. I want to read this video using opencv, convert to frame and save the frame on the clients pc each time a client uploads a video. I really don't know how to read this video from database. Is it also right to read the video file from view.py Your answer is highly appreciated. Model.py file class MyVideo(models.Model): name= models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") # mod = models.FilePathField def __str__(self): return self.name + ": " + str(self.videofile) view.py file class MyVideoView(viewsets.ModelViewSet): queryset = MyVideo.objects.all() serializer_class = MyVideoSerializer Opencv script # Opens the Video file cap= cv2.VideoCapture(file_name) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(('new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() -
Continuously develop and deploy a Django app with Visual Studio Code and Docker
I am developing a Django app for my own purposes. After a couple of weeks I was able to use it for my daily work. I simply ran it via Visual Studio Code which was handy because whenever an error occurred or I needed new features I just could change or enhance the code and check it out immediately. In the long run I want to let others use this app too, so I have to deploy it somehow. I do not want to run a server on my own, so I tested Heroku a little bit and Google Cloud Run. Encouraged by an acquaintance I took a closer look at Docker and it took me a while to get an idea of the basics. Mainly with the help of the book 'Django for Professionals' I was able to get my app running within a Docker container locally. Before I try to build my Docker image somewhere else I wanted to make sure that I still can debug my code. With the official 'Python in a container' tutorial I am able to set breakpoints and so on. (It took me a while to realize that due to this bug it …