Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - uploading data to a model with pandas ".to_sql()" causes problems for the foreign key field
I identified a problem that ".select_related()" doesn't work if the table with a foreign key was uploaded using pandas. Uploading data the alternative way using a loop is not an option because the table is too big. Here's an example: Set up #Models class Magazine(models.Model): name = models.CharField(max_length=20, unique=True, primary_key=True) founded = models.CharField(max_length=20, unique=True, primary_key=True) def __str__(self): return self.name class Issue(models.Model): name = models.ForeignKey(Magazine, on_delete=models.CASCADE, db_column="name") week = models.CharField(max_length=10, unique=False) def __str__(self): return self.week #Admin from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) #Migrated python ../manage.py makemigrations python ../manage.py migrate Fill first table import os import sys import pandas as pd import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') #configures the settings for the project. Need to do this before manipulating models django.setup() from mainsite.models import Magazine, Issue magazineNames = ['journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'NEVERISSUED'] magazineFounded = ['1901', '1995', '2005', '2011', '1993', '1900'] Magazine.objects.bulk_create([Magazine(name=i, founded=j) for i,j in zip(magazineNames, magazineFounded)]) Fill second table 1.) THIS WORKS for Issue.objects.select_related("name"), but uses a loop. It works because I can specify the names being a Magazine() instance. issueNames = ['journal science', 'journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'lawncare'] issueWeeks = ['1', '2', '3', '4', '5', '6', '7'] Issue.objects.bulk_create([Issue(name=Magazine(name=i), week=j) … -
Invalid signature Django rest framework simple_jwt token
Hiii i am faced with a problem of invalid token. I am testing simple_jwt with django rest framework When i log on the endpoint of TokenObtainPairView i receive refresh and access token but when i verify that token on jwt.io, I have invalid signature. It is obvious that my simple_jwt deliver me the wrong token. I don't know where the problem come from. After research I am thinking may be I need to Change 'SIGNING_KEY': SECRET_KEY,but I don't know how. I mentioned that I am using the pure TokenObtainPairView whithout any customization. If someone can help me. I am new here -
Max occurrences of a foreign key inside query
I'm trying to get an item with the most occurrences of a foreign key (votes), inside of a queryset (Questions, Choices). I.E. I need to get the most popular vote to set the 'winner' attribute in the JsonResponse. Any help on how I can figure this out? Here is my view. allchoices = [{ 'id':i.id, 'question':i.question.id, 'choice_text':i.choice_text, 'votes':i.voter_set.all().count() } for i in poll_choices] return JsonResponse({ "votes":choice.voter_set.all().count(), 'winner':True, 'success':True, 'allchoices':allchoices },safe=False,) These are my models: class Voter(models.Model): # Authentication of anonymous users choice = models.ForeignKey('PollChoice', on_delete=models.CASCADE) question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) class PollChoice(models.Model): question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class PollQuestion(models.Model): question = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey('poll_creator',/\ on_delete=models.CASCADE, null=False, blank=False) uuid = ShortUUIDField(length=8, max_length=12) def poll_choices(self): return self.pollchoice_set.all().annotate(voters=/\ models.Count(models.F('voter'))).order_by('-voters') def choices(self): return self.pollchoice_set.all() def __str__(self): return f'{self.question}' -
Django - how to see ALL column results of a join using .select_related()?
I am having difficulty seeing the foreign table's field from a resulting join using select_related(). Any idea what my issue is here? Define models class Magazine(models.Model): name = models.CharField(max_length=20, unique=True, primary_key=True) founded = models.CharField(max_length=20, unique=True, primary_key=True) def __str__(self): return self.name class Issue(models.Model): name = models.ForeignKey(Magazine, on_delete=models.CASCADE, db_column="name") week = models.CharField(max_length=10, unique=False) def __str__(self): return self.week Register from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) Migrate python ../manage.py makemigrations python ../manage.py migrate Loading data import os import sys import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mags.settings') #configures the settings for the project. Need to do this before manipulating models django.setup() from mainsite.models import Magazine, Issue magazineNames = ['journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'NEVERISSUED'] magazineFounded = ['1901', '1995', '2005', '2011', '1993', '1900'] Magazine.objects.bulk_create([Magazine(name=i, founded=j) for i,j in zip(magazineNames, magazineFounded)]) issueNames = ['journal science', 'journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'lawncare'] issueWeeks = ['1', '2', '3', '4', '5', '6', '7'] Issue.objects.bulk_create([Issue(name=Magazine(name=i), week=j) for i,j in zip(issueNames, issueWeeks)]) #QUERY Issue.objects.select_related("name").values_list() <QuerySet [(1, 'journal science', '1'), (2, 'journal science', '2'), (3, 'naughty mag', '3'), (4, 'funny cartoons', '4'), (5, 'comic fans', '5'), (6, 'lawncare', '6'), (7, 'lawncare', '7')]> -
AttributeError at /app/ 'numpy.ndarray' object has no attribute 'read'
I am making a wep app for face recognition by django and face_recogntion api, I don't how to solve this error from django.http import HttpResponse from django.shortcuts import redirect, render from .models import * import face_recognition import cv2 import urllib.request import numpy as np import dlib def Home(request): print(f'request method is {request.method}') if(request.method=='GET'): return render(request, "app.html") elif(request.method=='POST'): print(f'printing req body {request.POST["imageURL"]}') imageURL = urllib.request.urlopen(request.POST["imageURL"]) imageURL = face_recognition.load_image_file(imageURL) image = face_recognition.load_image_file(imageURL) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) imgLoc = face_recognition.face_locations(image); print(f'Image imagLoc {imgLoc}') cv2.imshow(image) cv2.waitKey(3000) return redirect('/app/') I am asking question on stackoverflow for the first time so sorry for any mistakes. -
How to check if there was a call of service function from APIView?
I'm trying to implement the service layer in my API. Now im trying to test create function with unittest lib. I dont really figure out, how to code it right. views.py class AuthorListApi(APIView): class InputSerializer(serializers.Serializer): name = serializers.CharField() def post(self, request): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) create_author(**serializer.validated_data) return Response(serializer.data, status=status.HTTP_201_CREATED) services.py def create_author(name: str) -> Author: """ Create a Author model object. """ author = Author(name=name) author.full_clean() author.save() return author test_view.py @mock.patch('books.views.AuthorListApi.create_author') def test_view_calls_service(self, service_mock): self.client.post(self.url, data=self.data) service_mock.assert_called_once_with(**self.data) Assertion error is: AttributeError: <class 'books.views.AuthorListApi'> does not have the attribute 'create_author' -
unsupported operand type(s) for -: 'DateField' and 'DateField'
I am working on creating a contract model with Django and I came cross on how to get the time duration from the start_date to the end_date?? class Contract(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=10) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) duration = models.IntegerField(end_date - start_date) # how get the duration by hours created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API. There are not enough tutorials and documentations on the internet regarding the set of django and angular along with mongodb. or maybe im tunnel visioned now. If anyone has a link which might solve my problem it would be great. Below is my angular's html file where you can see the form <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="InputAttackTitle">Attack Title</label> <input ngModel type="text" class="form-control" name="AttackTitle" id="InputAttackTitle" placeholder="Enter Attack Title"> </div> <div class="form-group"> <label for="InputAttackDescripton">Attack Description</label> <textarea ngModel class="form-control" name="AttackDescription" id="InputAttackDescripton" placeholder="Enter Attack Description" ></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <br> </div> Here you can see component.ts file export class IconsComponent implements OnInit { form: FormGroup; constructor(config: NgbModalConfig, private modalService: NgbModal,private http:HttpClient, public fb:FormBuilder) { config.backdrop = 'static'; config.keyboard = false; this.form = this.fb.group({ AttackTitle: [''], AttackDescription: [null] }) } AttackTitle:any; AttackDescription:any; onSubmit(){ var formData:any = new FormData(); formData.append("AttackTitle",this.form.get('AttackTitle').value); formData.append("AttackDescription",this.form.get('AttackDescription').value); this.http.post('http://127.0.0.1:8000/attackinfo', formData).subscribe( (response) => { return console.log(response); }, (error) => console.log(error) ) Below is the django's models class class AttackInfo(models.Model): AttackTitle=models.CharField(max_length=70, blank=False) AttackDescription = models.TextField(default='',blank=False) And Below is the view file @csrf_exempt def AttackInfoAPI(request,id=0): if request.method=='GET': attackinfo = AttackInfo.objects.all() attackinfo_serializer=AttackInfoSerializer(attackinfo,many=True) return JsonResponse(attackinfo_serializer.data,safe=False) elif … -
error when I push my project django to heroku
I want to deploying my project in heroku so I run heroku login heroku create heroku git:remote -a frozen-ravine-47377 heroku config:set DISABLE_COLLECTSTATIC=1 it's done and when i run git push heroku master I got error: $ git push heroku master Enumerating objects: 278, done. Counting objects: 100% (278/278), done. Delta compression using up to 4 threads Compressing objects: 100% (272/272), done. Writing objects: 100% (278/278), 694.38 KiB | 5.99 MiB/s, done. Total 278 (delta 126), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.8/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python … -
How to check mime type for urls without extension in django
I am trying to find mime type of video urls without extension- I am using mimetypes.guess_type(video_url) for finding mime type if video url has extension .mp4 then I am getting a response video/mp4 otherwise it's returning null. is there a way to find mime type of a video url without extension ? -
How should i make DetailView in Django, gives 404
in file "views.py" i added next code: from django.views.generic import DetailView class NewsDetailView(DetailView): model = Articles template_name = "news/details_view.html" context_object_name = 'article' then in the file urls.py I added to urlpatterns next: path('<int:pk>', views.NewsDetailView.as_view(), name="news_detail"), and created the template "details_view.html". When i write to browser: http://127.0.0.1:8000/news/1 it gives 404 error 404 error in DetailView -
Serving Django static admin files with debug off in Elastic Beanstalk
Per other posts on this subject, I followed the advice at https://bestprogrammingblogs.blogspot.com/2021/03/django-static-files-not-working-when-debug-is-false.html to serve static files when debug is false. The site advises to make changes to Settings and URLs respectively STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in URLs re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), For some reason, my local admin works but the AWS admin site does not. Do I need to tune anything on the AWS side to get this working? My environment variables don't explicitly have any static settings at the moment. -
Bootstap DataTable showing No matching records found Django
I am developing a project in Django where users can share files. I retrieve data(files) from the database and show it in a table on the template and use bootstrap DataTable to implement search functionality in my table But when I search any record from DataTable it shows me No matching records found. Bootstrap CSS CDN <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css"> Javascript CDN <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script> Tamplate <table id="datatable" class="table table-striped table-bordered" style="width:100%"> <thead style="background-color : #607d8b;"> <tr> <th>S.No</th> <th>Uploading Date</th> <th>Branch</th> <th>Subject</th> <th>Download Notes</th> <th>File Type</th> <th>Description</th> <th>Status</th> <th>Action</th> </tr> </th -
Django radio button values in views
I'm using Radio buttons in django forms to record gender fields of object Person, as below. Person Model class Person(models.Model): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) gender = models.CharField(choices=GENDER, null=True, blank=True, max_length=30) My PersonForm class PersonForm(forms.ModelForm): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") email= forms.CharField(label="Email") gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect(),) class Meta: model = Client fields = ['first_name', 'last_name','email','gender'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(PersonForm, self).clean() return cleaned_data Then my create_person_view(() def create_person_view(request): if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): form.save(): return render(request, 'person/view_persons.html') else: form = PersonForm() return render(request, "person/create_person.html", {"person_form": form}) Now, I save the form and saves fine. The problem comes in when getting the saved data from database and passing to templates. Specifically when I do Gender: {{person.gender}} It gives: Gender: <django.forms.fields.ChoiceField object at 0x7fd82ae866a0> I wanna display the real value of gender. Any help? Will be really appreciated. -
How to modify a Django Model field on `.save()` whose value depends on the incoming changes?
I have fields in multiple related models whose values are fully derived from other fields both in the model being saved and from fields in related models. I wanted to automate their value maintenance so that they are always current/valid, so I wrote a base class that each model inherits from. It overrides the .save() and .delete(). It pretty much works except for when multiple updates are triggered via changes to a through model of a M:M relationship. So for example, I have a test that creates 2 through model records, which triggers updates to a model named Infusate: glu_t = Tracer.objects.create(compound=glu) c16_t = Tracer.objects.create(compound=c16) io = Infusate.objects.create(short_name="ti") InfusateTracer.objects.create(infusate=io, tracer=glu_t, concentration=1.0) InfusateTracer.objects.create(infusate=io, tracer=c16_t, concentration=2.0) print(f"Name: {infusate.name}") Infusate.objects.get(name="ti{C16:0-[5,6-13C5,17O1];glucose-[2,3-13C5,4-17O1]}") The save() override looks like this: def save(self, *args, **kwargs): # Set the changed value triggering this update so that the derived value of the automatically updated field reflects the new values: super().save(*args, **kwargs) # Update the fields that change due to the above change (if any) self.update_decorated_fields() # Note, I cannot call save again because I get a duplicate exception: # super().save(*args, **kwargs) # Percolate changes up to the parents (if any) self.call_parent_updaters() The automatically maintained field updates are performed here. Note … -
Facing relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... issue. Can anybody help me?
Recently, I'm working with my Django Portfolio and after successfully deploying on Heroku I faced this error LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... So, this is how complete error is looking like Request Method: GET Request URL: https://shubhajeet-pradhan.herokuapp.com/ Django Version: 3.0.8 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shubhajeet_portfolio', 'base.apps.BaseConfig', 'crispy_forms', 'django_filters', 'ckeditor', 'ckeditor_uploader', 'storages', 'cloudinary_storage'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Template error: In template /app/base/templates/base/index.html, error at line 171 relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... ^ 161 : </div> 162 : </section> 163 : 164 : <section class="s1"> 165 : <div class="main-container"> 166 : <div class="greeting-wrapper"> 167 : <h3 style="text-align: center;">Projects</h3> 168 : <div class="blog-wrapper"> 169 : {% include 'base/navbar_blog.html' %} 170 : <div class="post-wrapper"> 171 : {% for post in posts %} 172 : <div> 173 : <div class="post"> 174 : <img class="thumbnail" src="{{post.thumbnail.url}}"> 175 : <div class="post-preview"> 176 : <h6 class="post-title">{{post.headline}}</h6> 177 : <p class="post-intro">{{post.sub_headline}}</p> 178 : <a href="{% url 'post' post.slug %}">Read More</a> 179 : </div> 180 : </div> 181 : </div> Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception … -
drf-spectacular define request schema as JSON Array (like Serializer(many=True))
Is it possible to define "many" serializer schema in drf-spectacular? The request should take this data (JSONArray): MonthlyIncomeSerializer(many=True) Which is a list of objects/dictionaries: [ {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, ] I tried: class PartialDTIPrenajomView(APIView): @extend_schema(parameters=[MonthlyIncomeSerializer(many=True)]) def post(self, request, **kwargs): which doesn't render anything in Swagger. -
Django/Docker: web container not up-to-date code
I use Django docker app and do not manage to apply code update to my web container. I've tried to delete all containers (docker rm -f ID ; docker system prune) and images (docker rmi -f ID ; docker image prune) related to my app and re-build with docker-compose -f docker-comose.preprod.yml build Then I run docker-compose -f docker-comose.preprod.yml up but for some reasons when I connect to my web running container (docker exec -it web sh) and read my updated files, I observe that update are not applied... How should I do to make my update applied? -
Django get count of related objects with value and add it to an annotation
If I want to annotate the number of related objects to each parent object, I would do this: Agent.objects.annotate(deal_count=Count('deal')) If my Deal objects have a closed boolean, how would I annotate the number of deals marked as closed? -
designating/connecting a model to a user - django
Im trying to make a social media site and wanted to connect a user to work experience. My current form is from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterForm(UserCreationForm): it takes in regular registration parameters like email, name, etc. If i was to make a several other models in the models.py does user = models.OneToOneField(User, on_delete=models.CASCADE) act as a connection? I want to connect several models to a certain user, so im assuming i'd have to drop one to one and instead use foreign key to reference the forms. Or is there a better approach to connecting a user with several other models along with ability to edit profiles -
How to use formset to get data from localstorage - DJANGO
i want to get data from local storage (because i don't use database), i use form NOT MODALS. views.py : def homepage(request): form_class = Audio_store form = form_class(request.POST or None) if request.method == "POST": form = Audio_store(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file1(request.FILES['password']) handle_uploaded_file(request.FILES['audio']) return render(request, "homepage.html", {'form': form}) return render(request, "homepage.html", {'form': form}) def song(request): songmp3 = formset_factory(Audio_store) if request.method == 'POST': formset = songmp3(request.POST, request.FILES) if formset.is_valid(): audiomp3 = formset.get.context('audio') pass else: formset = songmp3() return render(request, 'homepage.html', {'formset': formset}) form.py : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) can i use formset to get data from local storage? -
How do I iterate every item in a Django field using the <input type="select">?
I am a newbie in Django and I followed a video and used class Meta in creating the Django form. I wanted to modify the way the fields appear using HTML. Here is my code for Form: class AddForum(forms.ModelForm): class Meta: model = Forum fields = '__all__' labels = { 'post_title': 'Title of your post:', 'post_body': 'Content of your post:', 'author': 'Author:', 'forum_image': 'Attach image:', } def __init__(self, *args, **kwargs): super(AddForum, self).__init__(*args, **kwargs) self.fields['forum_image'].required = False I learned how to use <input> to add the post_title: <input class="for_post_title" type="text" name="post_title" placeholder="Forum Title"> like so. However, the author field as shown in Form must be entered using the dropdown menu. How should I iterate every existing author in the Django database and have it shown using the <select> element? -
Not able to pass post values from views.py to index.html in django
I am trying to show the form data received from the POST request on an HTML table. I have used JavaScript fetch API to submit the form and fetch the data in views.py . I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) context={"options_value":options_value, "value":value} return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </form> <table style="display: table" id="table"> <tbody> <tr> <th scope="row">ProfileUID :</th> <td>{{options_value}}</td> </tr> <tr> <th scope="row">First Nane :</th> <td>{{value}}</td> </tr> </tbody> </table> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val … -
django rendering a search result based on which submit button
when i try to search from the navbar i want a simple query to execute based on an input type="submit" and name="searchInput" when i submit the second form from the searchPage i want a different kind of query to happen and render me the searchPage with the data in it however it keeps redirecting me to the home Page def home(request) : q = request.GET.get('searchInput') if q!=-1: offres = Offre.objects.filter( Q(title__icontains=q) | Q(user__username__icontains=q) | Q(description__icontains=q) | Q(wilaya__name__icontains=q) ) context = { 'offres': offres, } return render(request,'searchPage.html',context) return render(request,'index.html',{}) def is_valid_query_parameter(parameter): return (parameter!='' and parameter is not None) def search(request) : if request.GET['submit'] == 'searchInput': q = request.GET.get('searchInput') if request.GET.get('searchInput') !=None else '' offres = Offre.objects.filter( Q(title__icontains=q)| Q(user__username__icontains=q)| Q(description__icontains=q)| Q(wilaya__name__icontains=q)| Q(category__value=q) ) context = { 'offres':offres, } return render(request,'searchPage.html',context) wilaya = request.GET.get('wilaya') hotel = request.GET.get('hotel') house = request.GET.get('house') land =request.GET.get('land') nbedrooms = request.GET.get('bedrooms') nbathrooms = request.GET.get('bathrooms') minPrice = request.GET.get('minPrice') maxPrice = request.GET.get('minPrice') wifi = request.GET.get('wifi') kitchen = request.GET.get('kitchen') furniture = request.GET.get('furniture') # mustInclude = {'wifi' : wifi, # 'kitchen' : kitchen, # 'furniture' :furniture } # excludeList = [] qs = Offre.objects.all() if is_valid_query_parameter(wilaya) : qs.filter(wilaya__number = wilaya) if not is_valid_query_parameter(hotel) : qs.exclude(category__value = 'hotel' ) if not is_valid_query_parameter(house) : qs.exclude(category__value … -
Django. Star rating multiple form displayed in a grid view not working
I've got a little problem. I have a page that is used to rate ski resorts. They are displayed in a grid view and each resort has a star rating form beneath. The problem is that only the first item in the grid can be rated. I tried to assign each form an unique id but that didn't work. Here is the code: class AddRatingForm(forms.ModelForm): class Meta: model = ResortUserRating fields = '__all__' widgets = { 'resort_rating': forms.RadioSelect() } def __init__(self, pk, *args, **kwargs): super(AddRatingForm, self).__init__(*args, **kwargs) self.pk = pk self.fields['user'].initial = self.pk def clean(self): return self.cleaned_data {% for resort in dashboard_resorts %} <div class = "grid-item"> {% if resort.img %} <img class="card-img-top" src="{{resort.img.url}}" alt ="Card image cap" height="300px" width="380px"> {% endif %} <p> <b>{{resort.name|upper}} </b></p> <p> <b>{{resort.id|upper}} </b></p> <form method="post" action = "{% url 'aplicatie2:rating' %}"> {% csrf_token %} <input type = "hidden" name = "user" value = "{{user.id}}"> <input type = "hidden" name = "resorts" value = " {{resort.id}}"> <div class="rate"> <input type="radio" name="resort_rating" id="rating1" value="1" required /><label for="rating1" title="1"> </label> <input type="radio" name="resort_rating" id="rating2" value="2" required /><label for="rating2" title="2"> </label> <input type="radio" name="resort_rating" id="rating3" value="3" required /><label for="rating3" title="3"> </label> <input type="radio" name="resort_rating" id="rating4" value="4" required /><label …