Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Can't set $(element).innerText after including in-browser babel to a django project
The moment I included babel, the following snippet stopped working as before. Perhaps it's because of the absence of a module bundler. I need react just for one UI component. index.js document.addEventListener('DOMContentLoaded', () => { document.querySelector('#' + VIEWS.profile).innerText = 'profile' }) index.html <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel" src="{% static 'network/index.js' %}"></script> The querySelector query returns the target element when tested in console under the same execution context. Babel reports, You are using the in-browser Babel transformer. Be sure to precompile your scripts for production Moreover, babel makes it hard to debug js in the browser. Is there any way around this? -
Password is not hashed on User model update
I have extended the AbstractUser model in django. When I post the SignUp form from Postman, the password gets hashed. But after sending the Put method in Postman for changing the password, the password gets showed in Django admin as it is not getting hashed. Models.py class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) Serializers.py from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from users.serializers import UserSerializer from users.models import User class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] I tried it in these way also by overwriting the serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, * args, ** kwargs): user = super().create( * args, ** kwargs) p = user.password user.set_password(p) user.save() return user def update(self, * args, ** kwargs): user = super().update( … -
how to resolve (1045, "Access denied for user 'User'@'IP or host' (using password: YES)") when build django docker container?
Well, I have multiple databases in django project. One is default and second istest_dev. i have created docker container. and then everything went well till building the container. after that When I try to call my django app api which is using test_dev db for reading data. I have encountered: OperationalError at /api/projects/ (1045, "Access denied for user 'test_dev'@'133.98.72.111' (using password: YES)") In settings file, my databases configuration: { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': Path(__file__).resolve().parent.parent / 'db.sqlite3', }, "test_dev" : { 'ENGINE': 'django.db.backends.mysql', 'NAME': "test_dev", 'USER': 'user', 'PASSWORD': 'db_password', 'HOST': '?=hosted_domain', 'PORT': '3306', 'SSL': True } } If you know any solution. Please help me out of this. Soon I have to put things on production.. -
Connect django+reactjs+firebase
How to send form data to firebase database via Django I connected Django to firebase ,how would I connect ReactJs to Django to send form data to firebase database using validation in python. If anyone has Github profile please paste it here so that I can take reference. -
Can't install opencv package in a Raspberry pi
So I am doing a face recognition project in a Raspberry Pi. It is a django project and when I run the server I get this error: AttributeError: module 'cv2' has no attribute 'face' I searched for the error and I came up with that I needed to install opencv-contrib-python The problem is that when I try to install it the download gets to 99% and I get this: 'pip3 install opencv-contrib-pyt…' terminated by signal SIGKILL (Forced quit). Does anyone know why this happens? how can I fix this? help is much appreciated -
How to create dynamic URL in Django when form is submitted
I am building a website in django where user search for student data by entering the roll number of the student. For example if user enters the roll number 001 in the form then student data should be fetch from database and Url should be https://www.studentdata.com/001 Similarly if user enters roll number 003 then the url should be https://www.student.com/003 and so on. I want to build website where I need to show thousands of student data. -
JSONDecodeError at / Expecting value: line 1 column 1 (char 0) when try to return response in a django rest_framework
I'm new to python rest_framework. I am trying to create a django website with two Apps. The first App has an HTML form which gets a city name from the user and then sends a request to the API in the second App, calls WeatherApp. In the WeatherApp I read data from database and serialize it but when trying to return response, I get this error: JSONDecodeError at / Expecting value: line 1 column 1 (char 0) This is the first App views: def index(request): context = {'form': form} if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] url = "http://127.0.0.1:8000/city/{}" city_weather = requests.get(url.format(name)).json() This is the WeatherApp views: def myfunc(self, cityname): query = City.objects.filter(name = cityname)[0] serializer = CitySerializer(query) return Response(serializer.data) This is the serializer: class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ("id", "name", "temperature") And this is my model: class City(models.Model): name = models.TextField(max_length=150) temperature = models.IntegerField(max_length=200, default=40) LastUpdate = models.DateTimeField(default= datetime.now) def __str__(self) -> str: return self.name When I debug the code, the error appears at return self.name in the model. Any help would be appreciated. -
How to upload a folder into a model field(In Admin panel), which will create an object for each file inside of that folder in Django?
I have a folder with 100 plus audio files from the same author. It would take time for me to upload each file separately to create 100 plus objects. What I want to do is in a model of the Author I want to have a field where I can upload a folder with all the audio files, which will then create a separate object for each audio file in that folder. -
Django OneToOneField Default value?
Hello Django OneToOneField Default value Inventory model class Inventory(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) energy = models.OneToOneF`ield(Product, default="Products.energy", null=True, on_delete=models.CASCADE) Products model class Product(models.Model): name = models.CharField(max_length=255) cost_for_sale = models.IntegerField() cost_for_buy = models.IntegerField() def __str__(self): return f'{self.name}' -
Error "ModuleNotFoundError: No module named 'psycopg2'" when deploying Django app to Google App Engine
I'm working on a Django application and using Fabric for deployment. When I deployed the apps to staging in Google App Engine using fab testing, I got this error: Updating service [staging] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [9] An internal error occurred while processing task /app-engine-flex/flex_await_healthy/flex_await_healthy>2022-01-01T09:48:30.226Z15496.fj.0: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/env/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/env/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/opt/python3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/env/lib/python3.6/site-packages/django/contrib/postgres/apps.py", line 8, in <module> from .signals import register_type_handlers File "/env/lib/python3.6/site-packages/django/contrib/postgres/signals.py", line 3, in <module> import psycopg2 ModuleNotFoundError: No module named 'psycopg2' I'm sure the psycopg2 has been installed successfully earlier. Here's the list installed dependencies after checking by pip list: ... platformdirs 2.4.0 prompt-toolkit 3.0.24 … -
django rest frame work, i was trying to create an exchange rate that compare the first currency to the second currency and print the value of second
from Django .shortcuts import render import requests from exchange rate .models import Exchange rate from . serialize import Exchange rate Serialize from rest framework .response import Response from rest_ framework import view sets from .models import Exchange rate class Exchange value(view sets .Model View Set): query set=Exchange rate .objects .all() serialize _class = Exchange rate Serialize def get(request, rate1, rate2): if request .method =='POST': url="https://api.exchangerate-api.com/v4/latest/USD" res=requests .get( URL ) result =res .Jason () try: if rate1 in result: return render(request ,result[rate2]) except Exception as e: print("currency could not be process")