Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add type hints on django initialization
I have user as foreign key user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) But when I access user through related object I can't see auto-completion for user attributes. F.e Unresolved attribute reference 'public_name' for class 'ForeignKey' How can I add type hint that it is actually User model? In django app initialization I am overriding serializers.ModelSerializer with my custom serializer. And overriding is taking place in app/init.py module. Problem is I can't see some attributes that exists in CustomModelSerializer. Pycharm is thinking it is ModelSerializer from drf. Is it possible to hint somewhere that it is CustomModelSerializer. (PS: I know I can import CustomModelSerializer everwhere, but it is a big project and I was looking for solutions with adding type hint or making Pycharm recognize overriding) -
Ignore options which already given in django
I created a django forms class StudentFamilyForm(forms.ModelForm): class Meta: model = StudentFamily fields = '__all__' exclude = ['created', 'is_deleted'] it is used to create family details for a student. in the StudentFamily model, there is a student one-to-one field. If i've created a family entry for a student, I don't want to see it in the select input. so how to do that? -
How to filter the dates from datetime field in django
views.py import datetime from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.utils import timezone import pytz roles = "" get_records_by_date = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) global get_records_by_date get_records_by_date = Scrapper.objects.all().filter(start_time=f_date,end_time=t_date) print(get_records_by_date) else: global roles roles = Scrapper.objects.all() return render(request, "home.html",{"scrappers": roles}) return render(request, "home.html", {"scrappers": get_records_by_date}) models.py from django.db import models from django.db import connections # Create your models here. from django.utils import timezone class Scrapper(models.Model): scrapper_id = models.IntegerField(primary_key=True) scrapper_jobs_log_id = models.IntegerField() external_job_source_id = models.IntegerField() start_time = models.DateField(default=True) end_time = models.DateField(default=True) scrapper_status = models.IntegerField() processed_records = models.IntegerField() new_records = models.IntegerField() skipped_records = models.IntegerField() error_records = models.IntegerField() class Meta: db_table = "scrapper_job_logs" Database structure I post f_date = 2022-11-24 00:00:00 , t_date = 2022-11-24 00:00:00 . I need to get the row start_time and end_time which has dates 2022-11-24. Is there any solution how to filter datas from datetime field. If I pass f_date and t_date my <QuerySet []> is empty. -
How to configure webmail tools in django?
I configured mail for my django project. It worked as usual perfectly for gmail. But when I used this configuration for webmail it won't work. Someone pleas help me how to setup webmail configuration for django proejct. I try for several time but it gives me error. I expect to send mail using my webmail. -
Is there a way to update a webpage after it is loaded in django without doing a periodic check?
I'm trying to do something similar to this question. Basically, I want to have the html page being updated once new information arrives at the server. The information won't come periodically, but rather in bursts. Is there a way for me to trigger the javascript/htmx function via django or is it that I have to do the per-X-seconds check on the browser side? All solutions that I've found are using the periodic check in a script which appears a bit surprising to me. -
DRF How to serialize model with media and foreign key field Django
I have django model containing filefield and imagefield class Audios(models.Model): name = models.CharField(max_length = 29,blank=True,null=True) duration = models.DecimalField(default=0.0,max_digits=5, decimal_places=2) language = models.ForeignKey(Language,on_delete=models.PROTECT,related_name='audios') zartist = models.ForeignKey(Artist,on_delete=models.CASCADE,related_name='myaudios') annotation = models.CharField(max_length=50) avatar = models.ImageField(upload_to=saveAudioImage, validators=[FileExtensionValidator(allowed_extensions=["jpg","png","jpeg"])], null=True, blank=True) audio = models.FileField(upload_to=saveAudioFile, validators=[FileExtensionValidator(allowed_extensions=["mp3","acc"])], null=True, blank=True) streamed = models.PositiveIntegerField(default=0) rating = models.DecimalField(default=0.0,max_digits=2, decimal_places=1) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.name and zartist field is a foreign key to another artist model and i wrote a serializer for it class AudiSerializer(serializers.ModelSerializer): class Meta: model = Audios fields = ('id','name','language','zartist','annotation','avatar','audio') and a view class AudioUpload(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request,format=None): print(request.data) print("\n\n") serializer = AudiSerializer(data=request.data) if serializer.is_valid(): serializer.save return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but when i test it with httpie it doesn't save it to the database and the filefield and imagefield are not properly handled. Any one help please ? -
Forbidden (403) CSRF verification failed. Request aborted. in django
I am new to Django and learning using templates. When I properly use csrf token in my sign up template form, submitting form stil makes the csrf token missing error. Following is my signup.html code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign In</title> </head> <body> <form action="/" method="post"> {% csrf_token %} <label for="">Username</label> <input type="text" name="username"> <br> <label for="">First Name</label> <input type="text" name="fname"> <br> <label for="">Last Name</label> <input type="text" name="lname"> <br> <label for="">email</label> <input type="email" name="email"> <br> <label for="">Password</label> <input type="password" name="pass1"> <br> <label for="">Confirm Password</label> <input type="password" name="pass1"> <br> <br> <button>Submit</button> </form> </body> </html> I guess there is something missing in TEMPLATES section of settings.py. Here is the section os settings.py . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here is the screenshot of error. And here is the screenshot of my directories format. Login is main project and authenticate is app -
If I have multilable admin register through API in django , How do I show the users of each admin?
I'm using DRF for make API , and I have API for register Admin. Admins have regitser users ( teacher , student). I won't to display users ( teacher , student) for each Admin when login in (Frontend , Django-Admin) -
Django shows Service Unavailable page
My Django app works fine in my local computer, then I deployed the code to an EC2 instance with Ubuntu and Apache. All was working fine, I was able to see the page, but when i setup the DB connection with the same DB info (postgres database) that I used locally the App started showing a Service Unavailable page, when I remove the DB connection info from the settings.py file work fine, when i put the DB connect fail. The connection with the DB is ok because I use the Django commands to create a super user and was created correctly. Setup DB connection to postgres from DJango app -
Is it possible to receive message from one web socket even though the web socket connection is closed?
I am learning Django Channels and trying to implement WhatsApp like feature. I want to update the contact box of a particular user with latest message even though that particular WebSocket connection is not open I am using Django channels and each window ( mowdin & jack ) represents a individual web socket connection with that user. When the connection is open with mowdin and mowdin sends a message, I'm able to update that message in the contact box of mowdin. ( As highlighted in image above). consumers.py class PersonalChatConsumer(AsyncWebsocketConsumer): async def connect(self): print('Line 8 Connect',self.scope['user']) self.my_id = self.scope['user'].id self.other_user_id = self.scope['url_route']['kwargs']['id'] if int(self.my_id) > int(self.other_user_id): self.room_name = f'{self.my_id}-{self.other_user_id}' else: self.room_name = f'{self.other_user_id}-{self.my_id}' self.room_group_name = 'chat_%s' %self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) message = data['message'] sender_username = data['sender'] group = await database_sync_to_async(Group.objects.get)(name=self.room_group_name) receiving_user = await database_sync_to_async(User.objects.get)(id=self.other_user_id) group.last_message = message group.sent_by = self.scope['user'].username group.received_by = receiving_user.username await database_sync_to_async(group.save)() chat = Chat(message=message, group=group, user=self.scope['user']) await self.channel_layer.group_send( self.room_group_name, { 'type':'chat.message', 'message': message, 'sender':sender_username, 'group':self.room_group_name, } ) async def chat_message(self, event): print('Line 52 Sending Message',self.scope['user'], event) message = event['message'] username = event['sender'] group = event['group'] … -
Django Rest How to show all related foreignkey object?
I have an blog website and my visitors can also comment on my blog posts. Each blog post have multiple comment and I want to show those comment under my each single blog post. Assume Blog1 have 10 comment so all 10 comment will be show under Blog1 here is my code: models.py class Blog(models.Model): blog_title = models.CharField(max_length=200, unique=True) class Comment(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) comment = models.TextField() blog = models.ForeignKey(Blog, on_delete=models.CASCADE) Serializer.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog exclude = ("author", "blog_is_published") lookup_field = 'blog_slug' extra_kwargs = { 'url': {'lookup_field': 'blog_slug'} } views.py: class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' -
DRF pagination issue in APIView
I want to implement LimitOffsetPagination in my APIView which was successful but the url is required to be appended with ?limit=<int>. Something like this: But I do not want to manually add that endpoint. So I tried creating a new pagination.py file: But now I am not getting the pagination prompt for navigation to next post like before. I think return needs to be altered? -
Display PDF in django
im new in django programming and i need to display a pdf file in a browser, but i cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but i cannot show. my urls.py: urlpatterns = [ path('uploadfile/', views.uploadFile, name="uploadFile"), path('verPDF/<idtermsCondition>', views.verPDF, name='verPDF'), ] my models.py: class termsCondition(models.Model): title = models.CharField(max_length=20, verbose_name="title") uploadPDF = models.FileField( upload_to="PDF/", null=True, blank=True) dateTimeUploaded = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField( auto_now=False, verbose_name="Fecha eliminacion", blank=True, null=True) class Meta: verbose_name = "termsCondition" verbose_name_plural = "termsConditions" my views.py: def uploadFile(request): user = request.user if user.is_authenticated: if user.is_admin: if request.method == "POST": # Fetching the form data fileTitle = request.POST["fileTitle"] loadPDF = request.FILES["uploadPDF"] # Saving the information in the database termscondition = termsCondition.objects.create( title=fileTitle, uploadPDF=loadPDF ) termscondition.save() else: listfiles = termsCondition.objects.all()[:1].get() return render(request, 'subirTerminos.html', context={ "files": listfiles }) else: messages.add_message(request=request, level=messages.SUCCESS, message="No tiene suficientes permisos para ingresar a esta página") return redirect('customer') else: return redirect('login2') def verPDF(request, idtermsCondition): user = request.user if user.is_authenticated(): if user.is_admin: getPDF = termsCondition.objects.get(pk=idtermsCondition) seePDF = {'PDF': getPDF.uploadPDF} print(seePDF) return render(request, 'subirTerminos.html', {'termsCondition': getPDF, 'uploadPDF': getPDF.uploadPDF}) else: messages.error(request, 'Do not have permission') else: return redirect('login2') my html: <div> <iframe id="verPDF" src="media/PDF/{{ uploadPDF.url }}" style="width:800px; height:800px;"></iframe> </div> … -
What is the application.properties alternative in Django?
I am beginner in web development. I have previously done a few small projects using Quarkus. I am trying to do a project in Django. I have some properties to set for my application. I had done that in the application.properties file in Quarkus. Is there any similar way to do so in Django? -
I want to create new model with name query but due to this issue I can't do that. this customer model had been created and working properly
from django.db import models class Customer(models.Model): fullname=models.CharField(blank=False,max_length=100) username=models.CharField(blank=False,max_length=100) email=models.CharField(blank=False,max_length=100) password=models.CharField(blank=False,max_length=100) cpassword=models.CharField(blank=False,max_length=100) phone=models.CharField(blank=False,max_length=100) address=models.CharField(blank=False,max_length=256) city=models.CharField(blank=False,max_length=256) def register(self): self.save() I want to create new model but due to this issue I can't do that. this customer model had been created for few days before. its properly working but new model can't create. I tried to create same model in new project, just by copy and paste so the new model had been created but the same model is not working in this project. this error occurred in terminal. python manage.py makemigrations It is impossible to change a nullable field 'email' on customer to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. 3) Quit and manually define a default value in models.py. -
django url specific to keyword without adding page number for first page
I have more list in specfic page https://www.hiicanhelpyou.com/india/best-top-doorstep-online-nearby/ro-water-purifier-service-repair-install-near-me-chennai in that i have added ten agent but i have more agent next page https://www.hiicanhelpyou.com/india/best-top-doorstep-online-nearby/ro-water-purifier-service-repair-install-near-me-chennai-1 . The first page always specific to keyword and next pageonwards it should append the page number . How to do SEO URL ? first page it should not add the page number so that keyword showup properly first page https://www.hiicanhelpyou.com/india/best-top-doorstep-online-nearby/ro-water-purifier-service-repair-install-near-me-chennai second page with appending page number https://www.hiicanhelpyou.com/india/best-top-doorstep-online-nearby/ro-water-purifier-service-repair-install-near-me-chennai-1 how to do this seo url in django -
how can i implement python script on html or display python script result on browser?
I am working on a project in python in which i am converting pdf file to text and then extracting keywords from that so i need to display keyword result on browser where i can take pdf as input and display keywords I tried using django but problem is that i am not able to take pdf as input but it is displaying output if taking text as input. code: from django.shortcuts import render import requests def button(request): return render(request,'home.html') def output(request): data="hjhjdhj" return render(request,'home.html',{'data':data}) -
Django - How to Filter when getting values_list?
I have an application that has multiple objects related to one Model. When I try and get data to display in a form (in order to update) it is either giving an error or not displaying any of the data. To illustrate the layout we have OBJECT(ID): Project(1): Issue(1) Issue(42) Issue(66) Issue(97) What is happening above is I have multiple issues related to the project. I am getting the IDs from the Issues within the Project by using the following queryset. get_issue_id = get_object_or_404(DevProjects, pk=pk) issue_id = DevIssues.objects.filter(project=get_issue_id).values_list('id', flat=True) Which returns: <QuerySet [1, 42, 66, 97]> I am trying to use the following queryset to filter the Issue ID from the values_list, in order to set the Instance= (for forms) to the queryset to only get the data and display that data in the form for the issues ID from the Project PK that I am requesting. update_issue = DevIssues.objects.filter(id=issue_id) Below is my current view.py get_issue_id = get_object_or_404(DevProjects, pk=pk) issue_id = DevIssues.objects.filter(project=get_issue_id).values_list('id', flat=True) update_issue = DevIssues.objects.filter(id=issue_id) update_issue_form = UpdateProjectIssues(instance=update_issue) if request.method == 'POST' and 'updateissue' in request.POST: update_issue_form = UpdateProjectIssues(request.POST, instance=update_issue) if update_issue_form.is_valid(): update_issue_form.save() And this is the current error I am facing: 'QuerySet' object has no attribute '_meta' How … -
using django, i want to show the user options to pick from with 'select' and a TextChoices model
in my html template i have a select box where the user chooses the desired size of clothing like this <select> <option> Small </option> <option> Medium </option> <option> Large </option> </select> i want to display the options for the user to see. because i want to save the input in the database, to grab it, i was thinking of doing this: models.py class Product(models.Model): ... class Size(models.TextChoices): SMALL = 'S' MEDIUM = 'M' LARGE = 'L' size = models.CharField(max_length=3, choices=Size.choices, default=Size.LARGE) html <select> {% for size in product.size %} <option value="" name="{{ size }}"> {{ size }} </option> {% endfor %} </select> views.py def product(request, slug): product = get_object_or_404(Product, slug=slug) return render(request, 'product/product.html', {'product': product}) but i only get to display one value, which is the default value LARGE in my admin page, the 'Sizes' dropdown select for the product is showing perfectly with all 3 different values for the admin to pick did i choose the wrong method with 'TextChoices'? the html is not correct? am i missing something in views.py? all of the above? -
Multi-tenants == Multi-sites?
Is tenancyforlaravel the equivalent to django's django-multisite + ALLOWED_HOSTS ? I created a bunch of related websites pointing the same Django app on my shared server. I am looking for the Laravel equivalent for a new project using the similar methodologies. Laravel only because there are many built-in solutions for SaaS. But I can't seem to relate the word multi-tenancy with multi-sites. Are both ditto ? (WordPress has a similar (same?) thing called Multisite) -
HTMX hx-target moves content down instead of replacing it in designated id
I am having the problem where my hx-target doesn't seem to be replacing the content where the target I point to. I'm using a a base html file that has a div with an id of requestcontent in it. All of my links, form actions and hx actions that I'm using point to this div for replacement. My initial access from an item on the menu sidebar works fine and gives results as shown here: Even when I click on the "Add bill" button the page renders correctly: However if I press close or save on this page when I return to the original page the top of the add page is still present: This is true from both my add and delete pages. The initial page that starts out the entire process is in billlist.html <div class="container shadow min-vh-100 py-2"> {% include 'acctsite/partials/messages.html' %} <h2>Accounts Payable / Bills Listing</h2> <div class="row" align="right"> <div class="col-10"></div> <div class="col-2 pb-1"> <button class="btn btn-primary btn-sm" hx-trigger="click" hx-get="{% url 'expadd' %}" hx-target="#requestcontent"> Add bill </button> </div> </div> <div class="row"> <div class="col h5">Date</div> <div class="col h5">Vendor</div> <div class="col h5">Description</div> <div class="col h5">Amount</div> <div class="col h5">Paid Info</div> <div class="col-1"></div> <div class="col-1"></div> <div class="col-1"></div> </div> <div class="row"> … -
How to Change django-autocomplete-light input box styling?
I have gotten the autocomplete to work with my Database and my front end, but the input widget looks slightly off. Is there a way to change the styling for the input? Also, is there a way to remove the initial dropdown, so after you click once, you can start typing and suggestions will appear? I am using the ListSelect2 Widget. The Select2Multiple looks like more of what I need but I want input to be only one. Current Widget Pre-Input Current Widget During Input Current Widget After Selection Desired Look (Select2Multiple Widget) I would appreciate any suggestions! -
Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them?
I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users will them receive an email with their credential. So that they can login with through the LoginAPIView. views.py class LoginView(APIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ["email", "password"] def validate(self, attrs): email = attrs.get("email") password = attrs.get("password") user = auth.authenticate(username=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contain admin") return {"email": user.email} models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email or not password: raise ValueError("Users must have both email and password") email = self.normalize_email(email).lower() user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser … -
Django - I can no longer save form with dynamic formset
I would like your help with a problem that I can't solve or find a solution on the internet. I have a user registration form that was working correctly before. But feel the need to insert a dynamic formset. However, now with the formset when filling out and sending the form, no data is saved in the database and instead of being redirected to a list of users, I am redirected to the form again already filled with the data that failed to be sent and without showing any kind of error. -=-=-=-=-=-=--=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Olá desenvolvedores, Gostaria da ajuda de vocês para um problema que não consigo resolver ou não encontro solução na internet. Eu tenho um formulário de registro de usuário que estava funcionando corretamente antes. Mas sinto a necessidade de inserir um formset dinâmico. Porém, agora com o formset ao preencher e enviar o formulário, nenhum dado é salvo no banco de dados e ao invés de ser redirecionado para uma lista de usuários, sou redirecionado novamente para o formulário já preenchido com os dados que não conseguiram enviar e sem apresentar nenhum tipo de erro. -=-=-=-=-=-=--=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- models.py ` class Contato(models.Model): tipo = ( ('Residencial', 'Residencial'), ('Comercial', 'Comercial'), ('Celular', … -
Django forms: cannot access local variable 'form' where it is not associated with a value
Condition: I have a model, created an empty table in the database, and I'm trying to create an html form that will fill in the fields of the corresponding columns of the table. And here's what my app looks like: models.py from django.db import models class Cities(models.Model): city = models.CharField(max_length=100) def __str__(self): return self.state class Routes(models.Model): route_name = models.CharField(max_length=50, default='Route') lvl = models.IntegerField(default=0) about = models.TextField(max_length=1500) total_distance = models.IntegerField(default=0) city = models.ForeignKey(Cities, on_delete=models.CASCADE) forms.py from django.forms import ModelForm from .models import Routes class RouteForm(ModelForm): class Meta: model = Routes fields = '__all__' views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from routes_form.forms import RouteForm def getAbout(request): if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return render(request, 'routes_form/form_page.html', {'form': form}) form.html <form method="post"> {% csrf_token %} <legend> <h2>About</h2> </legend> {{ form }} <input type="text" placeholder="Write more about the route: about waypoints, points of interest and warnings."> <input type="submit" value="Send route"> </form> I have already tried to do everything as indicated in the Django Forms documentation. But still something is wrong. Even at the moment of starting the server, it writes an error: cannot access local variable 'form' where it is not associated with a value