Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Django form is not displaying on the HTML template
This is the code for the form, model, and template. That refused to show. This project is with urgency to be delivered before next week. I would love if, y'all help me here thanks. this is the forms.py code from voterRegistration.models import voterReg from django import forms from django.forms import ModelForm from .models import voterReg class VoterRegForm(ModelForm): firstname = forms.CharField(initial='First Name', max_length=20) lastname = forms.CharField(initial='Last Name', max_length=30) email = forms.EmailField(help_text='Enter your Email Address') phonenumber = forms.IntegerField() Address = forms.CharField(max_length=70) gender = forms.CheckboxInput() dateofbirth = forms.DateField() state = forms.CharField(max_length=50) local = forms.CharField(max_length=50) occupation = forms.CharField(max_length=20) passport = forms.ImageField() class Meta: model = voterReg fields = ("firstname", "lastname","email", "phonenumber", "Address", "gender", "dateofbirth", "state", "local", "occupation", "passport") def save(self, commit=True): voterReg = super(VoterRegForm, self).save(commit=False) voterReg.firstname = self.cleaned_data["firstname"] voterReg.lastname = self.cleaned_data["lastname"] voterReg.email = self.cleaned_data["email"] voterReg.phonenumber = self.cleaned_data["phone number"] voterReg.Address = self.cleaned_data["Address"] voterReg.gender = self.cleaned_data["gender"] voterReg.dateofbirth = self.cleaned_data["dateofbirth"] voterReg.state = self.cleaned_data["state"] voterReg.local = self.cleaned_data["local"] voterReg.occupation = self.cleaned_data["occupation"] voterReg.passport = self.cleaned_data["passport"] if commit: voterReg.save() return voterReg this is the voterRegistration html template <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width; initial-scale=1; shrink-to-fit=no;"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>e-NEC || Voter Registration page</title> <!--load static--> {% load static %} <!--link to bootstrap and the rest--> <link href="{% static … -
Method for Changing django template to PDF that having either bootstrap or css or both
I have tried via weasyprint , pdfkit but showing errors even though if all errors removed, its showing very unsimilar output as expected .. Can anyone tell me what to do in changing django template that contains either Bootstrap or Css Or both in Django Thanks for any help. -
Django CheckConstraint With IntegrityError
I have a constraint that I'd like to add in my Django Model. I thought the CheckConstraint method would help to catch the error when the input does not meet the constraint. However, when I saved the model with an invalid input, e.g. percentage = 101, an error page was shown with IntegrityError. Does anyone here know how to properly use this method to validate the input? class Meta: constraints = [ models.CheckConstraint( check=Q(percentage__gte=1) & Q(percentage__lte=100), name="Please enter a valid percentage", ) ] -
django select_related().values() not returning all fields from 2 tables
I have 2 tables, one child (Car) and the other parent (Dealership). I'm using the orm query Car.objects.all().select_related('dealership').values() to perform a left join which would give me all the fields from both cars and their related dealerships but that's not happening as I'm only able to get all the fields from the Car model. class Dealership(models.Model): ... class Car(models.Model): dealership = models.ForeignKey(Dealership, on_delete=models.CASCADE, null=True, default=None) ... I read it in a different question that with .values() I'll have to explicitly mention all the required fields but there are just too many fields to enter manually. Is there a cleaner solution to this? -
How to redirect user to the desired page after login using LoginRequiredMixin in django?
I have created a mini project called ToDoList App. I have used class based views for create, update and delete functions. There is MyTasks icon on navbar. What I want? If the user is not logged in and he clicks on MyTasks icon, he should be redirected to the login page and after login to MyTasks page. I have used LOGIN_REDIRECT_URL = 'home' and LOGIN_URL='login' in settings.py file If I write LOGIN_REDIRECT_URL = 'task_list', it is working fine else not. Below is the code from views.py file: class TaskListView(LoginRequiredMixin, ListView): """List of all tasks.""" model = MyTasks context_object_name = 'tasks' template_name = 'task_list.html' This is from urls.py file: path('tasks/', views.TaskListView.as_view(), name="task_list"), I have used the attribute redirect_field_name='next' and tried to override dispatch method in the above class, still it is not working. The output I am getting is, after login, it is getting redirected to homepage instead of my tasks page. Any help is much appreciated. Below is the screenshot from the terminal: [1]: https://i.stack.imgur.com/KtsIG.png -
Object of type Token is not JSON serializable
views.py this is my views.py. when I wanna login I get an error. class AuthAPIView(APIView): def post(self, request, format=None): data = request.data username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) token = Token.objects.get(user=user) return Response(token) else: return Response(status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_404_NOT_FOUND) I have created a token for each user when registering. and now when I wanna authenticate I get an error. I wanna get my Token instead. -
How to get column names and data types from an SQL query without creating view
I am facing a challenge in Python/Django application. Can anyone help me to find the column names and their data type from a custom sql query. Example Query: SELECT Customers.CustomerName, Customers.Address, Orders.OrderID, Orders.OrderAmount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName; I need the result as follows:- {"CustomerName":"Varchar","Address":"Text","OrderID":"Int","OrderAmount":"Decimal"} -
Make a form that pulls choices from table in DB and then allows user to change to different foreign keys
So I have a user model with the following columns: username = models.CharField(db_column='Username',max_length=32,unique=True) email = models.CharField(db_column='Email',max_length=255) password = models.CharField(db_column='Password',max_length=128) prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True) I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms. It can't be a static list cause it has to always have every available Prosthodontist as they get added. Just for show this is what I have so far along the lines of the form: class ChangeProsthodontistForm(forms.ModelForm): class Meta: model = User fields = ('prosthodontist',) prosthodontist = forms.ChoiceField( label = "Prosthodontist", widget = forms.Select( attrs={ 'id':'prosthodontist', }, ), choices=() ) Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django. -
How to obtain the field from the parent serializer while serializing a nested json?
Assume this scenario class SerializerA(serializers.ModelSerializer): batch = SerializerB(many=True) class Meta: model = ModelA fields = ['fieldA', 'fieldB'] class SerializerB(serializers.ModelSerializer): class Meta: model = ModelB fields = ['fieldC', 'fieldD'] def validate(self, data): #I want to use fieldA value in this place How to access the field of the JSON one level above the current level while serializing the current level? -
Django Form is Not Visible - Using Model Forms
I'm trying to create a form on my site but the form itself is not visible. I just have a button to 'create post' but the form itself doesn't appear. I've been reading the Django documentation and so far haven't found an answer. I also tried making sure GET requests are explicitly mentioned in my views.py because I saw a post on this site, saying that can sometimes cause this. I'm also using form.as_p in my html file. Not sure what I'm doing wrong. views.py def make_post(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "network/make_post.html", form_for_post) else: form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] new_post = Post.objects.create( text=text, username=request.user, ) print("printing POST:", request.POST) return render(request, "network/make_post.html", { "new_post": new_post, }) def edit_post(request, pk): post = Post.objects.get(id=pk) form = PostForm(instance=post) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return render(request, "network/profile.html", { "form_for_post": form, "post": post, }) else: if request.method == "GET": form = PostForm() form_for_post = {'form': form} return render(request, "network/make_post.html", { "post": post, "form_for_post": form, }) relevant urls.py path('edit_post/<str:pk>/', views.edit_post, name="edit_post"), path("make_post", views.make_post, name="make_post"), html <div class="container"> <div class="add"> <h3> Write Your Post! </h3> <form method="POST" id="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ … -
Using django-autocomplete-light and django-addanother for the same field in a ModelForm
I'm trying to implement django-autocomplete-light and django-addanother for the same field in a ModelForm. I've tried the following: import floppyforms.__future__ as forms from .models import Worker from dal import autocomplete from organizations.models import Hub from django.urls import reverse_lazy from django_addanother.widgets import AddAnotherWidgetWrapper from django.forms import MultiWidget class WorkerCreateForm(forms.ModelForm): class Meta: model = Worker fields = ['display_name', 'hub', 'capacity', 'vehicle', ] widgets = { 'hub': autocomplete.ModelSelect2(url='hubs-autocomplete', attrs{'data-html': True}), 'hub': AddAnotherWidgetWrapper( forms.Select, reverse_lazy('create_hub')) } This will only render the AddAnotherWidgetWrapper obviously. I've tried to use MultiWidget in multiple ways and every time I got a different error (I will not post all my trials and errors since most of them don't make a lot of sense, but if you think I should share them I would be happy to do so). I'm finding it hard to understand how to use MultiWidget since there are no clear examples, and I'm not sure if it's the right solution for my use case. In django-autocomplete-light's documentation, they recommend using django-addanother for adding a model with multiple fields, but there's no explanation on how to implement it. I'd like to know if there's an easy way to use both packages together or if I should write … -
zsh: command not found: django-admin?
I installed django but when i run command django-admin startproject send_email it gives an error showing zsh: command not found: django-admin what can i do please help me. i search same question in google but the answers are not working pathparakh@Paths-MacBook-Air send_email % django-admin startproject send_email zsh: command not found: django-admin pathparakh@Paths-MacBook-Air send_email % python3 Python 3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (3, 2, 5, 'final', 0) >>> -
query one to many and array of id
First i have this problem: I want to send an array of id to the backend and then search for some things related to that id. but I don't know how to send the array, I am using this form. How should I pass the array to that url? var ids = [1,3,34,76,114] ... await self._list (`1.0/cda/inventariov/`, (response) => {}) Second: I have this url in the backend router.register (r'tecnico', viewsets.TecnicoViewSet) this is the view set class TecnicoViewSet ( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Technician.objects.all () serializer_class = Tecnicoserializer def list (self, request): data = request.data # [1,23,43,65] return Response(data) when I receive the array from step 1, I want to search all the information related to the id in different tables. As I said before, I have received the id of the technicians to consult, a model is work_orders so I want to obtain all the work orders made by each technician. apart from that I also need more queries to other models in the same viewset, but I think that is enough. this is the tecnico model class Tecnico(BaseModel): foto = models.ImageField(blank=True, null=True, verbose_name='Foto tecnico', upload_to='cda/pictures') empleado = models.IntegerField(null=True) categoria_tecnicos = models.ForeignKey('cda_configuracion.listaitems', related_name='Categoria_tecnico', on_delete=models.PROTECT) activo … -
Normal text field workable but once i add in form control it stop working
Currently I have this form where the inputs are normal textfield (Basic look) and it works. But once i add in form control, it stop working. In my HTML (One part of the text field) Workable <div class="col-md-5"> <div class="form-group"> <label for="{{form.hostname.id_for_label}}">Hostname</label> {{form.hostname}} </div> </div> But if i change it to Not workable <div class="col-md-5"> <div class="form-group"> <label for="{{form.hostname.id_for_label}}">Hostname</label> <input class="form-control" type="text" id="form.hostname.id_for_label" name="form.hostname" placeholder="" required> </div> </div> Am i doing something wrong? Appreciate if anyone could help -
How to find the percentage of employee scores using django
I have a table called Task. It captures task, task score and the employee it is assigned to. I want to calculate the performance of the employee using his total task scores for the week (duration should be dynamic. preferably input field) and the total scores allocated. I am thinking of aggregating the actual scores then dividing buy total score then multiply by 100 to get the percentage. My major challenge is where to perform this calculation. Should I create a model called performance and use a function? Or if can anyone show me how to go about this? Here is the model; class Task(models.Model): scores = models.IntegerField(null=True, blank=True) def __str__(self): return self.name Here is the formula I want to use. Performance(%) = actual score / total score * 100. Total score should be input field. -
How to fix error: 'str' objects is not maaping
<form action={% url "likeblog" article.pk %} method="post"> {% csrf_token %} <button style="height: 30px" type="submit" name="like" id="btnLike" value="{{ article.id }}"> <i class="far fa-thumbs-up"></i> </button> </form> and my urls: urlpatterns = [ path('like/<int:pk>', views.LikeBlog, name='likeblog'), ] but django error: 'str' object is not a mapping when the i using httpReponseRederit or redict django error str is not mapping! help me please -
Django model query - how to join string list with F expression
I have a model with array field and now a new string field required to hold content from array field with string format. class MyModel(models.Model): array_field = ArrayField( models.CharField( max_length=255, blank=True, null=True ), blank=True, null=True ) text_field = models.TextField(null=True, blank=True) I intend to use F() with update() like below MyModel.objects.filter(array_field__isnull=False).update(text_field="; ".join(F("array_field"))) But it gives me below error TypeError: can only join an iterable Does F() work with join()? -
Django (DRF) trailing slash issue
I have problem with PUT request in DRF, and it is basically about the url not having trailing slash, but even when i add a trailing slash to the required URL, it gives error (page not found 404) on the backend side, thus the data is not fetched in the frontend side anyway if someone has any solution, please tell here is my code: urls.py from django.contrib import admin from django.urls import path,include from rest_framework import routers from main import views router = routers.DefaultRouter() #Creating a router object which i assume is the web API root router.register(r'todos/', views.TodoView, 'todo') #mapping views URL'S to the router (web api root) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) #including all views urls/route in the same url path (api/) ] if frontend side also matters: app.js handleUpdate(item){ if(item.id){ axios.put(`http://localhost:8000/api/todos/${item.id}`) return } } -
Django Radio Buttons:
I have this following HTML Page: <p> Defect? <input type="radio" name="radAnswer" id="defect-yes"/> <label for="defect-yes">Yes</label> <input type="radio" name="radAnswer" id="defect-no"/> <label for="defect-no">No</label> </p> <p> Action Correctly Captured? <input type="radio" name="radAnswer2" id="defect-yes"/> <label for="defect-yes">Yes</label> <input type="radio" name="radAnswer2" id="defect-no"/> <label for="defect-no">No</label> </p> That displays this: And I have a field called Audit Outcome, that contains yes no or blanks as an input, and I wanted to know how to display radio buttons accordingly. I was thinking of something like : {% block content %} <form method="POST" action=""> {% csrf_token %} {% for item in items %} {% if item.Audit_outcome = "Yes" %} <input type="radio" name="radAnswer" id="defect-yes"/> <label for="defect-yes">Yes</label> {% else %} <input type="radio" name="radAnswer2" id="defect-no"/> <label for="defect-no">No</label> {% endif %} {% endfor %} </form> {% endblock %} But i know for a fact that this is not even close to what needs to be done... If anyone could give me their input or if you require more information. Thanks! -
Customizing Django's contrib.auth views for password reset
Since Django 3.0, the django.contrib.auth views are class-based views. So when developing a password reset on a website, you would have to import do something like from django.contrib.auth import views as av av.PasswordResetDoneView.as_view(template_name="accounts/password_reset_sent.html") However, I want to add some custom features to my site like sending an email AFTER the password has been reset by the user. Where can I add my custom functions and how? Note: I already configured an SMTP to my site and I also have the password reset setup with my custom templates. -
Django "Model class <Class> doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS" after separating models
I'm getting this error and I've been trying to fix it for many hours, it came up once I separated my models.py into a directory with multiple files. This is the current structure of my project. I have omitted many files, but these are the relevant ones: Project_folder academy app1 app2 manage.py models _ _ init _ _.py content.py session.py app3 config static Before, I had all my models in a single file inside app2, called models.py. However, as the file started to grow too large, I separated each of the models into different categories. Also, in __init__.py I imported these elements: from academy.app2.models.content import * from academy.app2.models.session import * Now, when I try to make migrations with python manage.py makemigrations app2, as usual, I'm getting this error: RuntimeError: Model class core.models.content.Reward doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When I searched for this error, I came across this answer, however, when I add the Meta Class declarating the app_label, I get this error: RuntimeError: Conflicting 'reward' models in application 'app2': <class 'academy.app2.models.content.Reward'> and <class 'app2.models.content.Reward'>. This is my Config file for app2: class App2Config(AppConfig): name = 'academy.app2' This is my INSTALLED_APPS: INSTALLED_APPS = [ … -
DRF python ReturnList to JSON
I am trying to query informaicon and then I want to loop through that information to get certain data. The point is that when I try to go through the item "data" in the console I get a message saying "AttributeError: object 'ReturnList' has no attribute 'elements' " when I do "type (data)" I get the following: <class 'rest_framework.utils.serializer_helpers.ReturnList'> without the for (no errors) the information arrives as a JSON to the front. [{id: 1, photo: null ..}, {id: 2, photo: null ..} ... etc] viewSet code: class TecnicosViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer def list(self, request): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer(queryset, many=True) data = serializer_class.data print(type(data)) # for index, item in data.items(): # print('II', index) return Response(data) -
Django Apache Site: Loads Forever
I have a Django Site running on an Apache server which is running with no errors but when i serach for localhost it loads forever and doesn't give a 404 response or anything. Any idea what i am doing wrong? Also, i am doing this using Apache and mod_wsgi. httpd.conf Define SRVROOT "c:/Apache24" ServerName localhost Include conf/extra/httpd-vhosts.conf LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" httpd-vhosts.conf <VirtualHost *:80> ServerName localhost ServerAlias localhost WSGIScriptAlias / "C:/Users/Administrator/Desktop/myapp/myapp/wsgi_windows.py" <Directory "C:/Users/Administrator/Desktop/myapp/myapp/"> <Files wsgi_windows.py> Require all granted </Files> </Directory> </VirtualHost> wsgi_windows.py import os import sys import site from django.core.wsgi import get_wsgi_application sys.path.append('C:/Users/Administrator/Desktop/myapp/') os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() -
how to submit two subforms with one parent form using formset , giving formset values to M2M field django
i'm trying to make Hotel management system for an hotel , the scenario is : if the two visitor come for the first time ,they should be registered , using inline formset , and give the values for a M2M field in this case the M2M should accept null, and if those two visitors came again , we dont need to register , and just search for their name in the M2M field , and the admin can upload multiple images these is my models class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',related_name='vistors',blank=True) check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) #others class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_vistors') full_name = models.CharField(max_length=150) dob = models.DateField(max_length=14) city = models.ForeignKey(City,on_delete=models.CASCADE) #others class Meta: constraints = [ models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information') ] class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my forms.py class BookingForm(forms.ModelForm): takes_by = forms.ModelMultipleChoiceField(queryset=Vistor.objects.all()) class Meta: model = Booking fields = ['takes_by','check_in','check_out',#others] class VistorForm(forms.ModelForm): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = Vistor fields = ['full_name','dob','city'] VistorsInlineFormset = inlineformset_factory(Booking,Vistor,form=VistorForm,extra=1,can_delete=True) but it wont let me to leave takes_by null , it raise this field is required and i've used Function based view , this is my views.py @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) isnot_checked … -
Django: Hidden form FIELD (not widget) with `form.as_table`
One can add a disabled attribute to a widget by passing in attrs={'disabled':True}. However there also exists a disabled form field (not widget) argument, which tells Django this field is disabled, and then Django handles it accordingly in the validation logic and also setting the HTML disabled attribute. Now similarly with regards to hidden, one can set a widget to be hidden passing in attrs={'hidden':True}, but the problem with this is that it only hides the HTML input widget, the label associated with it still shown. How does one get around this problem (when using form.as_table, I understand one can loop through the visible and hidden fields and manually build up a form, but thats not what I am looking for. Under Core field arguments I would expect to see a hidden attribute.