Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test function that checks and login temporary user - Django
Hello I'm trying to test function that takes temporary user id (if exists) from session and log the user in. def check_if_temp_user_exists_and_log_in(request): temp_user = request.session.get('temporary_user_id', None) if temp_user: u = User.objects.get(pk=temp_user) return login(request, u) Here is my uncomplete unittest. I don't know, what login() returns, so I am not able to finish the test code. import unittest from django.test import RequestFactory from django.contrib.sessions.middleware import SessionMiddleware class AnonymousOrRealTestCase(unittest.TestCase): def test_check_if_temp_user_exists_and_log_in(self): request = RequestFactory().get('/') # adding session middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.session['temporary_user_id'] = '1' result = check_if_temp_user_exists_and_log_in(request) self.assert ??? Can you help my please? Thanks a lot :) -
Filtering posts by three components logic issue
Code is working fine, but I have one little problem in filtering. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') if VideoPost.objects.filter(school=school_slug).filter(category=category_slug).filter(approve = 1).exists(): posts = VideoPost.objects.all().filter(approve = 1) if school_slug: posts = posts.filter(school=school_slug) if category_slug: posts = posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) return render(request, 'stories/no_post.html') 4th code line makes it to show the posts when it has both school and category are set only. How could I use that line to be working with one filter is applied? -
not working running python manage.py rusnerver
when runninge that command python manage.py rusnerver i get this error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? i try to pip install mysqlclient and got that Command "C:\Users\xavi6\PycharmProjects\LES\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xavi6\\App Data\\Local\\Temp\\pip-install-8q8y5ra6\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\ n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\xavi6\AppData\Local\Temp\pip-record-zvgp3gov\inst all-record.txt --single-version-externally-managed --compile --install-headers C:\Users\xavi6\PycharmProjects\LES\venv\include\site\py thon3.7\mysqlclient" failed with error code 1 in C:\Users\xavi6\AppData\Local\Temp\pip-install-8q8y5ra6\mysqlclient\ Im using pycharm and i think i try everything, pls help me. Thanks for help Andre. -
Formset invalid but 'Save' saves parent model and closes page
I've been using Django for a while - but I'm new to formsets. I have a formset 'payment' on a parent model 'invoice'. If the user enters a payment but forget the payment date (which is required) the page still saves the invoice and then closes. I can see from form_valid that formset.is_valid() is False. I can see the error raised if I print it in console: [{}, {}, {'paymentdate': ['This field is required.']}, {}]. I can even see the validation show up on the page right before is closes. How do I keep the page from closing when there is a validation error? -
How to check username exists or not in wiew.py without forms.py?
How to check username exists or not in wiew.py without forms.py, if USERNAME_FIELD = 'email' in Django settings? in models.py I create accounts model and USERNAME_FIELD = 'email' so now when I trying check username with User.objects.filter(username=username).exists() it returns email address, so how I can check if the username already exists in the database? -
How can I filter posts by user profiles with a certain field value? - Django
I am creating a blog application using Django and I would like to filter the blog posts using user profiles with a certain field value. For example, let's say that there is a field for professions in the profile model of the users, I would like to filter all the posts posted by doctors. Is this possible and if so, how would I achieve this? -
Django ModelChoiceField queryset filter from URL
I'm sure this is either a simple fix or I fundamentally misunderstand something. On this page, the current Store is determined via the url. I want to populate the ListingForm's choices with the Bonds that associated with that Store. Can someone help me achieve this properly? urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('stores/<slug:anchor>', views.ListingView.as_view(), name='listing'), ] forms.py from django import forms from store.models import Bond class ListingForm(forms.Form): face_value = forms.ModelChoiceField(queryset=...) # this part is a problem def __init__(self, store, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) self.fields['face_value'].queryset = Bond.objects.filter(store=store) view.py class ListingView(FormView): template_name = 'listing.html' form_class = ListingForm success_url = '/checkout/preview' # todo anchor = None store = None queryset = None def get_form_kwargs(self): kwargs = super(ListingView, self).get_form_kwargs() kwargs['store'] = self.store def get_context_data(self, **kwargs): self.anchor = self.kwargs.get('anchor') self.store = Store.objects.filter(anchor_id=self.anchor).first() self.queryset = Bond.objects.filter(store=self.store) context = super(FormView, self).get_context_data(**kwargs) context['store'] = self.store context['store_bonds'] = self.queryset return context def form_valid(self, form): # save selected bond to session # redirect to success_url face_value = form.cleaned_data['face_value'] bond = Bond.objects.filter(store=self.store, face_value=face_value).first() if bond: self.request.session['bond'] = bond return super().form_valid(form) -
Django connect to securecrt
I am trying to open and send commands from Django to securecrt, my idea is to have use Django to communicate with securecrt and initiate commands and get the output 1-Django to open securecrt and initate ssh session to a specific server 2-Then send some commands to that server 3-Get the output to Django Why I need that way, I don't have access to run commands directly to server from Django, instead I have to login to jumphost server Is there a way to perform such action? -
How Can I get "pk" or "id" in 'get_context_data' from CVB ListView. thanks for your response in advance
class UserList(ListView): model = User def get_context_data(self, **kwargs): user = self.request.user.pk profile = self.get_object() #how to get the list object form here is_subscribed = False if profile.subscribe.filter(id=user).exists(): is_liked = True context = super().get_context_data(**kwargs) context['is_liked'] = is_liked return context am using Django 3.0 and python 3.8 how do I get an object from a ListView and check if its liked or not -
Since backend framwork like Flask have HTML template which can generate html pages, can people just use backend framework to replace frontend?
Since backend framwork like Flask have HTML template which can generate html pages, can people just use backend framework to replace frontend using the HTML template feature provided by backend framework (Jinja2)? When do people need to use a frontend framework like React.js? -
Is it possible to submit a form with same name inputs django
In my app I am not sure how many inputs I need for that form. So I create inputs on the fly using django template for loop. When I submit the form it only takes the last input of the same one's. I have another solution which is to create input name differently using for loop in django forms and it works but I am not sure how do I write these inputs in django template such as. {{ form.samename1 }} {{ form.samename2}} Is there a way I could concatenate strings on django template which create the above result using a for loop.? -
How to set permissions per handler function with APIView?
I am writing an API for a small school-related project using Django and Django-Rest-Framework. I am trying to figure out permissions. I am using APIView for my views, and am looking to set different permissions for each handler method without writing more views. Here is one of the views for the blog module that I have: (This view is used for /posts/) from .serializers import * from django.db.models import Case, When from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework import status, permissions # Create your views here. class PostList(APIView): """ API Endpoint to List Posts METHODS: GET, POST """ @permission_classes([permissions.AllowAny,]) def get(self, request, format=None): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @permission_classes([permissions.IsAuthenticated]) def post(self, request, format=None): serializer = PostCreationSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save() data = serializer.data data["id"] = obj.id return Response(data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) The current default is permissions.IsAuthenticated, though changing that would not necessarily help as I would still need to change some permissions individually. So I should be able to make a GET request while not authenticated to /posts/ and get a list of all posts, while I should get a 401 from a POST request to /posts/. … -
Django model problem : (fields.E304) Reverse accessor for a model clashes with reverse accessor for an other/same model
i'm writing a simple model`with a foreignKey field which refer to the author of a specific article but i got this error message when making migrations. I know the the problem will be solved by adding related_nameattribute to the field but i want to understand why is this happening ? thank you for your time SystemCheckError: System check identified some issues: ERRORS: articles.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. users.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. my articles.models file from django.db import models from django.conf import settings class Article(models.Model): title = models.CharField( max_length=250) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() def get_absolute_url(self): return reverse("article_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title -
Make Django Template Font Smaller if Object Long
I'm trying to get make my heading font smaller if there are more than 20 characters. For some reason it doesn't seem to render the smaller font when I have a long heading. <div class="col-12 col-md-9"> <a href="{% url "pmp:project_detail" project.id %}"> {% if project > 20 %} <h1 style="font-size:.7em;">{{ project }}</h1> {% else %} <h1>{{ project }}</h1> {% endif %} </a> </div> -
AttributeError: 'UserVote' object has no attribute 'model' in Django
Trying to add this voter class to a custom user model. I don't think I needed to create a custom model the way I did, but I'm already into it and I'd prefer not to start from scratch. Basically, I'm trying to create a matching system where two users can select yes or no to each other and then be matched. Anyhow, the migrations worked. But, when I go to add it to admin.py, I get " AttributeError: 'UserVote' object has no attribute 'model' " **Models.py ** from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User from dating_project import settings class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Profile(AbstractBaseUser): email = models.EmailField(verbose_name="email") username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
Django-Filters : override method to allow property's model filtering
This is a model containing some field and a property carbs_g_secured : Models.py class Food(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) ingredients_label = models.TextField() moisture_g = models.DecimalField(max_digits=4, decimal_places=1, blank=True, null=True) def __str__(self): return self.name def carbs_g_secured(self): # If moisture is missing if self.carbs_g : return self.carbs_g,'Carbs provided' else : return None, 'Moisture is missing' I'd like to do some min/max filtering with django-rest-framework on the the carbs_g_secured property. I know I can't do that directly with Django-filters but I try to override the whole thing. I have the following approach : Serializers.py class FoodSerializer(serializers.ModelSerializer): carbs_g_secured = serializers.ReadOnlyField() class Meta: model = Food fields = '__all__' Views.py class FoodFilter(filters.FilterSet): carbs_g_secured_max = django_filters.NumberFilter(method='MyPropertyFilter') class Meta: model = Food fields = {'name': ['exact', 'in', 'startswith'], 'species':['exact'], 'protein_g':['exact','lte','gte'], 'carbs_g_secured_max':['exact']} def MyPropertyFilter(self, queryset, name, value): results = [row for row in queryset if value and row.carbs_g_secured()[0] and row.carbs_g_secured()[0] < value] return results Problem is this is returning a list where it's expecting a query set. web_1 | AssertionError: Expected 'FoodFilter.carbs_g_secured_max' to return a QuerySet, but got a list instead. So it seems I'm a bit stuck. I think it's not good practise to transform this list into query set. What do you guys … -
How to detect when HttpResponse(content_type='text/csv') is returned starts in Django Template?
I have a button in my template which when clicked converts a particular model to csv file and download begins. <a href="{% url 'down' %}" >Download csv File</a> The view: def down(request): allobj=resource.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="resources.csv"' writer = csv.writer(response) writer.writerow(['Name','Email','Resource']) for obj in allobj: writer.writerow([obj.name,obj.email,obj.resource]) return response Problem: I want to show a loading gif as the model is pretty big. I can start the animation when the link is clicked, but I need to know when to stop it. So is there a way to detect in the template when the response is returned or when the download begins? I know its easy to detect when a view has functioned successfully using Ajax, But how would I implement the downloadable link using ajax as it usually has a Json response but here I have a response = HttpResponse(content_type='text/csv') -
How to manage downloadable files in Django
In my Django application users can upload a PDF in the admin section. I would like these PDF files to be able to be downloaded on the public site. This works fine locally but in my production environment I get a 404 not found error for these files. I'm wondering what is the best way to serve these type of files so that they can be downloaded ? I have done some googling and seen some people mentioning that they should be hosted on another server. Is this the best approach or can they be hosted within the Django app for download ? Here are my settings for where these files are located : # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
How to do RTL with django-easy-pdf
I'm using django-easy-pdf in a project to provide an output report. Works great. I'm just adding Hebrew to the languages available and I cannot get the output in RTL. I've tried a number of approaches to force RTL formatting including hard-coding html, body, p, table, tr, td, span { direction: rtl; } within the tags in base.html. Does django-easy-pdf support RTL and if so, how do I implement it? -
Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id'
i am using nested for loop in django template to print data which i get from the data base {% if objectives %} {% for obj in objectives %} {% for sobj in sobjective %} {% if sobj.id==obj.id %} yes {% endif %} all the open tags are closed but its raising an error as i mentioned above TemplateSyntaxError at /objectives Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id' -
python3 nested namespace packages as Django modules
I'm struggling since months with a problem when using Python nested packages with Django. I have a project which is a Django framework, consisting of several packages, some of them are even Django apps, It's open source, you can even look at the code if it helps. There is one package gdaps which is core functionality, plugin manager etc. Then there should be a gdaps-frontend package which bundles basic frontend matters. And then, there are several plugins for frontends, like 'gdaps-frontend_vue`etc. Now, to address e.g. from gdaps.frontend.api import foo (part of gdaps-frontend), I think that gdaps and gdaps.frontend both should be nested namespace packages. They must not have init.py files The problem now is, that gdaps and gdaps.frontend also are Django apps. Which need a init.py file with a "default_app_config="foo.AppConfig" declaration in it for conveniently finding the AppConfig. I can't get it right here. Either with init.py - then imports go wrong, or without, then Django doens't find the app. I also have a version string in gdaps and gdaps.frontend which I use in several places. Any ideas How to solve this? -
Django: "No comment found matching the query" 404 Error
I'm making a simple blog app with comments on a 'posts detail view' page, but I'm getting a 404 error saying "No comment found matching the query" whenever I try submitting my comment. Everything else in the app works except for the comments. I'm new to django and am making this site to learn, would appreciate any help! Views.py class PostDetailView(DetailView): model = Post fields = ['content'] class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] template_name = 'blog/comment.html' def form_valid(self, form): post = self.get_object() form.instance.author = self.request.user return super().form_valid(form) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_posted'] def __str__(self): return f'Comment {self.content} by {self.author.username}' def get_absolute_url(self): return reverse('comment', kwargs={'pk': self.pk}) urls.py from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, CommentCreateView ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/comment/<int:pk>/', CommentCreateView.as_view(), name='create'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] comments.html This is the form. It's supposed to redirect to a different form to comment then back to post detail view {% extends "blog/base.html" %} … -
Javscript POST requests being saved to database in different order than sent
I'm sure there is a much more elegant way of writing this JS using a for loop (open to suggestions!). I am attempting to use JS to POST to my django database using django REST. The code below is achieving that, but is not written in order... The user inputs text into 10 different text boxes, then the script writes them to the database. The problem is that when it is written into the database, it is not in the order it was entered on the webpage. It seems to be random. Any ideas why? addAgendaItems.js function saveUpdates(id) { let ai1 = document.getElementById("item1").value let ai2 = document.getElementById("item2").value let ai3 = document.getElementById("item3").value let ai4 = document.getElementById("item4").value let ai5 = document.getElementById("item5").value let ai6 = document.getElementById("item6").value let ai7 = document.getElementById("item7").value let ai8 = document.getElementById("item8").value let ai9 = document.getElementById("item9").value let ai10 = document.getElementById("item10").value if (ai1 != ''){ changeData(id, ai1); } if (ai2 != ''){ changeData(id, ai2); } if (ai3 != ''){ changeData(id, ai3); } if (ai4 != ''){ changeData(id, ai4); } if (ai5 != ''){ changeData(id, ai5); } if (ai6 != ''){ changeData(id, ai6); } if (ai7 != ''){ changeData(id, ai7); } if (ai8 != ''){ changeData(id, ai8); } if (ai9 != ''){ changeData(id, … -
Connecting uwsgi with Nginx does not work
I'm trying to connetc my django app with nginx via uwsgi, but it seems that the passing of data to uwsgi does not happen. I've tested that the uwsgi server is running properly and do not get any log output on either end. uwsgi.ini [uwsgi] module = MyDjangoApp.wsgi:application master = True ;http-socket = :8001 #to run uwsgi on its one to ensure that it works socket = :8001 vacuum = True max-requests = 5000 plugin = python3 enable-threads = True /etc/nginx/sites-available file tree default serverDjango_nginx.conf serverDjango_nginx.conf: # the upstream component nginx needs to connect to upstream django { #server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media # location /media { # location /media { # alias /path/to/your/mysite/media; # your Django project's media files $ # } # location /static { # alias /path/to/your/mysite/static; # your Django project's … -
Django: can't able to import views in urls.py 'from pages import views'
from django.contrib import admin from django.urls import path, include from pages import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('dashboard/', include(pages.urls)), ] I'm trying to import views from pages directory (which is a app in django) like this 'from pages import views' but this isn't working. See the image bellowAs shown in image the when i'm trying to import views from pages it gives me error saying no module pages