Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to build a full stack app with load balancer react native react and django (system design)
I am building an app that has django (DRF) as backend framework, React for the front end and React Native for mobile. I am using Docker and Nginx as Load balancer. Now my issue, I read about API gateway, since I intend to deploy my app on AWS, is the system design below the best approach for a small app then could potentially scale without slowing down the app from the start if i ever have a lot of users? Mobile (maybe port 3000) ----> NGINX (Load balancer) * API Gateway -----> backend (Django) Desktop (maybe port 9000) Do I really need the API Gateway, if YES should this be from NGINX or AWS I am looking forward to your advises to make an educated decision. Thank you -
Django create Postgres Enumerated Types fields from models
Does django support postgres enumerated types? I'm creating a model as follows, which generates the following migration. When I run the migration I would expect these types would be enforced at the db level, but it appears they are not. At a high level I'm trying to do run CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy') using the django modeling. Model class Person(models.Model): class Mood(models.TextChoices): Sad = 'sad' Ok = 'ok' Happy = 'happy' name = models.CharField() mood = models.CharField(choices=Mood.choices) Generated Migration class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('mood', models.CharField(choices=[('sad', 'Sad'), ('ok', 'Ok'), ('happy', 'Happy')], max_length=10)), ], ), ] -
Page not found (404) : When try to view a page in django
am new to django , so i wrote a simple program to go to Page2 from Page1 using a link in Page 1 and from Page2 to Page 1 using another link in Page 2, but it is showing Page Not Found . urls.py from django.contrib import admin from django.urls import path from website import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Index,name='IndexPage'), path('darkmode', views.darkmode,name='darkmode'), ] views.py def Index(request): return render(request,'Page1.html') def darkmode(request): return render(request,'Page2.html') Page1.html <div data-url="{% url 'darkmode' %}" class="dark-mode-switcher cursor-pointer shadow-md fixed bottom-0 right-0 box dark:bg-dark-2 border rounded-full w-40 h-12 flex items-center justify-center z-50 mb-10 mr-10"> <div class="mr-4 text-gray-700 dark:text-gray-300">Dark Mode</div> <div class="dark-mode-switcher__toggle border"></div> </div> Page2.html <div data-url="{% url 'Index' %}" class="dark-mode-switcher cursor-pointer shadow-md fixed bottom-0 right-0 box dark:bg-dark-2 border rounded-full w-40 h-12 flex items-center justify-center z-50 mb-10 mr-10"> <div class="mr-4 text-gray-700 dark:text-gray-300">Dark Mode</div> <div class="dark-mode-switcher__toggle dark-mode-switcher__toggle--active border"></div> </div> and am not able to figure put why this happened , Can anyone help me to figure this out -
CommandError: Unable to serialize database
I've checked every solution but can't get it. Actually, I'm new to Django. python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 4 > project_dump.json this is suggested by the instructor so I use it but whenever I enter this code I got this error you can see the error in this image Can anyone know what to do? -
Why is my form text input value POSTing as list?
My form field value is being received as a list and I can't figure out why. I need it to just be a string. form <form id="design-brief-3" name="design-brief-3" data-name="Design Brief 3" class="contact-form" method="POST" action="{% url 'project-design' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-field-container"> <label for="business_slogan" class="form-field-label">Business Slogan/Tagline/Mission Statement</label> <input type="text" class="form-field w-input" maxlength="256" name="business_slogan" data-name="business_slogan" placeholder="If we say 'Just Do It' you know what we mean." id="business_slogan" required=""/> </div> <div class="form-field-container"> <label for="essential_content" class="form-field-label">Essential Content</label> <textarea required="" maxlength="5000" id="essential_content" name="essential_content" data-name="essential_content" placeholder="Please include any content you have, it can be as long as you want." class="form-field message w-input"></textarea> </div> <div class="form-field-container"> <label for="logo" class="form-field-label">If you have a logo, upload it here.</label> <input type="file" class="form-field w-input" name="logo" data-name="logo" placeholder="Who is your ideal client?" id="Logo"/> </div> <div class="form-field-container"> <label for="#id_file" class="form-field-label">Additional files, such as page copies & additional images, you can upload multiple.</label> <input type="file" class="form-field w-input" name="#id_file" data-name="#id_file" id="#id_file" multiple="multiple"/> View: def projectdesign(request): if request.POST: print(request.POST) return render(request, 'users/projectdesign.html', context) Output: <QueryDict: {'csrfmiddlewaretoken': ['9p3NTDraxyssQZNdavUSrUaJaT1rQTIImn5rMnjm1F'], 'business_slogan': ['Just do it'], 'essential_content': ['sdsdsad'], 'logo': [''], '#id_file': ['']}> -
Django Customize read-only view in ModelAdmin
I have an ModelAdmin that, with a certain condition, makes has_change_permission equal to false. This makes all fields read-only when attempting to edit a model instance. But how am I able to customize these read-only fields? In particular, in this read-only view, I want: To be able to see a field that is excluded from the creation form (with exclude=[field]). To be able to make certain character fields hyperlinks. -
I want to preserve line breaks in CharField in Django REST framework
I'm using a CharField in the Django REST framework to store text, but how can I preserve line breaks in the API? In the case of Django templates, I think line breaks are possible with {{ value|linebreaksbr }}, but what about the Django REST framework? I would appreciate it if you could tell me how to do this. -
Django Rest-Framework-Simplejwt not working with modheader
I am working on some projects and trying to the list view of the book. I used Django Rest-Framework-Simplejwt to generate tokens and mod header for authentication. When I tried to request a token for a user such as the admin user, and enter it into the mod header, the request is still unauthorized. I tried to do it a couple of times, but still not working. Views.py from rest_framework import generics, permissions from rest_framework.permissions import IsAuthenticated from rest_framework.exceptions import ValidationError from django.contrib.auth.models import User from .models import Book from .serializers import ( BookSerializer, RegistrationSerializer ) class BookCreateView(generics.CreateAPIView): """Create a Book""" queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) class BookListView(generics.ListAPIView): """Show all books""" serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Book.objects.filter(user=user) class BookDetailView(generics.RetrieveAPIView): """Show detail of the book""" serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Book.objects.filter(user=user) class BookUpdateView(generics.RetrieveUpdateDestroyAPIView): """update detail of the book""" queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) def delete(self, request, *args, **kwargs): book = Book.objects.filter(user=self.request.user, pk=kwargs['pk']) if book.exists(): return self.destroy(request, *args, **kwargs) else: raise ValidationError('Book is not yours!') def perform_update(self, serializer, **kwargs): book = Book.objects.get(pk=self.kwargs['pk']) if self.request.user != book.user: … -
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