Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter the database through dropdown with the help of ajax?
Thank you for your help. I have a template that takes a value from the user via dropdown, then this value is sent to the server via ajax. I want to filter the database data based on this value. But after filtering, the queryset value in the template is empty. Why is the queryset empty? my template: my ajax code views code: Filter data based on data received from the user via ajax Where filtered data should be displayed: enter image description here What is currently displayed: There is no data -
How to disable ALLOWED_HOST check on paticular Django REST API URL?
IS there any way to disable DJANGO ALLOWED_HOST check on particular API URL, We want to allow API requests from list of websites(HOSTS), but there is RFID reader machine which will also be writing data on our DJANGO server using REST API and we want to make only that particular REST API URL public and other REST APIs should be allowed as ALLOWED_HOST check of DJANGO. -
Models relationship and mapping of models
I have a Warehouse model and an Item Model, simplified to - class Warehouse(models.Model): warehouseCode = models.CharField(max_length=30) class Item(models.Model): itemCode = models.CharField(max_length=30) and a third model to map the relationship as whether an item can be stored in a warehouse or not. (locked is the field) class ItemWarehouse(models.Model): item = models.ForeignKey(ItemMaster) warehouse = models.ForeignKey(Warehouse) locked = models.BooleanField(default=False) The system is designed such that before creating any item at least we should have one warehouse. Now suppose we have 2 warehouses (warehouse_1 and warehouse_2) and we created the First item. As mentioned above warehouse_1 can have the item First and warehouse_2 is locked for item First (No transaction of item First can be done in warehouse_2). The question is after creating 500 such items (n numbers of items), we created 1 more warehouse called warehouse_3. What should be the optimized or best way to map the relationship of the newly created warehouse with all the previously created items. Thinking in mind of system design and UI design. I'm using the rest framework and frontend client. Or a better complete design than what I have till now. -
How to define ManyToManyField in Django for tests
To test my serializers in django rest framework I use Model Name.objects.create method to create fields. But I can't create ManyToManyField. Guess, firstly I need to create objects for first model and for second model otherwise ManyToManyField bound can't be created. But still can't define ManyToManyField for test with create method. Please help me to realize how it should work correctly. I've red django documentation, but haven't got how to solve my issue. Here is my code example: models.py class Book(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=7, decimal_places=2) author_name = models.CharField(max_length=200) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='my_books') readers = models.ManyToManyField(User, through='UserBookRelation', related_name='books') test.py class BookSerializerTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_username') self.book_1 = Book.objects.create(name='Test book 1', price=750, author_name='Author 1', owner=self.user) self.book_2 = Book.objects.create(name='Test book 2', price=650, author_name='Author 1', owner=self.user) def test_readers(self): users = [self.user] reader = self.book_1.readers.set(users) print(f'Readers: {reader}') readers is None, how to define self.user? Thank you in advance. -
"get()" Record from Django SQLite3 DB AFTER Encryption with django_cryptography
I have created a Django application, where I ask the visitor of the site to input their name into a form. Upon POST submission, it stores their name, and the IP address they are visiting from into an SQLite3 database. For practise, I encrypt the IP address before storing it in the db. If the user "returns" to the site, my code is set to find a record for that user in the db first, based on their IP address. If there's already a record in the db with that IP, it'll display a "welcome back" message. If I don't encrypt the IP, my app works fine, but when I attempt to use django_cryptography I get stuck. What I have so far is: models.py from django.db import models from django import forms from django_cryptography.fields import encrypt INT_MAX_NAME_STRING_LENGTH = 100 # Previous visitors object class Previous_Visitor_Model(models.Model): visitor_name = models.CharField(max_length=INT_MAX_NAME_STRING_LENGTH) visitor_ip = encrypt(models.CharField(max_length=16)) # IP_Address_Field() # The name form on the initial page class NameForm(forms.Form): visitor_name = forms.CharField(label='Your (company) name', max_length=INT_MAX_NAME_STRING_LENGTH) So I encrypt their IP address in the model. When a visitor enters their name into the form and submits, a new record is created in the db, with their name, … -
Django log out view doesn't work (no network traffic)
I'm learning Django to build the back end for my website. I'm making an authentication app for the project. I'm testing it using a separate html file instead of template since I want to eventually connect it with my front end. The log in view works fine but the log out one doesn't. It prints to the server terminal what looks like a success message: "POST /members/logout_user/ HTTP/1.1" 200 10 but it doesn't do anything in the browser. There is no network traffic. Views: from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.http import HttpResponse from rest_framework.decorators import api_view @api_view(['POST']) def login_user(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse("Logged in") else: return HttpResponse("incorrect") @api_view(['POST']) def logout_user(request): logout(request) return HttpResponse("logged out") My html client: <!DOCTYPE html> <html> <body> <form method="POST" action="http://127.0.0.1:8000/members/login_user/"> User name: <input type="text" name="username" id="username" /> <br /> Password: <input type="password" name="password" id="password" /> <input type="submit" /> </form> <button onclick="logout()">Log out</button> <script> function logout() { csrf_cookieValue = document.cookie .split(";") .find((row) => row.startsWith("csrftoken")) .split("=")[1]; let xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:8000/members/logout_user/"); xhr.setRequestHeader("X-CSRFToken", "csrf_cookieValue"); xhr.send(); </script> </body> </html> -
relation "users_user" does not exist
so I am trying to migrate my app after just creating a project and this error just pop up out of the blue.. LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."user.... the only thing I did differently was that I used abstract user to extend my user models so that I can be able to give my user a specific role.it also does not allow me to create a super user as it throws the same error. I am new to all of this so some help can be really useful currently using Django 4.04. I tried deleting all migrations files and rerun migrations and didn't change anything models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_admin = models.BooleanField('Admin', default=False) is_teacher = models.BooleanField('Teacher', default=False) class Teacher(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) class Admin(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] AUTH_USER_MODEL = 'users.User' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') LOGIN_REDIRECT_URL = 'dashboard/' LOGIN_URL = 'login/' form.py from attr import field from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm class TeacherRegisterForm(UserCreationForm): email = forms.EmailField() class Meta(UserCreationForm.Meta): model = User fields = … -
Django count all unique accurance of a many to many field
I have models like : class Book: author = models.ManyToManyField() class Author: ... I want to get all unique authors that have books. example BookA: AuthorA, AuthorB BookB: AuthorB, AuthorC Auther D, E, F has no book so the result should be a query set of Author ABC. Most existing answers are just count of authors of each book. Thanks -
Permission for owner that user account
I building 2 permission for the user account owner and the apartment owner. Although they have the same code, the user account owner doesn't work. permissions.py class IsOwnerUserOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.username == request.user # Not Work class IsOwnerApartmentOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.seller == request.user # Work OK views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerUserOrReadOnly] class ApartmentViewset(viewsets.ModelViewSet): queryset = Apartment.objects.filter(issold=False).order_by('-timestamp') serializer_class = ApartmentSerializer # Set permission for only user owner apartment can edit it. permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly] -
Problem in logging in the user in django webpage
I have issues with creating a login page in django. I am done with the views and html and stuff but the issue is that when I hit login it won't log the user in. After some debugging I saw that the issue is that the value of the user is None but I don't know why If anyone could help me with this it would be great i am posting the code below: views:- from django.shortcuts import render, redirect from .forms import RegisterForm, ProfileForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate def loginUser(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] try: user = User.objects.get(email=email) except: print("User does not exist!") user = authenticate(request, email=email, password=password) if user is None: login(request, user) return redirect('home') else: print('The email or password is incorrect') html:- <div> <div class="login-container"> <div class="header-container"> <h1 class="header-text heading"><span>login</span></h1> </div> <div class="login-container1"> <div class="login-container2"> <span class="login-text biggerSubHeading">welcome</span> <form method="POST"> {% csrf_token %} <div class="login-container3"> <div class="label-container"> <label class="label"><span>Email</span></label> </div> <input type="text" name="email" placeholder="placeholder" class="login-textinput input" /> </div> <div class="login-container4"> <div class="label-container"> <label class="label"><span>Password</span></label> </div> <div class="password-field-container"> <div class="password-field-container1"> <input type="password" name="password" placeholder="placeholder" class="password-field-textinput input" id="lPassword" /> </div> <div class="password-field-container2"> <input type="checkbox" onclick="reveal3()" id="check3" class="password-field-checkbox" /> … -
How to handle two Django forms in one view?
I have a view that contains two Django forms. They were previously working but now whichever one is underneath the top one does not work. I have tried switching the order of the forms and whichever form is on the top will work while the other one will not do anything when submitted. I tried changing my forms so they resemble this example if request.method == "POST" and "selectgenderform" in request.POST: but that did not work (the forms did nothing). Does anyone know how to fix this problem? part of views.py def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) #code for comment and bid forms listing_price = listing.bid sellar = listing.user comment_obj = Comments.objects.filter(listing=listing) #types of forms comment_form = CommentForm() bid_form = BidsForm() #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for bid in other_bids: if bid.bid > max_bid: max_bid = bid.bid #checks if request method is post for all the forms if request.method == "POST": print(request.POST) #forms comment_form = CommentForm(request.POST) bid_form = BidsForm(request.POST) #checks if bid form is valid if bid_form.is_valid(): print('!!!!!form is valid') #print("bid form is valid") print(listing.bid) new_bid = float(bid_form.cleaned_data.get("bid")) if (new_bid >= listing_price) or (new_bid > max_bid): bid = bid_form.save(commit=False) … -
Django: Download a temporary image
I am currently trying to create a function within a Django app to download a pandas dataframe as an image. I wanted to create the image as a temporary file, download it, then delete it. Does anyone know how to integrate tempfile into this code? Views.py def download_png(request, study): Names(study) #Funciton to get (name) variable Retrieve(study) #Function to get (data) variable BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pngfilename = str(name) + "_" + str(current_time) + ".png" temp = tempfile.NamedTemporaryFile(suffix=".png") fig = temp.write(df2img.plot_dataframe(data)) filepath = temp.name response = HttpResponse(df2img.save_dataframe(fig=fig, filename=filepath), content_type=mimetypes.guess_type(filepath)) response['Content-Disposition'] = "attachment; filename=%s" % pngfilename return response -
How to fix issue saving form to django database?
So I have a form you can fill from the webpage which I want to save to my django database to create a new object when submitted instead of adding it in admin. I've tried it and the system works except for one thing, saving it, the function starts as I've managed to switch pages from that function when clicking submit but the object isnt found in the database after so I guess the saving is the only issue. Here is my views.py : def uploadform(request): if request.method == 'POST': name = request.POST['name'] details = request.POST['details'] littype = request.POST['littype'] image = request.POST['image'] new_object = PostForm.objects.create(name=name, details=details, littype=littype, image=image) new_object.save() return render(request, 'uploadform.html', {}) Here is my models.py (The one to save the form is the "PostForm" class) : from email.mime import image from django.db import models from django.db.models import Model # Create your models here. class info(models.Model): name = models.CharField(max_length=100) details = models.CharField(max_length=10000) littype = models.CharField(default="Type of Litterature", blank=True, max_length=100) image = models.ImageField(default=None, blank=True, upload_to='app/files/covers') class PostForm(models.Model): name = models.CharField(max_length=200) details = models.TextField() littype = models.TextField() image = models.FileField(upload_to='app/files/') def __str__(self): return self.name Here is my html page : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link type="text/css" … -
How can I add to my investment balance with django
With the code below, I'm attempting to add the amount to my current balance but I am getting a 'QuerySet' object has no attribute 'balance' def create_investment_view(request): if request.method == "POST": form = InvestmentForm(request.POST) if form.is_valid(): amount = form.cleaned_data['amount'] user_investment = Investment.objects.all() user_investment = user_investment.balance + amount else: form = InvestmentForm() context = { 'form':form, } return render (request, 'create-investment.html', context) class Investment(models.Model): balance = models.IntegerField() class InvestmentForm(forms.Form): amount = forms.IntegerField(widget=forms.TextInput(attrs={'required':True, 'max_length':80, 'class' : 'form-control', 'placeholder': ' 1,000,000'}), label=_("Amount to deposit (Ksh.)"), error_messages={ 'invalid': _("This value must contain only numbers.") })``` -
react native - django api jwt - HTTP Fetch fails with "TypeError: Network request failed"
im trying to connect my react native app to django. i am using JWT. im trying to send a post method to my api but I get "TypeError: Network request failed" => Resolved every time i press the sign in button. i am using a real android device. im new to react so it is been very hard to solve this problem! can anybody help me pls? i already try all methods above but none seem to work enter image description here enter image description here.stack.imgur.com/70KY9.png -
Django: Field 'id' expected a number but got <Video: Introduction>
i am trying to get the id of a Video, but it keeps showing this error Field 'id' expected a number but got <Video: Introduction>. How do i get to add the number that is expected and not the string. views.py def mark_lesson_done(request, course_slug, video_id): user = request.user profile = Profile.objects.get(user=user) course = Course.objects.get(slug=course_slug) video = Video.objects.get(id=video_id) complete_lesson = False if not profile.completed_lessons.get(id=video).id().exists(): profile.completed_lessons.add(videos) messages(request, f'Lesson Completed!') complete_lesson = True return HttpResponseRedirect(reverse('course:course-content', args=[course_slug])) -
Django - How set headers for external resources?
At my Django application, I want to display an image from an external web server. This web server only returns the image if an Authorization token (JWT) is set in the request header. At my Django template, I do: <img src="{{ blabla.cover_url }}"> Where cover_url is a model function, which looks like this at the moment: def cover_url(self, *args, **kwargs): jwt_payload = jwt_payload_handler(get_request().user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) cover_url = "https://cdn.mydomain.com/Images/123456789.jpg" My question now is how I return the cover_url with the Authorization header set? -
Login Failed Error Message Django Based Views
I have a project made in django based view. I need to show an error message when the user enters the wrong password, but in every forum I've seen so far there is a suggestion to use a 'Form'. There is no way to show error message with the project done this way? view.py: def login(request): if request.method == "GET": return render(request, 'users/login.html') else: Email = request.POST.get('Email') Senha = request.POST.get('Senha') user = authenticate(username=Email, password=Senha) if user: loginDjango(request, user) return render(request, 'convite/cadastro_convite.html') else: return redirect('login') html: <div class="col-sm-12 col-md-7 login-dir"> <h2 class="login-titulo">Faça seu login!</h2> <form class="login-form" action="{% url 'login'%}" method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="log-email" aria-describedby="emailHelp" name="Email" placeholder="Email"> </div> <div class="form-group"> <input type="password" class="form-control" id="log-senha" name="Senha" placeholder="Senha"> </div> <button href="/Exemplo" type="submit" class="btn btn-primary login-btn_dir"><i class="fa-solid fa-right-to-bracket"></i> Acessar</button> </form> </div> model: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): NomeUsuario = models.TextField(blank=True) Endereco = models.TextField(blank=True) Celular = models.TextField(blank=True) Cidade = models.TextField(blank=True) Estado = models.TextField(blank=True) Cep = models.TextField(blank=True) Bairro = models.TextField(blank=True) -
suggestion AWS vs Heroku
hello I am having an app with django I deployed to heroku, I am using RDS, and now I am thinking which one is better for me heroku or AWS. my questions also, the app is running slow since I am using redis and everything in heroku for free, how can I make my django app fast. -
E1101: Module 'ldap' has no 'OPT_DEBUG_LEVEL' member (no-member)
I have the following code in my settings.py of my Django application: AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 0, ldap.OPT_REFERRALS: 0, } When I run pylint, I get: E1101: Module 'ldap' has no 'OPT_DEBUG_LEVEL' member (no-member) E1101: Module 'ldap' has no 'OPT_REFERRALS' member (no-member) Why is that? I see in multiple places online those those two flags exist. So why? Also tried: > print("OPT_REFERRALS" in dir(ldap)) True So why do I get this warning? -
Password reset using graphene-django?
In our on going project we are migrating all our views from django to react using graphene. Originally, we used the built in django authentication system for user registration, login and password reset. To migrate the login view, we used authenticate and login from django.contrib.auth which worked great. But now we are stuck on the password reset view. We cannot find a way to send the password reset email. Are there any built in functions like the ones mentioned before that we could use? I checked the following project https://github.com/PedroBern/django-graphql-auth, but it seems abandoned, so I would like to avoid it. -
Losing data in db.sqlite3 when deploying django project to heroku
Whenever I make updates to my website I lose all data that has been added to my models. For example my models include users and service_calls and when I push a deploy it overwrites my db.sqlite3 file and I'm back to just my superuser being the only user and 0 service calls in my database. How can I push an update without having my db.sqlite3 file overwritten? Is that possible or do I need to have my local db.sqlite3 file updated before deploying and if so how would I go about that. Thanks in advance -
Django - How to process authorization headers?
At my Django application, I display pictures which are stored on an external web server. To make the picture accessible, the client needs to call the resource with an attached authorization Barer token in the request header, like this: Authorization: Bearer eyJ0eXAiO... To get the actual URL to the picture, I have a function in my models.py which I can simply call at my template.html: def cover_url(self): cover_url = self.libera_backend.endpoint + '/' + self.libera_backend.assets_bucket + '/' + self.cover_path return cover_url As I have to generate a JWT token to make the resource accessible, I have to do something like this: jwt_payload = jwt_payload_handler(user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) Where I'm not sure how to implement this. Does it have to be part of a template tag, or is there any way to find out what user calls def cover_url? If so, how can I add the Authorization header here? -
Dynamic SECRET_KEY in Django disadvantages
I just started learning Django and I'm wondering what the drawbacks of using a randomly generated SECRET-KEY would be. So far I've started with using this code... from pathlib import Path import random, string Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ Randomized security key size = 100 SECRET_KEY = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase string.punctuation + string.hexdigits + string.digits, k = size)) For now, this seems to work well for a simple blog that I made but I'm wondering what drawbacks this might have in other uses and if there are better ways of making the key secure. Thanks in advance! -
python django whatsapp bot to let others to signup to DBs without using html
Creating a Django project django-admin startproject messages . django-admin startapp whatsapp python manage.py migrate python manage.py runserver Open the settings.py file from the messages directory INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whatsapp.apps.WhatsappConfig', # ← new item ] Open the views.py from the whatsapp subdirectory. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def message(self): return HttpResponse('Hello!') To make this endpoint accessible through the web application, a URL needs to be assigned to it. Open the urls.py file from the messages directory and add a new entry to the urlpatterns list as shown below: from django.contrib import admin from django.urls import path from whatsapp import views # ← new import urlpatterns = [ path('admin/', admin.site.urls), path('message', views.message), # ← new item ] Receiving WhatsApp messages The next step is to update the logic inside the message() endpoint to extract the information about the incoming message. Replace the contents of the views.py file in the whatsapp subdirectory with the following: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def message(request): user = request.POST.get('From') message = request.POST.get('Body') print(f'{user} says {message}') return HttpResponse('Hello!') Sending a response Update the views.py file in the whatsapp subdirectory one last time with the …