Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
NameError: name 'Message' is not defined (Django - Python3)
So, I'm creating an app in Django, and I can't seem to reference a class in the same file. My models.py: from django.db import models from django.core.validators import MinLengthValidator from users.models import User from .models import Message class Group(models.Model): group_id = models.IntegerField(unique=True) group_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) #owner = models.ForeignKey(User) creation_date = models.DateField(auto_now=True) max_users = models.IntegerField(validators=[MinLengthValidator(2)]) members = models.ManyToManyField(User, max_length=max_users) messages = models.ManyToManyField(Message) class Message(models.Model): content = models.CharField(max_=500, validators=[MinLengthValidator(1)]) sent_date = models.DateTimeField(auto_now=True) sender = models.OneToOneField(User) I tried importing from the same module... from .models import Message ...but this results in a circular import. Does anyone know how to resolve this? -
Creating credentials file on server via Dockerfile & Google cloud secret manager
I'm using Google cloud build for CI/CD for my django app, and one requirement I have is to set my GOOGLE_APPLICATION_CREDENTIALS so I can perform authenticated actions in my Docker build. For example, I need to run RUN python manage.py collectstatic --noinput which requires access to my Google cloud storage buckets. I've generated the credentials and it works well when simply including it in my (currently private) repo as a .json file, so it gets pulled into my Docker container with the COPY . . command and setting the env variable with ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json. Ultimately, I want to grab the credential value from secret manager and create the credentials file during the build stage, so I can completely remove the credentials from the repo. I tried doing this with editing cloudbuild.yaml (referencing this doc) with various implementations of the availableSecrets config, $$SECRET syntax, and build-args in the docker build command and trying to access in Dockerfile with ARG GOOGLE_BUILD_CREDS RUN echo "$GOOGLE_BUILD_CREDS" >> credentials.json ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json with no success. If someone could advise me how to implement this in my cloudbuild.yaml and Dockerfile if its possible, or if there's another better solution altogether, would be much appreciated. This is the … -
Filter using @property field django
I would like to filter based on @property field to generate a queryset. My model as below. `class PrHW(models.Model): po_duration = models.IntegerField(null=True) provision_start_date = models.DateField(null=True, blank=True) description = models.TextField(blank=True, null=True) @property def provision_end_date(self): provision_end_date = self.provision_start_date + relativedelta(months=self.po_duration) return provision_end_date` Since "provision_end_date" is a calculated field, it is not part of PrHW.objects.all() and hence I am unable create queryset using it as a filter option (eg, generate list of PrHW objects where provision_end_date is less than today - This generates error that "provision_end_date" is not a valid field; which was expected). I tried creating custom model manager but still I am unable to access either the @property field or other fields such as "provision_start_date" in the custom manager. May be this would be straingt forward but even after several searches, unable to get the hang of it. Any help is appreciated. -
Querying multiple schemas with django tenants
I'm writing this question because I have doubts about how to implement a scenario that we had not foreseen for my django developed application. Basically what I need is a way to allow some types of users, depending on their role, could access data that is in multiple schemas. So the approach that I had thought of was to create relationships between the "tenants", which define the database schemes, and detecting which of them a certain user belongs to, to be able to query all the schemes that are related to it. In the same way, this has some drawbacks, since this solution would require a lot of additional programming and concatenating querysets or working by adding the responses of the serialized data of each queryset of the aforementioned schemas could be inefficient. Thanks in advance. -
Django Rest how to show list of comment which belongs only from related Blog and Author?
Assume Author Jhone write an Blog which title is "This blog written by author Jhone" and Author Joe write an Blog "This blog written by author Joe" . Jhone blog received 20 comments and Joe blog received 10 comments. When Jhone will be login his account he can only able to see comments those belongs from his blog post and same will be for Joe. Here I tried this query Comment.objects.all().filter(blog__author_id=request.user.id) but still now everyone can see each others blog comments from my api url. here is my code: @api_view(['POST', 'GET']) def comment_api(request): if request.method == 'POST': serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'GET': comment = Comment.objects.all().filter(blog__author_id=request.user.id) serializer = CommentSerializer(comment, many=True) return Response(serializer.data) serializer.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' models.py class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) 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) -
How can i change django admin to ltr style without change language?
I use Persian language in my django project : LANGUAGE_CODE = 'fa-ir' and I want to change the direction from rtl to ltr without changing the language code. How can I do this? I tried to change this from admin template but I couldn't -
Django – Efficiently fetch recursive categoryi structure
I have a model which looks like this: class Category(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( 'categories.Category', null=True, blank=True, on_delete=models.CASCADE, related_name='categories' ) basically, in the parent field, it references itself. If a parent is set to None, it's the root category. I use it to build a hierarchy of categories. What would be the most efficient way to: fetch all the objects through the hierarchy display them in a template? For some reason, select_related does not seem to lead to performance improvements here. I also found this: How to recursively query in django efficiently? But had a really hard time applying it to my example. Would appreciate any help. Thanks! -
'>' not supported between instances of 'type' and 'datetime.date'
I'm creating a CRUD application that displays activities available on or after today; I'm working through the filtering mechanism on displaying these activities, however I'm having a nightmare trying to only show the activities that are on/after today. I'm getting the below error when I try to use the '>=' operand, however it's giving me the following error: '>' not supported between instances of 'type' and 'datetime.date' Below is my views.py for the comparison: today= date.today() available_activities = Activity.objects.filter(available = True).values() activities = available_activities.filter(date > today).values() activities= available_activities.order_by('date','start_time') Below is a screenshot of the error traceback also, to show the data format for the data in the DB also. -
RegexValidator in Django Models not validating email correctly
I'm making a django form with an email field and using a RegexValidator and want a specific format of of the email but it seems to be not validating the field correctly email = models.EmailField( unique=True, validators=[ RegexValidator( regex=r"^[2][2][a-zA-Z]{3}\d{3}@[nith.ac.in]*", message= "Only freshers with college email addresses are authorised.") ], ) When I am entering the email ending with @nith.ac.in or @nith.acin both are getting accepted while @nith.acin should not get accepted... any sols? -
UNIQUE constraint failed: auth_user.username while trying to register the user in django
I have written following set of code in views.py of my project but when I try to register the user info as an object in the database, above mentioned error arrived views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib import messages from django.shortcuts import redirect, render # Create your views here. def home(request): return render(request, "authentication/index.html") def signin(request): if request.method == "post": username = request.POST['username'] pass1 = request.POST['pass1'] user = authenticate(username = username, password=pass1) if user is not None: login(request, user) fname = user.first_name return render(request, 'authenticate/index.html', {'fname' : fname}) else: messages.error(request, 'Bad credentials') return redirect('home') return render(request, "authentication/signin.html") def signup(request): if request.method == "POST": # username = request.POST.get('username') username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username, email, pass1) ## Error is coming in this line ## myuser.firstname = fname myuser.lastname = lname myuser.save() messages.success(request, 'Your account has been succesfully created.') return redirect('/signin') return render(request, "authentication/signup.html") def signout(request): pass I am trying to make user login system and following error has arrived in views.py of my app. enter image description here -
Graphene Python JSON Query Parameter
i'm trying to make a query passing a list of JSON as parameters but i have no idea how and i couldnt find anywhere else example query { verify(password="aba", rulesList=[{"rule":"minDigit", value:5}, {"rule":"noRepeted", value:0}] { ... } } and the Python Code enter image description here I've tried changing the rulesList type but i couldnt use ObjectTypes inside that list thanks for your time -
Get Old Objects, Update, and then return old objects
I have an APIView that looks like this: class GetNotifications(ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): notifications = Notification.objects.select_related().filter(user=self.request.user).order_by("-created_at") Notification.objects.select_for_update().filter(is_read=False, user=self.request.user).update(is_read=True) return notifications What I'm trying to do is get all notifications that the user has. These include notifications that have been read and that have been not read yet (hence the is_read field). I'd like to return both the is_read and the not is_read notifications.Once those objects are received then an update will happen to change the not read notifications to is read. What this means is that any user who accesses this API through the site will mean that they've read their notifications so we can set is_read=True...however, my current code returns the objects after updating them. I want to return the old objects prior to updating hence me assigning notifications to the old objects before updating. I believe this is due to lazy loading on Django's part. Is there a way/better way to solve this? -
Issue With Nested Comments Using MPTT in Django and Django Rest Framework API - Result In Detail Not Found
I'm trying to create a nested comment system using MPTT but using Django Rest Framework to serialize MPTT tree. I got the nested comments to work - and these comments are added, edited, and deleted by calling Django Rest Framework API endpoints only - not using Django ORM DB calls at all. Unfortunately, there is a bug I couldn't figure out! Although the comments are added, edited, and deleted fine - but when a seventh or eighth comment is nested - suddenly the first-in comment or first-in nested comments would become [detail: Not found.] - meaning it will return an empty result or throw an unknown validation error somewhere which I couldn't figure out why. This results in when clicking on edit or delete the buggy comments becoming impossible - but the GET part is fine since these buggy comments do show up in the comment section (or should I say the list part returns fine). The image I'll attach will show that when I entered comment ggggg, the comment aaaa and bbbb will throw errors when trying to edit or delete them. If I delete comment gggg, comment hhhh will also be deleted (as CASCADE was enabled) - and … -
'Django OperationalError: no such table: users_portal' in Django
I'm creating a webapp and I am attempting to access the 'Portal' page (created by myself) in the User's section on the in-built Django Admin backend page. However, when I try to access this page, the following error is outputted onto the terminal: django.db.utils.OperationalError: no such table: users_portal This error has stopped my from accessing the 'Portal' page and therefore, has hindered me from progressing with my webapp. Any suggestions on how to get rid of this error? Would be highly grateful and open to all suggestions! I have already tried to make the migrations, and have them migrated. I have also attempted the --fake migrations and unfortunately none of them have yielded to the result I expected.