Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using flags as options for languages in django
I'm trying to add flags to my dropdown for i18n, so far I've tried adding an img tag and using as background image but none of them seem to work <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> {% get_current_language as LANGUAGE_CODE %} <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <select name="language" id="" class="icon-menu"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{language.code}}" {% if language.code == LANGUAGE_CODE %} selected {% endif %} {% if language.code == "en-gb" %} style="background-image:url(/static/img/en-gb.png);" alt="english">english {% elif language.code == "pt-br" %} >portugues<img src="/static/img/pt-br.png" alt=""> {% else %} {{ language.name_local }} {% endif %} </option> {% endfor %} </select> <input type="submit" value="{% trans 'Go' %}"> </form> </li> -
Error while opening Django admin: "Error at /admin/ Incorrect padding"
I was making a web app using Django. I was using Django 3.0.7 for the sake. Then I upgraded to Django 3.1.1. When I reinstalled Django 3.0.7 I am unable to open Django Admin. While I try to get into my Django admin an error shows up saying: Error at /admin/ Incorrect padding Exception Location: ...\python\python38\lib\base64.py in b64decode, line 87 -
How to write a TestCase for user login
I should test login functionality for this Django project, but it seems it can't login properly. This is the login method on views.py def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) request.session['username'] = username # Session test if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}.") # Redirect da login alla dashboard dell'utente return redirect("dashboard") else: messages.error("Invalis User") #return render(request=request, template_name="dashboard.html", context={}) else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form": form}) After login, it redirects to the dashboard which shows boards linked to the user, with this code def dashboard(request): usern = request.session.get('username') userlog = User.objects.get(username=usern) boards = BoardMember.objects.all().filter(user=userlog) return render(request, "dashboard.html", {'board': boards, 'user': userlog}) Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is: self.client.post("/", {"username": self.user2.username, "password": self.user2.password}) response = self.client.get(reverse("dashboard")) self.assertEqual(response.content, self.user2.username) -
How to create a template creator with moveable objects?
Good day, I am currently working on an automatic system that generates invoices with data that it receives from an API. I am currently doing this with Django (Python) to create some variation. Well, I want to create a system with which you can easily create templates for these invoices. You have seen these kinds of systems before. You can move blocks with items such as a logo or text wherever you want. Well I know that these templates are further stored as HTML. Only nowhere I can find clear information about how I can easily assemble such a system or how such a system works. Below I show a GIF of the system what I want. If anyone has any information on this I will be very happy if you can share that with me :) -
Django model order the results according to the entry date
How do order the DB query result according to the entry date? I want to order the output from the latest entry added, using MySQL DB creation timestamp. class Author(models.Model): name = models.CharField(max_length=50) age = models.PositiveIntegerField(null=True, blank=True) alias = models.CharField(max_length=50, null=True, blank=True) goes_by = models.CharField(max_length=50, null=True, blank=True) flag = models.PositiveIntegerField() def __str__(self): return self.name objects = models.Manager() def getAuthor(request): if request.method == "POST": result = list(Author.objects.filter(flag=0).values_list("name").order_by('-date')) else: pass return JsonResponse(result, safe=False) -
Can't access django development server on a remote vps
I've just got a VPS with Ubuntu 18.04 on it. Now I want to move my Django app I've been developing on a local PC to the VPS. I moved it and it starts okay - it says the server is running on 0.0.0.0:8000. So the server is running fine, but I can't connect to it from a web browser on my local PC. I have port 8000 enabled with netstat and I have added the IP to ALLOWED_HOSTS. -
Django Subquery/Window function
I'm trying to create a subquery that would produce the same result as a window function. I have following models: class BookQuerySet(models.QuerySet): def with_reviews(self): return self.annotate(score=models.Avg('review__score')) def with_reviews_per_category(self): categories = Category.objects.filter( book=models.OuterRef('pk') ).annotate( cs=models.Avg('book__review__score') ) qs = self.annotate( category_score=models.Subquery(categories.values('cs')[:1]) ) return qs def with_reviews_per_category_window(self): return self.annotate( category_score=models.Window( expression=models.Avg('review__score'), partition_by=[models.F('category_id')] ) ).distinct() class Category(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField('Author', related_name='books') category = models.ForeignKey('Category', on_delete=models.CASCADE) objects = BookQuerySet.as_manager() class Author(models.Model): # Irrelevant class Review(models.Model): summary = models.CharField(max_length=200) book = models.ForeignKey('Book', on_delete=models.CASCADE) score = models.PositiveSmallIntegerField( default=1, validators=[ MinValueValidator(1), MaxValueValidator(5) ], ) The reviews have following values: [{'score': 5, 'book': 5, 'book__category': 3}, {'score': 2, 'book': 4, 'book__category': 2}, {'score': 4, 'book': 1, 'book__category': 1}, {'score': 4, 'book': 2, 'book__category': 1}, {'score': 4, 'book': 3, 'book__category': 1}, {'score': 5, 'book': 1, 'book__category': 1}, {'score': 5, 'book': 2, 'book__category': 1}, {'score': 5, 'book': 3, 'book__category': 1}, {'score': 5, 'book': 3, 'book__category': 1}] And the window function produces correct results: In [11]: list(Book.objects.with_reviews_per_category_window().values('id', 'category', 'category_score')) Out[11]: [{'id': 4, 'category': 2, 'category_score': 2.0}, {'id': 3, 'category': 1, 'category_score': 4.571428571428571}, {'id': 2, 'category': 1, 'category_score': 4.571428571428571}, {'id': 5, 'category': 3, 'category_score': 5.0}, {'id': 1, 'category': 1, 'category_score': 4.571428571428571}] I can confirm that … -
Error submitting a modified field of a form
I am having a problem with my form, and it is that when trying to persist my data in the database this is not done correctly, because in my form the developer field is not being validated in the correct way because it does not show an error to the client, but the browser console shows me the following error, an invalid form control with name = 'developer' cannot be focused. This is my form: class ProjectForm(ModelForm): developer = forms.ModelMultipleChoiceField( queryset=User.objects.filter(groups__name='desarrolladores'), label='Desarrolladores', ) class Meta: model = Project fields = ( 'developer', 'name', 'status' ) labels = { 'name': 'Nombre de Proyecto', 'status': 'Estado', } def clean_developer(self): developer = self.cleaned_data.get('developer') if developer is None: raise forms.ValidationError('El campo es obligatorio') return developer -
Django: Unable to access attribute of foreign key
I have a Comment model with User as a foreign key, and simply want to render the username of the comment. The comment shows up on the page but the username doesn't, I'm not sure why my code doesn't work.. Sorry if this is a really basic question. class Comment(models.Model): comment = models.TextField(default="") user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default=1) def comment(request, listing_id): listin = Listing.objects.get(id=listing_id) if request.method == "POST": comment = CommentForm(request.POST) if comment.is_valid(): comment = comment.save(commit=False) comment.user = request.user comment.listing = listin comment.save() return redirect("listing", listing_id=listing_id) HTML code: {% for comment in comments %} <p>{{ comment.user.username }}: {{ comment.comment }}</p> {% endfor %} -
Proper way to use a counter variable in HTML with Chart.js on Django
I am relatively new to Django and Chart.js. To create charts using Chart.js, I need the charts to have different names. For this, I have thought about using a counter variable. <script>**var count = 0;**</script> <ul> {% for object in objects %} <li> ... <script> {% block jquery %} console.log(count); var endpoint = '/api/chart/data/'; fetch(endpoint, { method: "GET", }).then(response => response.json()) .then(data => { console.log('Success:', data); **count = count + 1;** ... eval('var chart_id = "myChart{{ count }}"'); eval('var ctx{{ count }} = document.getElementById(chart_id)'); eval('var myChart = new Chart(ctx{{ count }}, graph_data)'); console.log("myChart{{ count }}") }) .catch((error) => { console.log("Error:") console.log(error); }); {% endblock %} </script> <canvas id= "myChart{{ count }}" width="400" height="400"></canvas> ... </li> {% endfor %} </ul> However, when I look in the source code on my dev server, I can see that the id for all of the canvas tags is simply "myChart". Why is this? What am I doing wrong? -
Filter not null dates with Django and GraphQL
We have a tour node with feauted_date (DateTime) field, that can also be nullable. class TourFilter(OrderByMixin): class Meta: model = TourModel fields = { 'featured_date': ['exact', 'lt', 'gt'], } class TourNode(DjangoObjectType): class Meta: model = TourModel filter_fields = TourFilter.Meta.fields interfaces = (relay.Node, ) Currently we use featured_date for sorting with OrderMixin, but is there any way to filter them by not null? -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file
When I try to execute py manage.py runserver I had the following message: Message of Import Error I found a lot of possible solutions on the internet. Ayway, I suggest firt, try the following. Go to the wsgi.py file, inside MySite. wsgi.py file Verify that Django is imported. I use Pycharm, the IDE allowed me to import directly from there. After this I was able to run manage.py -
Why does my Bootstrap and/or CSS look different on localhost:8000 than on 127001:8000 for my Django website? And how can I fix this issue?
For some reason my website looks different for both ports. Here is what I mean -
Django Model Manager
I have a Django Model where users can create objects and keep them private for a certain period of time. class MyModel(models.Model): creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) private_until = models.DateField(null=True, default=None, blank=True) objects = MyModelManager() In my ListView, I want for visitors only the "non-private" objects to appear and for authenticated users the "non-private" objects plus their own private objects. So my Manager looks like this: class MyModelManager(models.Manager): def include_his_private(self, user): if user.is_authenticated: include_his_private = super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) include_his_private |= super().get_queryset().filter(Q(creator=user)) return include_his_private else: return super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) def get_queryset(self): return super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) For my ListView this works great. But when I click on an object to get its DetailView, I get a 404 error right on "URL-Level". In my URLs I have: path('<slug:slug>', MyModelDetailView.as_view(), name='mymodel_detail'), ... and somehow, Django checks already in advance the whole slug against the per Manager allowed slugs, before I have the chance to pass the user in. What is the way to solve my problem? Any help is appreciated. Thanks in advance! -
Google Maps API close Info windows automatically
I'm working with the google maps API, I'm completely new to javascript and have no idea what I'm doing. Could you please tell me how to edit this code so that the infowindows close by themselves when I click on another marker? Right now when I click on a marker and the infowindow pops up it stays open when I click on a second marker. I've found similar questions on stack overflow but I'm completely lost in javascript and it's too complicated for me. Thanks! {% for party in parties %} var marker = new google.maps.Marker({ position:{lat:{{ party.latitude }},lng:{{ party.longitude }}}, map:map, }); var infoWindow = new google.maps.InfoWindow({ content:"{{ party.name }}" }); marker.infoWindow = infoWindow; marker.addListener('click', function(){ return this.infoWindow.open(map, this); }); {% endfor %} -
why does this error appear even if the folder is correct?
I did everything according to the tutorial, why this error? -
Django - Save a Excel file to a model's FileFild
I want to save a file in my excel_file field but i have this error : 'utf-8' codec can't decode byte 0x9d in position 15: invalid start byte class Product(models.Model): excel_file = models.FileField(upload_to='upload', blank=True) def save(self, *args, **kwargs): try : myFile = open('excel_file.xlsx', 'r') name = "new_test.xlsx" self.excel_file.save(name, File(myFile)) super().save(*args, **kwargs) except Exception as e: print(e) -
folium.Marker does not does decode
I have a folium map called imap. I have created a string object called test_mark which is a string 'Hà Nội' test_mark = 'Hà Nội' folium.Marker(location=(43.30,-8.30),popup= test_mark, icon= folium.Icon()).add_to(imap) When I check the marker on the map, what I get is 'hà ná»i'. I guess it might be some kind of encoding problem, but I can not figure out how to solve it. Thanks in advance -
Django: AttributeError at /tickets/post/1/like/ 'str' object has no attribute 'fields'
I have a problem when I am trying to 'upvote' a ticket in my app. There is a button on my app that adds one to the upvotes field, but as soon as I press on the button I get the error. I have refreshed all of my migrations as I had a problem with an old field that was being picked up but I may need to run something else? Here is the traceback: Environment: Request Method: GET Request URL: http://3231d88fef004534aa79ab40a77c1898.vfs.cloud9.us-east-2.amazonaws.com/tickets/post/1/like/ Django Version: 1.11 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tickets', 'checkout'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Template error: In template /home/ubuntu/environment/issuetracker/templates/base.html, error at line 0 'str' object has no attribute 'fields' 1 : {% load staticfiles %} 2 : 3 : <html> 4 : 5 : <head> 6 : <meta charset="UTF-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 : <title>IssueTracker{% block page_title %}{% endblock %}</title> 10 : <link rel="icon" href="media/img/bug.jpg"> Traceback: File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/environment/issuetracker/tickets/views.py" in … -
filter home page(blog posts) by category on button press
I currently have a page which displays all the blog posts, which updates when a new post has been added. Each blog has a department and a category I am looking to have 2 buttons ontop of the page which have 'department' and 'category', when the user loads the home page he/she will see all blog posts but when the user wants to see the category they simple need to press the CATEGORY button which will dynamically update the blog posts to show all the blog posts that match the category. I have say 5 categories: programming, onboarding, coding, help. I have spent hours and creating new issues trying to filter the current blog posts to show a button which filters the posts by 'programming'. end goal: 2 buttons above posts department = filter the current posts by the department that the user is a part of (department is assigned to the user when they update their profile) category = filter the posts by a choice of categories (programming, coding etc) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Category (models.Model): named = models.CharField(max_length=100) def __str__(self): return self.named def get_absolute_url(self): … -
Folder for static images can't be accessed/found
I tried following this or this or this but nothing works for me - I have a directory called media which has uploaded files in it - but I cannot access it with http://127.0.0.1:8000/media/ - Page not found (404). My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'PROJECT/static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = "/media/" and my urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView, from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('home/', RedirectView.as_view(url='/')), path('admin/', admin.site.urls), path('', include('appname.urls')), path('', include('django.contrib.auth.urls')), path(r'^login', auth_views.LoginView.as_view(template_name='registration/login.html')), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from django.conf import settings from django.conf.urls.static import static if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Bonus question because I could not try it until now: How would I access an image with filename.jpg in /media/ in a template? -
React favicon not displayed after run build
I changed the favicon.ico to image.svg in my react app. When running development server it is showing the icon fine, but when I run build, the favicon is not there. My stack is Django DRF, React and Nginx. I tried to bypass this issue by setting favicon in the nginx config and changing permissions on the image to 755. But If I do that I receive 404 on the file. nginx config file: location = /favicon.ico { alias /home/user/pyapps/project/image.svg; } Do I have to change owner of the file or something similar to that? -
How do I cache form data in Django?
I'm creating a single page application in Django. It mainly consists of multiple, small forms that are filled in and validated independent from each other. Every form looks similar to this: With a final button press at the end though, the input of all those forms should be processed together. How can I save/cache all data of the submitted forms to process them with a final form submit at the end? I tried creating only one big form, but then I can't validate each field one after the other, when the user clicks the 'Next' button. -
Django not getting id from the url parameter
i have these serializer on Django class CarManagerSerializer(serializers.ModelSerializer): class Meta: model = Manager fields = '__all__' and this view class class CarManagerViewSet(APIView): allowed_methods = ('GET',) def get(self, request, manager_id = None): if manager_id is None: managers = Manager.objects.all().order_by('-name') serializer = CarManagerSerializer(managers , many=True) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) else: managers = Manager.objects.get(id = manager_id).select_related('cars') serializer = CarManagerSerializer(managers , many=True) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) im trying to get the manager by its manager id http://127.0.0.1:8000/carmanagers/3 but the manager_id wont get passed to the view, i keep getting 'None' where did i miss ? below is the url urlpatterns = [ url( r'carmanagers/(?P<manager_id>[0-9]+)/$', CarManagerViewSet.as_view(), name='car-managers' ), url( r'carmanagers', CarManagerViewSet.as_view(), name='car-managers' ), ] -
Dynamic form in Django
I am trying to make a dynamic form in Django that asks according to the user's answers. For example, in this google form when you select option 1, it sends you to the section of option 1 with their respective questions. Google Form Example