Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Heroku - ModuleNotFoundError: No module named 'django_social_share'
My django site works fine locally but on Heroku has "Application Error" Page . but it exists in settings.py file Thanks in advance so i typed heroku logs --tail My heroku log : -
Deploy Django with VueJS on DigitalOcean Apps
I have a project that consists of Django (DRF) backend and VueJS app frontend. During development, I have two servers - Django deployment server on port 8000 and VueJS on port 8080. I would like to make this work also on DigitalOcean Apps platform so the only thing I need to deploy it is to git push project to master. Structure: django_project/django_project/settings.py ... django_project/django_app1 django_project/django_app2 django_project/vue_app If I deploy this, only Django project is being server. I need to bound VueJS project to / URL and Django to /api url. I have some ideas but I'm not sure how to make them work. For example, I'll setup outputDir to /var/www but I can't access the nginx configuration so I don't know how to do that. Do you have any ideas? -
django-admin to open a new project
I am using this command: django-admin stratproject Hello to initiate a new project, but I am getting the following error django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin stratproject Hello + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException just started with django and this is so frustrating -
Update CSS on Django production Server (Nginx, Gunicorn, Whitenoise)
I have a Django production setup on an VPS with Nginx and Gunicorn and I serve static files through whitenoise. I have updated the CSS and pulled the changes on the server but they don't show up. After I pulled the changes, I ran the following commands: python3 manage.py collectstatic <- to collect the new files sudo systemctl reload nginx <- restart nginx kill -HUP /Gunicorn master PID/ <- restart gunicorn I read in the Whitenoise documentation that it should serve new files immediately without restarting. So I think everything should be reset and the new files should be served but it doesn't work. Am I missing a step? For completeness sake here is the nginx config: server { listen 80; server_name XXX.XXX.XXX.XXX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/project_path/project_name; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project_path/project.sock; } } Thanks in advance -
Django: NoReverseMatch at /home/blog/ Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name
I have been getting this error, and I didn't know what I did wrong in the code, I checked everything and I still cant figure it out. I also try getting the specific post object in the database by id, i mean doing something like "post = Post.objects.get(id=id)" in post function in my views.py, but i got the same error. Any help will be appreciated. this is my models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField() def __str__(self): return self.user.username class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200) overview = models.CharField(max_length=200) categories = models.ManyToManyField(Category) author = models.ForeignKey(Author, on_delete=models.CASCADE) comment_count = models.IntegerField(default=0) views_count = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField() featured = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'id': self.id}) my urls from django.urls import path from blog.views import home, blog, post app_name = 'blog' urlpatterns = [ path('', home, name='home-page'), path('blog/', blog, name='blogs'), path('post/<id>/', post, name='post-detail'), ] my blog.html template <div class="container"> <div class="row"> {% for post in queryset %} <div class="post col-xl-6"> <div class="post-thumbnail"> <a href="post.html"><img src="{{post.thumbnail.url}}" alt="..." class="img-fluid"></a> </div> <div class="post-details"> … -
How to add a second annotation to an already annotated queryset with django models
I want to create a queryset with following columns movie.id | movie.title | movie.description | movie.maximum_rating | movie.maximum_rating_user Below is are my models and the code I have tried. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name="ratings") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ratings") score = models.DecimalField(decimal_places=2, max_digits=9) class Movie(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=4096) When i run below code the following is printed in console: (basically this shows all data in the experimental database) views.py def index(request, movie_id): movies = Movie.objects.all().annotate( maximum_rating=Max('ratings__score'), maximum_rating_user=F('ratings__user') ) for movie in movies: print(movie.id, movie.title, movie.description, movie.maximum_rating, movie.maximum_rating_user) return HttpResponse("") id title description rating user 1 Jumping Cats Running wild 2 1 1 Jumping Cats Running wild 1 2 1 Jumping Cats Running wild 5 3 1 Jumping Cats Running wild 4 4 2 Terminator I'll be back! 8 1 2 Terminator I'll be back! 6 2 2 Terminator I'll be back! 4 3 2 Terminator I'll be back! 10 4 3 Dumbo Walt Disney 6 1 3 Dumbo Walt Disney 8 2 3 Dumbo Walt Disney 9 3 3 Dumbo Walt Disney 2 4 4 Thin Red Line Wartimes 9 1 4 Thin … -
Django SerializerMethodField vs Complex SQL
I'm wondering about what people think about the tradeoffs of efficiency and readability between using Django's SerializerMethodField and writing potentially convoluted SQL. I'm think SQL would generally be quicker, but the complexity of code may not be worth it. I lean towards using the SerializerMethodField for better readability/maintainability, but am curious what others think. This isn't a great example and just serves as an introduction to what I am talking about. These SQL queries could get much more convoluted. I know this code probably isn't actually written perfectly. # Comment # is_admin: Boolean # public_email: String # email: Optional String default_email = 'foo@bar.com' queryset = Comment.objects class CommentSerializer(serializers.Serializer): is_admin = serializers.BooleanField() email = serializers.SerializerMethodField() @staticmethod def get_email(comment): if comment.is_admin: return comment.public_email return comment.email or default_email queryset = Comment.objects.annotate( email=Case( When(is_admin=True, then='public_email'), default=Coalesce('email', Value(default_email)), output_field=CharField(), ) ) class CommentSerializer(serializers.Serializer): is_admin = serializers.BooleanField() email = serializers.CharField() -
How to change admin color in Django based on whether person is an Superuser or not?
I would like to implement a function in Django admin, that if a person logged is superuser then the color in admin is different. How can I approach it? I don't want 'normal' users to have access to admin, but I want to have 2 levels of access - superuser that can change everything (and add more personnel etc) and normal staff level, who can't add other employees and is limited in what he can do. How can I approach the issue? Can I simply add flag somewhere which states that if logged user is superuser then use different/additional css or something? -
How can I get reposted post info? Django
I'm making a small social network on Django. I want to make repost feature. I have Post model in models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField('Post text') image = models.ImageField('Image', upload_to='post_pics', blank=True) date = models.DateTimeField('Date') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked_by_user') def __str__(self): return self.text Then I created the Repost model, that takes Post model: class Repost(Post): post = models.ForeignKey(Post, related_name='reposted_post', on_delete=models.CASCADE) Then I tried to create a repost with admin panel. New was post created, but how can I get info (user, text, image, date and likes) of post that I reposted and paste it in my repost? Part of my html: {% for p in post %} <p>{{ p.user.username }}</p> <p>{{ p.text }}</p> <p>{{ p.date }}</p> {% endfor %} -
What are possible security flaws on using user login with email indirectly in Django using default user model?
I wanted to implement login in Django (version 3.1.7) using email instead of username. So I checked for solutions and stumbled upon this question But as a beginner, I don't want play around default user model class by defining custom user model. So a quick fix was to fetch username from user email and then authenticate. My implementation: from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages def login(request): if request.method == 'POST': email=request.POST['email'] userinfo= User.objects.filter(email=email)[:1] if userinfo.exists(): username=userinfo.first() else: messages.info(request,'Email doesn\'t exist..') return redirect('login') password=request.POST['password'] user= auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/') else: messages.info(request,'Invalid credentials') return redirect('login') else: return render(request,'login.html') I made sure that email is unique while registration: def register(request): if request.method == 'POST': username=request.POST['username'] email=request.POST['email'] password=request.POST['password'] password1=request.POST['password1'] if password1 == password: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') else: user= User.objects.create_user(username=username,password=password,email=email) user.save() return redirect('login') else: messages.info(request,'passwords not matching') return redirect('register') else: return render(request,'register.html') This implementation works correctly. Also, I use csrf_token in both html forms. Now I want to know if there are any security flaws by using these implementation for login. What are the possible ways to make it more stricter. What things will not … -
The profile_pic and profile_bio do not get updated in Update View in Django
So, I am trying to create a Profile Update Form. My problem is that my form updates every field except profile_pic and profile_bio. However, I have updated them successfully directly through the PostgreSQL admin. Most of the answers I found for this problem were to include enctype="multipart/form-data" in the template tag, but I have it already. How do you think I can resolve this issue? This is the Profile Model class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') profile_bio = models.TextField(null=True, blank=True) def __str__(self): return str(self.user) This is the form for Profile Update class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'username', 'email', 'profile_bio', 'profile_pic'] first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) profile_bio = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) password = None This is the View that is supposed to update the profile, it updates all the field successfully except profile_bio and profile_pic class UserEditView(UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user The registration/edit_profile.html Template {% extends 'base.html' %} {% block title %} Edit Profile {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="card" style="width: … -
django postgres DateTimeField auto_now It adds 10 minutes to the current time automatically
model updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) settings TIME_ZONE = "Asia/Seoul" LANGUAGE_CODE = "en-us" USE_I18N = False USE_L10N = True USE_TZ = True if now => 2021-03-24 14:16:22.248579+00 but saved updated_at => 2021-03-24 14:26:22.248579+00 created_at => 2021-03-24 14:26:22.248579+00 I can't find the cause. Where can I check it? -
Django: API with accumulated data
I am new to python and want to implement an API with accumulated data. I've seen a lot of information about the possibility to browse the database with the django rest framework but I cannot find the right solution to view data which is analyzed or summarized. For example, I have data about some newspaperarticles: articles: [ { name: "test 1", views: 10000 }, { name: "test 2", views: 20000 }, { name: "test 3", views: 30000 } ] I want to show analyzed data like summary: { name: "articles", sum_views: 60000, article_count: 3 } What would be the best practice if I want to use django and the django rest framework? -
How can I create children of a non-existent parent page in the Wagtail CMS for Django?
I want to create children of a page (such as "/questions/example"), without having to create the root page "/questions". Is there a quick way of implementing something like this? -
Get messages from django query
def search(request): query=request.GET.get('q') if query: queryset = Q(adm__exact=query) result = Mymodel.objects.filter(queryset).distinct() return render(request, 'h.html',{'result':result} I'd like to have message get back to me incase what is in the query is not available in the database. How/where do I insert the code?? -
Atomic transaction Django not getting rolled back when second Query fails on mongoDb
I am trying to implement Atomic transaction on mongoDb using django(python) but when the second query fails it does not roll back the insertion happend in previous statement following is my API code from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.core.exceptions import ValidationError from django.views.decorators.csrf import csrf_exempt from django.db import IntegrityError, DatabaseError, transaction from rest_framework.decorators import api_view from rest_framework import status from .models import Invoice, Item # Create your views here. @api_view(["POST"]) @csrf_exempt def add(request): try: with transaction.atomic(): invoice = Invoice( Number = request.data['number'], Date = date.today() ) invoice.save() for itemReq in request.data['items']: item = Item( Invocie_Id = invoice, Name = itemReq['name'], amout = itemReq['amount'], price = itemReq['price'], ) item.save() except DatabaseError: return JsonResponse({'error': 'Could not save element, possibly duplicate'}, safe=False, status=status.HTTP_403_FORBIDDEN) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return JsonResponse({'success': 'Saved Sucessfully'}, safe=False, status=status.HTTP_200_OK) -
How to convert money from a currencies to another in Python
I am using Django to build a money transfer application and I would like a way to build a template tag in order to automatically exchange money from one currency to another using the OPENEXCHANGE URL. So, I referred to this link: https://django-money-rates.readthedocs.io/en/latest/readme.html but it does not work and facing the issue in the attachment. How can I do it, please? Or is there another way to solve the problem? For more information, I am using Django-3.1.7 and Python-3.8 Thanks -
Django/Rest Framework Nest Serialization
I'm having a bit of trouble with implementing the serialization for my server. It is a host to demonstrate homomorphic encryption. Storage on the server consists of integers (really two integer tuples (X,q)), which are tied to a single set, sets are tied to sessions, sessions are tied to users... sets & sessions can both be posted. Posting a set includes the user_id, session_id and multiple integers in the request. Posting a set includes the user_id, session_id, then multiple sets in the request. Also, for a set the server generates an ID and sets that value for all integers in the set, and includes it in the response. Ideally, the user_id and session_id are going to be put in once in either type of request. So for a session post, each set does not have the user_id, session_id, but for a set post the set does have those values. For get requests, similar idea... one instance of user_id, session_id, and this time set_id because it was created in the post. A user can request a set or session in the GET request as well. I understand the basic idea of serialization, but I have trouble when nesting comes into play. … -
Simultaneous authorization of the administrator in the admin panel and on the site
When logging in through the admin panel, the administrator simultaneously logs in to the site and in the admin panel, how can I fix this, please tell me? The problem is that when I go on behalf of the admin in the admin panel, authorization occurs on the site that I am developing, and I do not need it. I would like the authorization to be performed separately on the site(for users) and on the admin panel(for admin).(DJANGO).Please help me with this question ??? -
Django - Trying to keep track of user's cart
I have a cart where I have two fields that I use to connect to a user. One is User, I use that if user is logged in. Other is session, this is used to keep track of logged out users. It uses session_key. Now the problem I am facing is that when a user logs in the cart disconnects because the session_key has changed. I know that I can use cookie to identify the browser or client. But I am not able to find an example of Django's set_cookies being used with JsonResponse(AJAX call). It is only for HttpResponse. I think I could use either of these two ways, if possible. Set cookie through AJAX Or Set cookie when user visits website. I want this with ability that no matter which page the user visits at fist the cookie should be set on that visit. Does anyone have a resource or example to achieve this? Thank you -
Toggle Structure in Django-cms toolbar is Disabled
Problem: CMS-toolbar is hiding Navigation bar menus & it's now disabled(not moving up). Django version = 3.0.8 Django cms = 3.8.0 {% cms_toolbar %}<!-- from cms toobar --> <body> <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="index.html">Start Bootstrap</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> {% show_menu 0 100 100 100 %} <!-- for cms menu --> <li class="nav-item"> <a class="#" href="about.html">About</a> </li> <li class="nav-item"> <a class="#" href="services.html">Services</a> </li> </ul> </div> </div> </nav> How can I convert that icon to arrow one which can be moved up and down easily? This is what I have This is what I need -
ERR_CONNECTION_REFUSED Serving Django Project on Ubuntu
I am serving Django Project on Digitalocean Ubuntu Droplet. When I am configure https connection everything collapse and I can nat browse my ip 188.166.117.124 On every browser I get ERR_CONNECTION_REFUSED error $ grep server_name /etc/nginx/sites-enabled/* -RiI /etc/nginx/sites-enabled/default: server_name _; /etc/nginx/sites-enabled/default:# server_name example.com; /etc/nginx/sites-enabled/personal_web_site: server_name 188.166.117.124; $ netstat -tlpdn Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* listen - tcp 0 0 127.0.0.53:53 0.0.0.0:* listen - tcp 0 0 0.0.0.0:22 0.0.0.0:* listen - tcp 0 0 0.0.0.0:5432 0.0.0.0:* listen - tcp6 0 0 :::80 :::* listen - tcp6 0 0 :::22 :::* listen - tcp6 0 0 :::5432 :::* listen - $ netstat -tulpn | grep :80 tcp 0 0 0.0.0.0:80 0.0.0.0:* listen - tcp6 0 0 :::80 :::* listen - strong text $ sudo ufw status to action from ----- ----- -------- Nginx Full ALLOW Anywhere Nginx HTTP ALLOW Anywhere Nginx HTTPS ALLOW Anywhere 8000 ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6) Nginx HTTPS (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) I tried with $ sudo ufw disabled nothing changed What is the problem of my server -
How do you change django widget select attrs?
I'm trying to add new attributes to this ChoiceField so with help of ddslick() it should display images instead of text, but I'm unable to do so, I've tried declaring it explicitly before and after the meta class or simply as an normal widget, but without success, neither the generated <select> or <option> tags changed any of it's attributes, I was wondering if there's anything else that I can try. class MemoryForm(ModelForm): cover_image=(ChoiceField(widget=Select(attrs={'class': 'asdf'}))) class Meta: model = Memory fields = [ "title", "description", "date", "location", "accurate_date", "accurate_month", "accurate_day", "cover_image", ] labels = {"title": "", "description": "", "date": "", "location": ""} widgets = { "title": TextInput( attrs={"placeholder": _("Enter a title"), "class": "only-bottom"} ), "description": TextInput( attrs={ "placeholder": _("Add a description (optional)"), "class": "only-bottom", } ), "location": TextInput( attrs={"placeholder": _("Enter a location"), "class": "only-bottom"} ), "date": HiddenInput(), "accurate_date": HiddenInput(), "accurate_month": HiddenInput(), "accurate_day": HiddenInput(), "cover_image" : Select( attrs={"data-imagesrc": "/static/media/images/cherryimage/e2e4a952-e949-4b97-8597-eebd9bd445d5.jpg"} ), } -
Which is best method to deploy django site on production server?
In how many different ways I can deploy django web app? Can you explain any one method in detail? -
Django forms request
My Django application has two models. Which are Vehicle and Offer. So users can submit offers for vehicles. When submitting an offer I want to capture user_id and vehicle_id with the form. views.py def your_view(request): if request.method == 'POST': offer_form = Offerform(request.POST) if offer_form.is_valid(): instance = offer_form.save(commit=False) instance.user = request.user instance.vehicle = ? instance.save() messages.success(request, 'Offer submitted successfully') return redirect('vehicles') models.py class Offer(models.Model): name = models.CharField(max_length=90, blank=False) email = models.EmailField(max_length=90, blank=False) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) I can get the user with reqeust.user but how to get the vehicle_id that the user submits their offers to?