Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL with parameter not working with include
I am trying to pass a parameter to a url before my include statement. I think my problem should be similar to this one, but I can't figure out why mine isn't working. I get the error NoReverseMatch at /womens/ Reverse for 'shampoo' with arguments '('womens',)' not found. 1 pattern(s) tried: ['(?P<gender>womens|mens)/items/shampoo/$'] *config.urls* urlpatterns = [ re_path(r'(?P<gender>womens|mens)/items/$, include('items.urls')), ... ] *items.urls* urlpatterns = [ path('shampoo', views.shampoo, name='shampoo'), path('soap', views.soap, name='soap'), ... ] {% url 'items:shampoo' gender='male' %} I expect to get male/items/shampoo, but it doesn't work. Despite this, I can still manually go to male/items/shampoo. -
how to filter many-to-many fields in django models
I have 3 models: User , Tag and Recipe. User model is so basic and it's not important. Here is the Tag model: class Tag(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=CASCADE) And here is the Recipe model: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=CASCADE) title = models.CharField(max_length=255) tags = models.ManyToManyField('Tag',) I made endpoint for all of these models but there is one problem! When I try to create a Recipe object, all of Tag objects will be listed, But I want to list just the logged in user tags. Here is my Tag serializer: class TagSerializer(serializers.ModelSerializer): class Meta: model = models.Tag fields = ('id' , 'name') extra_kwargs = { 'id' : { 'read_only' : True, } } And here is my Tag viewset: class TagsView(RecipeAttrsView): queryset = models.Tag.objects.all() serializer_class = serializers.TagSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return self.queryset.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) How can I filter tags, so that all listed tag objects belong to the logged in user? -
Calling a function from a function
I have some logic within a view that I want to have rendered on multiple templates. How do I call the logic view from within another view and pass the data back to the view to be rendered? This is a simple test I was doing. def table_view(request): today = now().date() project_data = get_data_view context = {'projects_data':project_data} return render(request, "pages/project_table.html", context=context) def get_data_view(request): project_list = Project.objects.all() context = {"project_list":project_list} return {'context':context} The table view just renders a table, but the data within the table I want from the get_data_view I know I can write the logic within the same view, but some of my views contain a lot of code and don't want to be repeating the same code to retrieve the same data. -
ERROR: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 47: 'else'. Did you forget to register or load this tag?
How to solve problem How to solve problem How to solve problem -
How can I supress this type error from Django create_user?
I'm getting the following type error from pylance: from django.contrib.auth.models import User, AbstractUser from django.contrib.auth import get_user_model get_user_model().objects.create_user(**user_data) # ^- Cannot access member "create_user" for type "BaseManager[Any]" # Member "create_user" is unknown Pylance reportGeneralTypeIssues # User.objects.create_user(**user_data) # same error # AbstractUser.objects.create_user(**user_data) # same error For some reason it thinks AbstractUser.objects has a broader type BaseManager[Any] instead of UserManager, even though AbstractUser defines objects = UserManager(). The code works without errors when tested. Does anyone know how I can supress or get rid of this sort of type error? -
Populate drop down from a database column without repetition - Django
am learning Django while building Hostel booking application. I want the drop down list found in index.html to be populated from a database column called "location". I would like to retrieve the second elements (the human-readable names) without repetitions. So far I have tried as shown in the codes below but I am getting repetitions whenever I have many hostels sharing the same location. I understand to obtain the list of distinct column names from the database is to use distinct() in conjunction with values(). But how do I use distinct() with get_FOO_display() at the same time to get distinct columns as well as the second elements of the tuples. Or is there another approach I should take? models.py HOST_LOCATION=[('KM', 'Kings Main Campus'), ('KT', 'Kings Town Campus'), ('KK', 'Kings Kitale Campus'), ('KE', 'Kings Eldoret Branch')] class Hostel(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(null=False, unique=True, blank=True) location = models.CharField(max_length=50, choices=HOST_LOCATION, default=None, null=False) landlord = models.ForeignKey(User, on_delete=models.CASCADE, default=None) def __str__(self): return self.name Views.py def index(request): Host = Hostel.objects.all() return render(request, 'index.html', {'Host': Host}) Template <select class="custom-select" id="inputGroupSelect04"> <option selected disabled> SELECT A CAMPUS TO FIND HOSTEL</option> {% for entry in Host %} <option value="{{ entry.id }}">{{ entry.get_location_display }}</option> {% endfor %} </select> -
Django - Return months that posts by a user spans given time offset from UTC
I'm working on a social media app and I want user A to be able to get all the months that user B posted in user A's time zone. The front-end is in Javascript the most sensible thing would be for a user to send their time zone's offset from UTC (Can be done with new Date().getTimezoneOffset() in JS) as this is what time zone dates are saved in Django. So for example user A would ping a url that looks something like /<user B's username>/<year>/<user A's time zone offset from UTC>. Let's say user B is in PST and created a post at November 15 2021 12:00pm and December 31 2021 at 11:00pm. Then let's say user A who's in EST calls that url then it should return [November, January] (Or the equivalent numerical mapping), because December 31 at 11:00pm PST is January 1st at 2:00am EST. How can I return all months user B posted in user A's time zone, give user A's time zone offset from UTC? models.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) -
drf-spectacular: Add OpenApiResponse to a serializer-less function-based view
So, I'm documenting the following piece of code using drf-spectacular: from rest_framework import response from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_framework import status from drf_spectacular.utils import extend_schema, OpenApiParameter def passcode_generator: return 0 # placeholder @extend_schema( parameters=[ OpenApiParameter(name="callsign", required=True, type=str), ], description="Get an APRS-IS passcode for a given callsign", ) @api_view(["POST"]) @permission_classes([AllowAny]) def get_passcode(request): callsign = request.data.get("callsign", None) if callsign is None: raise Response( {"error": "Missing callsign"}, status=status.HTTP_400_BAD_REQUEST ) return Response({"passcode": passcode_generator(callsign)}) What I can't understand how to do is how to document the responses. Namely, there is OpenApiResponse in drf_spectacular.utils but the documentation is very slim. How can I document the responses of my API with this system? -
Can I use standard generic CreateView for model formset?
I am again stuck with model formset. I have following form: ArticleFormSet = modelformset_factory(Article, fields=('title', 'pub_date'), extra=3) and View for this model formset: class ArticleCreateView(CreateView): model = Article form_class = ArticleFormSet template_name = 'article_form_view.html' success_url = "/" Reading documentation here: https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#model-formsets I understand that, I can use ArticleFormSet instead of standard form for form_class attribute. So basically, what I am expecting is, this should display 3 forms for the same Article model and I should be able to create three articles at the same time. But I am getting "TypeError: init() got an unexpected keyword argument 'instance' ". So the question is, is this how it supposed to work? Or what would be the correct way of creating few articles at the same time? -
Django form - only show checkbox's with True values
This image shows how currently all 'tags' are displayed whether True or False. browser view of checkboxes I am trying to find a simple way to only display checkboxes for those 'tags' with a true value. Can I add an 'if' statement to this code in forms.py (e.g. within the widgets Meta, or in CheckboxSelectMultiple()) ? class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) The Project class (model) underlying the ProjectForm only stores the 'True' Tags on a many-to-many relationship. See image of sqlite showing only 'True' value Tags/Checkboxes are stored with each Project: view of sqlite database tables The ProjectForm (shown above) is used to create or update a single project and therefore only displays fields for that single project. Yet the widget containing the checkboxes is displaying the checkboxes used by all projects (not just the specific project being created/edited). HTML template Form is as follows: <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <!-- Input:Text --> <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} … -
Django. How to automatically select the desired user in the form
I recently started studying Django. I have a model that is associated with users. Need to fill in the "User" field automatically. I wanted to use request.user, but my attempts were unsuccessful. Can you tell me how to do it correctly? Sample from - https://i.stack.imgur.com/zcwLk.png models.py class Ticket(models.Model): ticket_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') ticket_title = models.CharField(max_length=100) ticket_date_open = models.DateTimeField(auto_now_add=True) ticket_status = models.BooleanField(default=False) ticket_reason = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='User') forms.py class TicketForm(ModelForm): class Meta: model = Ticket fields = ('ticket_title', 'ticket_status', 'ticket_reason', 'user',) views.py class CreateTicket(CreateView): form_class = TicketForm template_name = 'support/new_t[enter image description here][1]icket.html' success_url = reverse_lazy('test') Form - https://i.stack.imgur.com/zcwLk.png -
Context Class for All Views Classes in Django
Is there a way to pass context or a variable to all Views Types Classes ? For example, I would like to set context for all views with: context = {'title': admin.site.site_title} I had to create one class for which type of Views Classes, like: class TitleView(View): context = {'title': admin.site.site_title} def __init__(self, **kwargs): kwargs = self.get_context_data(**kwargs) View.__init__(self, **kwargs) def get_context_data(self, *, object_list=None, **kwargs): self.context['title'] = kwargs['title'] = admin.site.site_title return kwargs class TitleCreateView(CreateView): context = {'title': admin.site.site_title} def get_context_data(self, *, object_list=None, **kwargs): self.context['title'] = kwargs['title'] = admin.site.site_title return CreateView.get_context_data(self, **kwargs) And descend from them the site views. Considering there are several different types of Views (View, FormView, CreateView, UpdateView, etc) and considering they are different (View class doensn't have get_context_data, for example), I would like a way to set context with less code and classes using Mixin or other centralized way for all Views. -
NoReverseMatch at /authentication/register Djangoproje
After i click register button then it shows this error.it shows like this i want this to send activation link to the user account.. after i submit the register button then user is registered but it doesnt send any activation link and shows this error.. please help me code in views.py code for sign up and activate link. class RegistrationView(View): def get(self, request): return render(request,'authentication/register.html') def post(self, request): username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] context={ 'fieldValues':request.POST } if not User.objects.filter(username=username).exists(): if not User.objects.filter(email=email).exists(): if len(password) < 6: messages.error(request, 'Password too short') return render(request, 'authentication/register.html',context) user = User.objects.create_user(username=username, email=email) user.set_password(password) user.is_active = False user.save() uidb67 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link = reverse('activate',kwargs={'uidb67': uidb67,'token': token_generator.make_token(user)}) activate_url='http://'+domain+link email_body = 'Hello '+user.username+ \ 'Please use this link to verify your account\n' +activate_url email_subject='Activate your account' email = EmailMessage( email_subject,email_body,'noreply@semicolon.com', [email], ) email.send(fail_silently=False) messages.success(request,'Account successfully created') return render(request,'authentication/register.html') return render(request,'authentication/register.html') class VerificationView(View): def get(self,request, uidb64, token): return redirect('login') in utils.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() in urls.py path('activate/<uidb64>/<token>',VerificationView.as_view(),name="activate"), in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'main')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
How to display decimals only if necessary in Python
Is there an easy way in Python to display the decimal only if it is necessary - i.e. if it is not 0. For example: print(1.0) > 1.0 print(2.5) > 2.5 Is there a standard function that does: some_function(1.0) > 1 some_function(2.5) > 2.5 I could manually check if int(a) == a (as described here), but I was wondering if there was a built-in/standard way of doing this already. -
Django admin lag dates in model based on view
In Django I builded a model based on view and in admin account i see there is added values that are not present in postgresql database. These are ordered values in db view: but in admin values looks like laged by 1 day: Model in django looks like this: class VBalance(models.Model): id = models.IntegerField(primary_key=True) date = models.DateField() balance = models.DecimalField(max_digits=14, decimal_places=2) class Meta: managed = False # Created from a view. Don't remove. db_table = 'v_balance' def __str__(self) -> str: # return "Balance: " + "{:.2f}".format(self.balance) + " on: " + self.date.strftime("%m/%d/%Y") return "Balance: " + str(self.balance) + " on: " + self.date.strftime("%m/%d/%Y") Any ideas how to fix this? -
How to populate FormView with initial data?
While reading Django's documentation, I am trying to practice at the same time. Today I am reading Formsets; https://docs.djangoproject.com/en/4.0/topics/forms/formsets/ Now I am trying to populate generic FormView with initial data. Here is the code: class ArticleFormView(FormView): # same here, use FormSet instance, not standard Form form_class = ArticleFormSet template_name = 'article_form_view.html' success_url = "/" def get_initial(self): init_data = {'value1': 'foo', 'value2': 'bar'} return init_data And this results a "in _construct_form defaults['initial'] = self.initial[i] KeyError: 0" So the question is how do I populate a formset in a FormView with initial data? -
Error in Django -- if max_value is not None and max_value < 0.: TypeError: '<' not supported between instances of 'dict' and 'float'
I want to deploy my keras MobileNet model on web application for skin classification using Django. i have trained model file mobile.h5 but when i run the program on pycharm and on localhost i upload the picture for classification and get this error Error in Django -- if max_value is not None and max_value < 0.: TypeError: '<' not supported between instances of 'dict' and 'float' import keras.models import tensorflow.keras.applications from django.shortcuts import render #import torchvision #import torch.nn as nn from PIL import Image #import torchvision.transforms as transforms import base64 from .forms import ImageUploadForm import numpy as np def getClassOfImage(image): #net = torchvision.models.mobilenet_v2(pretrained=True) #net.classifier[1] = nn.Linear(net.last_channel, 100) mob = tensorflow.keras.applications.mobilenet.MobileNet() classes = ('akiec', 'bcc', 'bkl', 'df', 'mel', 'nv') path = "classifyImage/models/mobile.h5" checkpoint = keras.models.load_model(path) mob.load_state_dict(checkpoint['mob']) mob.eval() #transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) transf = tensorflow.keras.layers.experimental.preprocessing.Normalization(mean=[0.5,0.5,0.5], variance=[np.square(0.5),np.square(0.5),np.square(0.5)]) img = Image.open(image) img = img.resize((224, 224)) input = transf(img) input = input.unsqueeze(0) output = mob(input) _, predicted = tensorflow.keras.layers.maximum(output, 1) print('Predicted: ', classes[predicted[0]]) return classes[predicted[0]] strong text def index(request): image_uri = None predicted_label = None if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] image_bytes = image.file.read() encoded_img = base64.b64encode(image_bytes).decode('ascii') image_uri = 'data:%s;base64,%s' % ('image/jpeg', encoded_img) # … -
Facing Issue to make the UUID as endpoint in Django Rest framework
As I am new to Django I am unable to make the endpoint in API in the rest-framework library how to make the UUID as an EndPoint their This image shows the models in id as UUID Serlize the object to data Try to view using ModelViewSet Route the API and make the UUID as an Showing This Error How to Resolve this Error -
how to add facebook-login in django
Hello guys I am a junior web developer: I created an app that I want to link it with Facebook login: I mean when a user click on login with facebook then it would redirect him to my App dashboard. I have watched and read a lot of tutorials and documentations, but all I sees was using a localhost in the facebook developer dashboard under the App Domain section, but my app was already in Heroku, can I use the localhost for the productions like how I sees the tutorials? or my app domain name generated by heroku, sorry I get confused? it's necessary to create the user models in the Models.py or Not. -
Link to Home page from the sub-page in Django
I have a one-page Django site. There's only one app called homepage and inside this page, I have menu items linked to anchors in the same page. Everything works fine. I also have a sub-page, 'privacy.html'. In this page I have the same menu system, and this is how I've linked the menu items: <a href="{% url 'homepage:index' %}#anchor>Menu Item</a> The issue is {% url 'homepage:index' %} actually returns / which is correct, but this makes the menu items to point to the anchors in the current page (privacy.html), while they are in the homepage.html file. I understand this happens because those pages are inside same app, but creating a second app just to display a single HTML file is overkill. Is there any solution to this? -
url guarding in django detail view
I am trying to fix url guarding issue while using DetailView in django web for displaying a particular object (product) details and passing id (pk) to url that doesn't exist in the product model (table) instances. currently it shows Type Error like "No products found matching the query" . instead i am looking for a way to display caution page to the user that the required product id doesn't exist. Illustrated as sample below models.py from django.db import models class Products(models.Model): product_name=models.CharField(max_length=200) product_descript=models.CharField(max_length=200) product_price=models.IntegerField() def __str__(self): return self.product_name url.py from django.urls import path from . import views urlpatterns=[ path('product/detail=<int:pk>',views.ProductDetailView.as_view(), name='detail'),] views.py from django.views.generic.detail import DetailView from .models import Products class ProductDetailView(DetailView): model=Products template_name='food/detail.html' food/detail.html <div> <h1>Name: {{object.product_name}}</h1> <h3>Descrription: {{object.product_descript}}</h3> <h4>Price: {{object.product_price}}</h4> </div> Detail page while passing not exist id. -
I cannot display dynamic data in Django
View of base url View of the page when any one of link is clicked. Here the room name is not visible urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # python dictionary below rooms = [ {'id': '1', 'name': 'Lets learn Python!'}, {'id': '2', 'name': 'Design with me!'}, {'id': '3', 'name': 'Frontend Dev!'}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def room(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'room': room} return render(request, 'base/room.html', context) home.html {% extends 'main.html' %} {% block content %} <h1>HOME</h1> <div> <div> {% for room in rooms %} <h5>{{room.id}}</h5> <h2><a href="{% url 'room' room.id %}">{{room.name}}</a></h2> {% endfor %} </div> </div> {% endblock %} room.html {% extends 'main.html' %} {% block content %} <h1>{{room.name}}</h1> {% endblock %} Here, I tried rectifying the links and checking the functions in all the files. I believe there is something wrong in room.html file, but cannot find the error. -
Sending a parameter to the render function of pdf
I'm trying in Django to render from html to pdf a monthly report that takes data from a database by month. I need to send the selected month on the html page to the class that creates the Pdf. How can I do that? My view class : class view_pdf_monthly_report(View): def get(self, request, *args, **kwargs): push = {'month':month} pdf = render_to_pdf('home/pdf_monthly_inquiries_report.html', push) return HttpResponse(pdf, content_type='application/pdf') My html: how can I send the month from here? <div class="text-center"> <a class="btn btn-info" href="{% url 'view_pdf_monthly_report'%}" target="_blank">View PDF</a> </div> Thanks ! -
I am trying to sort and paginate object at the same time in django, but after paginating the sort gets reset
If I have applied the sorting to my wallpapers and after that if I try to paginate the sorting gets reset. like if I have sorted wallpapers according to pub date in ascending order and after pagination, it gets back to normal. view def home(request): WAllPAPER_PER_PAGE = 4 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator import json from django.core.serializers.json import DjangoJSONEncoder from django.db.models import Q ordering =request.GET.get('ordering', "") search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)) else: wallpapers = Wallpaper.objects.all() if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) -
Django comment form
I am following the guide to create comment given by Django central, https://djangocentral.com/creating-comments-system-with-django/ and it is working. However I am using the {{ form.as_p }} Which will give 3 fields, as the form say, with name, email and the body. But i wanted to have predefined name, which would be your username you are logged inn with and the email attached to that account. How would i go ahead to create that? forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'email', 'body'] models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_added'] def __str__(self): return self.name views.py def post_detail(request, category_slug, slug, status=Post.ACTIVE): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', category_slug=category_slug, slug=slug) else: form = CommentForm() return render(request, 'blog/post_detail.html', {'post': post, 'form': form}) in the html template {% if user.is_authenticated %} <h2 class="subtitle is-4">Comments</h2> <form method="post" class="mb-6"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-success">Submit comment</button> </div> </div> </form> {% endif %}