Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} -
I'm Trying to allow multiple user to use jupyter lab for coding online on my website
I want to allow the user to log in to my Django app and have their code separately and should not be allowed to delete the code/Folder/Files which they have not created. For each user, the code should get saved separately Here is the git repository of my tried code https://github.com/Rajput612/django-jupyterlab Any Help Or guidance will be a great help as I want to create this for people who don't have the laptop at their disposal. -
Django-Rest-Framework: documenting parameters of function-based view without model
So, I have a function-based view on a DRF application that looks something like this: 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 def passcode_generator(callsign: str) -> int: return 0 # Placeholder @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)}) Clearly, "callsign" is the only expected argument, and it is mandatory. And that "passcode" is the only field in the response. But DRF doesn't know that. This means that DRF's web-browsable API page can't show the HTML form tab, and means that documentation generators can't properly document it: So the question is, how can one document this function-based view? Thanks! -
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 1135-1137: ordinal not in range(256)
I'm trying in Django to render from html to pdf a monthly report that takes data from a database in Hebrew. I have a problem that I have not been able to fix for several days. When I display data in English the pdf works properly and everything is fine, but when I want to display data in the Hebrew language from the database, it does not allow me and the following error appears: 'latin-1' codec can't encode characters in position 1135-1137: ordinal not in range(256) I have already tried a several solutions: I changed the font several times in the base html of the PDF via the css and it just does not help at all. I tried to change the rendering function I have at the moment and it also did not help at all. My rendering function : def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
Reverse for 'Newsdetail' with arguments '('',)' not found. 1 pattern(s) tried:Django error
In the following links direct to same URL name with different params, <div onclick="location.href='{% url 'newscountry' 'Saudi' %}'"> x </div> <div "onclick="location.href='{% url 'newscountry' 'UAE' %}'"> y </div> However when the second div element is clicked it gives an error, but the first link works fine. URL.PY path('country/<str:countryname>/',NewsCountryView.as_view(),name='newscountry'), VIEW.PY class NewsCountryView(ListView): model = News template_name = 'newsfront/index.html' # <app>/<model>_<viewtype>.html context_object_name = 'news' def get_queryset(self): country=self.kwargs.get('countryname') return News.objects.filter(country=country)