Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access to property in view(django)
I'm beginner and I need some solution First, I have Racket and Detail class. class Racket(models.Model): name = models.CharField(max_length=20) class RacketDetail(models.Model): racket = models.OneToOneField(Racket, related_name='detail', on_delete=models.CASCADE) adminReview = models.TextField() adminPower = models.FloatField(default=0) adminSpin = models.FloatField(default=0) adminManeuverability = models.FloatField(default=0) adminStability = models.FloatField(default=0) adminComfort = models.FloatField(default=0) @property def adminAvgScore(self): scoreAvg = ( self.adminPower + self.adminSpin + self.adminManeuverability + self.adminStability + self.adminComfort ) / 5 return round(scoreAvg, 2) Second, I want to rander list using the @property(adminAvgScore), so I made view like this. def racketMain(request: HttpRequest): getRacket = Racket.objects.all().order_by('detail__adminAvgScore') return render(request, "racket/racketMain.html", {'racketItems': getRacket, }) Unfortunally when I use 'RacketDetail' class's column I can access all column except 'adminAvgScore' using by "order_by('detail__". If I use like "order_by('detail__adminAvgScore')" then Django show to me error "Unsupported lookup 'adminAvgScore' for BigAutoField or join on the field not permitted." How can I solve it? Or should I think in a different way? -
Django python + javascript countdown – time is off by 3 hours
I am relatively new and just a hobbyist programmer. At the moment I try to work on a small Django project where I want to set a date and time in the future via a form and after the user clicks "Submit", the page shows a countdown from now until the set date and time. After experimenting a bit with the datetime module, I find myself with an awkward problem. I have two fields in the forms: 1. date, and 2. time With timestamp = datetime.datetime.combine(date, time).strftime('%s') I combine those two information and get a seconds output. I then, pass timestamp to my .js file with {{ timestamp|json_script:'timestamp'}}. In javascript, I do the following: const setTime = JSON.parse(document.getElementById('timestamp').textContent); var difference = setTime * 1000 - now.getTime(); //Python gives me seconds not milliseconds date = new Date(difference); datevalues = [ date.getYear() - 70, date.getMonth(), date.getDate() - 1, date.getHours(), date.getMinutes(), date.getSeconds(), ]; document.getElementById("countdown").innerText = datevalues[0] + "years" + datevalues[1] + "months" + datevalues[2] + "days" + datevalues[3] + "hours" + datevalues[4] + "minutes" + datevalues[5] + "seconds" + setTime * 1000 + " ... " + now.getTime() + " ... " + difference let t = setTimeout(function () { timer() }, 1000); … -
local variable 'product' referenced before assignment ? in Django
I am facing the issue I can't find the solution yet. It's working so far. but now showing an error. don't know how to fix this. please need help. views.py def add_product(request): product_form = ProductForm() product_variant_images_form = ProductVariantsImagesForm() if request.method == 'POST': product_form = ProductForm(request.POST) product_variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES) if product_form.is_valid(): print(request.POST) product = product_form.save(commit=False) vendor = CustomUser.objects.filter(id=request.user.id) product.vendoruser = vendor[0] product.save() vendor = CustomUser.objects.get(id=request.user.id) product_variant = ProductVariants() product_variant.product_id = product ###ERROR SHOWING IN THIS LINE product_variant.vendoruser = vendor product_variant.price = request.POST.get('price') product_variant.initial_stock = request.POST.get('initial_stock') product_variant.weight_of_product = request.POST.get('weight_of_product') product_variant.save() return redirect('vendor:inventory_display') else: productform = ProductForm() productvariantsform = ProductVariantsForm() product_variant_images_form = ProductVariantsImagesForm() return render(request, 'vendor/add_product.html', {'productform': productform,'product_variant_images_form':product_variant_images_form, 'productvariantsform': productvariantsform}) It's working fine.After product added multiple time the error occurred. how can I get rid of this error.please some help much appreciated. -
How to access a specific element from a CHOICES list in Django?
In my models, I have a choices list, such as: class Graduation(models.Model): YEAR_IN_SCHOOL_CHOICES = [ ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ('GR', 'Graduate'), ] student_level = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES) In my views, I want to get the value for a specific element. I have this: search = 'JR' all_choices = Graduation.YEAR_IN_SCHOOL_CHOICES My goal is to get Junior returned by the system. How can I do that? I tried: all_choices[search] but that doesn't work. I know I can change the format of my choices list in the models, but in this case my models can not be changed. What is the right way to obtain the label from this list? Do I have to loop through the list and use an if statement? That doesn't seem efficient but I am not sure if I have another choice. -
How can I login to two django applications with a single access credential?
I currently have several applications developed in django, and they ask me that with a single credential and depending on the permissions assigned to each user, they can access the different applications, how could I do that taking into account the session management middleware what does django have? -
Why My video is not playing from my code...?
I am working on a project and my video element is not working. here is my code below for html file <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>Jangeer</title> </head> <body> {% load static %} <video src="{% static 'video.webmhd.webm' %}" muted autoplay loop></video> </body> </html> I am working in django framework. -
Django Shell Plus Clear History
Is there a command to clear the history of Django's Shell Plus? I did not find any hints in the documentation or by typing ?. -
how do i get the repeating event details on all following dates in python django
models: from django.db import models class datecrt(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() forms: import datetime from xml.dom.minidom import Attr from django import forms from .models import datecrt class dateform(forms.ModelForm): class Meta: model=datecrt fields='__all__' widgets={ 'stdate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ), 'sttime':forms.TimeInput( attrs={'type':'time','class':'form-control'}, format='%H:%M', ), 'endate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ) } def __init__(self,*args,**kwargs): super(dateform,self).__init__(*args,**kwargs) self.fields['stdate'].imput_format=('%D-%m-%yy',) self.fields['sttime'].imput_format=('%H:%M',) self.fields['endate'].imput_format=('%D-%m-%yy',) Views: from unicodedata import name from django.shortcuts import redirect, render from .forms import dateform from .models import datecrt def datecr(request): if request.method=='GET': form=dateform() return render(request, 'date.html', {'form':form}) else: form=dateform(request.POST) if form.is_valid(): form.save() return redirect('/dateview') def dateview(request): context={'dateview':datecrt.objects.all()} return render(request, 'dateview.html',context) When I create this booking on 1st of feb and end date will select as 5th of feb, my challenge is, created booking should display name, date, and time till 5th of feb automatically in dateview template, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Django-PolymorphicModel- How to create child class without fieldname
I didnot use PolymorphicModel befor. Its new to me. I want to both parent and child class. I want to access all the child class from parent class. So i am using this one.I want to create one child class without fields. because, Foreignkey it will create own if i try also it will through error. how can I achieve this?? models.py class EmploymentStatus(PolymorphicModel): status = models.CharField(max_length=255) employment = models.ForeignKey(Employment, on_delete=models.RESTRICT) from_date = models.DateField(null=False) status_from_date = models.DateTimeField(null=False, default=datetime.utcnow) status_turu_date = models.DateField() def __str__(self): return self.id class PendingEmploymentStatus(EmploymentStatus): -
Django Display count of database entries related via foreign key
I have two models, ProjectNotes and ProjectNoteComments. ProjectNoteComments are related to ProjectNotes via a foreign key. I want to display the number of comments each note has on a listview. I am just learning Django and so far I have not been able to figure out how to retrieve and display the comment count. My view: (I do import count) class ProjectNotesList(ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' comments = ProjectNotes.comments def related_project(self, **kwargs): project = get_object_or_404(Project, id=self.kwargs.get('pk')) notes = ProjectNotes.objects.all return notes def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments')) My template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <h1>Notes for {{ project }}</h1> {% if project.notes.all %} {% for note in project.notes.all %} <div class ="projectnotes-entry"> <div class="col-sm-8"> <div class="row-sm-6"> <div class="card mb-2"> <div class="card-body"> <div class="card-title"><a href="{% url 'project_note_detail' project.pk note.pk %}">{{ note.title }}</a></div> <div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }} <a href="{% url 'project_note_detail' project.pk note.pk %}">read more</a></div> </div> </div> </div> </div> </div> <h2>comments count</h2> {{ commentscount }} {% endfor %} {% else %} <p>No notes have been have been added yet.</p> {% endif … -
Number of Likes is not increasing in the template but it's works in admin
I follow a tutorial in youtube just to add a like button to my Blog application, but the number of likes is not increasing in the template. but its increase when i highlight a user and hit save in the admin area. I mean its working fine in the admin but not in template. how can i set that ? the model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = models.ImageField(null=False, blank=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return str(self.category) the view: def like(request, pk): post = get_object_or_404(Photo, id=request.GET.get('post_id')) post.Likes.add(request.user) return HttpResponseRedirect(reverse('view', args=[str(pk)])) def viewPhoto(request, pk): post = get_object_or_404(Photo, id=pk) photo = Photo.objects.get(id=pk) stuff = get_object_or_404(Photo, id=pk) total_likes = stuff.total_likes() return render(request, 'photo.html', {'photo': photo, 'post': post, 'total_likes': total_likes}) the templates: <form action="{% url 'Photo' photo.id %}" method="POST"> {% csrf_token %} {{ total_likes }} <button type="submit", name="post_id" value="{{ post.id }}">Touch</button> </form> the urls: path('', views.login, name='login'), path('home', views.home, name='home'), path('view/<str:pk>/', views.viewPhoto, name='Photo'), path('post/create', views.PostCreativeView.as_view(), name='post_create'), path('register', views.register, name='register'), path('comment/<str:pk>/', views.comment, name='comment'), path('like/<str:pk>/', views.like, name='like_post'), -
Django, custom auto increment charfields
I'm new in Django, with this method I wanna customize it to generate item code as the Primary Key, like this: PC.202202.001 PC => Primary Key in item_category model 202202 => year & month 001 => auto increments Now, my questions is how to get object/value ForeignKey field based on selected data into variable? So, it'll change the PrimaryKey in generate_code field every time a new data has been added. Also, how to make auto increments in proper way? Because, right now I'm just using queryset .count() Here's my model: class item_category(models.Model): id_item = models.CharField(primary_key=True, max_length=5, unique=True) name_item = models.CharField(max_length=150) def __str__(self): return self.name_item def auto_increment(): last_item_code = item_code.objects.all().last() total_item = item_code.objects.all().count() + 1 join_dates = datetime.now().strftime('%Y%m.') if not last_kode_barang: return 'NB.' + str(join_dates) + '00' + str(total_item) else: item_cat_id = last_kode_barang.id_item_category + '.' new_item_id = str(kat_barang_id + join_dates + '00' + str(total_item)) if total_barang >= 10: new_barang_id = str(kat_barang_id + join_dates + '0' + str(total_barang)) return new_item_id class item_code(models.Model): id_item_category = models.ForeignKey(kategori_barang, on_delete=models.CASCADE, db_column='id_barang') generate_code = models.CharField(primary_key=True, editable=False, default=auto_increment, max_length=20) -
Hi my friends, I'm learning Django recently and I have a problem that I tried to solve a lot and the problem is 'int' object is not iterable [closed]
from django.shortcuts import render from .models import Signup from .forms import SignupForm email = [] def checkSignup(name): count = Signup.objects.all().count() for i in range(count): i+=1 ch = Signup.objects.get(i) if ch.name==name: return True return False def signup_index(request): context = {'form':SignupForm} if request.method == 'POST': name = request.POST.get('name') password = request.POST.get('password') if checkSignup(name) == False: email.append(name) data = Signup(name = name , password = password) data.save() else: print("This email already exists") return render(request, 'signup_index.html',context) -
OnetoMany field in django models
From my search it comes to my understanding there is no OnetoMany Field in django, can someone explain or simplify a solution if i wanted to have these three classes connected to each other. a UserRank class which i can define as many as ranks i want,example (captain,2nd eng,chief mate...etc) a User class which can have one of the above ranks, a job class which can have 1 or many ranks from the UserRank class models.py class UserRank(models.Model): rank = models.CharField(blank=True,null=True,max_length=150) def __str__(self): return self.rank class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150,unique=True) name = models.CharField(max_length=150,) phone = models.CharField(max_length=50) date_of_birth = models.DateField(blank=True, null=True) picture = models.ImageField(blank=True, null=True, upload_to='users_imgs') is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) user_rank = models.ForeignKey(UserRank,related_name='userRank',null=True,on_delete=models.SET_NULL) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','name'] def get_full_name(self): return self.username def get_short_name(self): return self.username.split()[0] class Job(models.Model): job_type = ( ('I', 'Interval'), ('O', 'One time'), ) name = models.CharField(max_length=100) description = models.CharField(max_length=100) type = models.CharField(max_length=1, choices=job_type) interval = models.IntegerField() is_critical = models.BooleanField() due_date = models.DateField() user_rank = models.ManyToManyField(UserRank,related_name='ranks',blank=True) component = models.ForeignKey( Component, related_name='jobs', on_delete=models.CASCADE) runninghours = models.ForeignKey( RunningHours, related_name="RHjobs", on_delete=models.CASCADE) def __str__(self): return self.name -
Use an input password in django models and hash it
I'm trying to make a password field and hash it to have more security, but it didn't work trying to use form.InputPassword. Someone could help me? :) PS: I saw on stackoverflow using "forms" form django but im doing with models from django.db import models from uuid import uuid4 from django import forms class Cliente(models.Model): id_usuario = models.UUIDField(auto_created=True, default=uuid4, editable=False) nome = models.CharField(max_length=100, blank=False, null=False) senha = models.CharField(max_length=100, blank=False, null=False) -
Weasy-print convert to pdf with border image
Im trying to create pdf file for payment receipt. But im not able to figure out how do i set border for it. For border im using this image Like This . But While converting it to pdf next page gets Like this How can i make it constant border for all page Python + Django code: from weasyprint import HTML html_string = render_to_string('receipt.html', DATA) html = HTML(string=html_string) result = html.write_pdf() f = open(str(os.path.join(MEDIA_URL + "invoice_receipt/", 'temp.pdf')), 'wb') f.write(result) file_obj = File(open(MEDIA_URL + "invoice_receipt/" + "temp.pdf", 'rb')) transaction.receipt_file = file_obj transaction.save() receipt.html template: <style> table tbody tr td{ border-top: unset !important; } table tbody tr:nth-child(7) td, table tbody tr:nth-child(8) td, table tbody tr:nth-child(9) td, table tbody tr:nth-child(10) td, table tbody tr:nth-child(11) td, table tbody tr:nth-child(12) td { padding-top: 0; padding-bottom: 0; } .amount-in-words{ border-bottom:3px solid black; } .table thead th { vertical-align: bottom; border-bottom: 4px solid black; } /* .invoice-template{ padding: 20px; border: 20px solid transparent; border-image: linear-gradient(to right,#633363 50%,#f3c53d 50%); border-image-slice: 1; } */ .logo{ margin-top: 2rem; } .logo2{ margin-top: 2rem; height: 160px; width:200px; } .invoice-template{ padding: 20px; background-image: url('https://dev-api.test.com/files/files/DumpData/Frame.png'); background-repeat: no-repeat; background-size: contain; break-inside: auto; } .main-container{ border: 1px solid black; padding: 20px 10px; background: white; } p … -
Form is not valid Django
I am a beginner in Django/Python and whenever I try to submit my form the is_valid() method returns false. I have tried to display the errors using form.errors but it returns nothing or {}. When i try running the following code: form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] I get [('', []), ('Required', [])] form.py class ApplicationForm(forms.ModelForm): email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) required = forms.ModelMultipleChoiceField(queryset=Requirements.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Requirements fields = ['email', 'required'] views.py def application_form(request): try: form = ApplicationForm() context = {'form': form} if request.method == 'GET': return render(request, 'requirements/job_specs.html', context) if request.method == 'POST': print(form.is_valid(), form.errors) if form.is_valid(): form.save() return JsonResponse({'created': True}) form.non_field_errors() field_errors = [(field.label, field.errors) for field in form] print(field_errors) return JsonResponse(form.errors.as_json(), safe=False) except Exception as e: print(e) form = ApplicationForm(request.POST or None) context = {'form': form} return render(request, 'requirements/job_specs.html', context) HTML <form method="POST" id="application-form"> {% csrf_token %} {{ form }} <div class="bg-light row" > <div class="" id="btn-box"> <div class="col-md-12 d-grid gap-2 col-6 "> <button type="submit" class="btn btn-primary btn-lg">Save</button> </div> </div> </div> </form> I have tried to apply solutions from similar posts such as Django forms is not valid or Django forms is … -
Django automatically resubmitting the form on refreshing the page
Whenever I fill the form then I click on submit button of the form to store it in the database it stored the data perfectly but when I refresh the page it again submits. So the problem is it is showing the same data multiple times in the database. Here is my Django Template code <h4 class="text-center alert alert-success">Add New Students</h4> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="Submit" class="btn btn-success" value="Add"> How can I tackle this ? Here is my view function def add_show(request): if request.method == 'POST': fm = StudentRegistration(request.POST) if fm.is_valid(): nm = fm.cleaned_data['name'] em = fm.cleaned_data['email'] pw = fm.cleaned_data['password'] reg = User(name=nm, email=em, password=pw) reg.save() fm = StudentRegistration() else: fm = StudentRegistration() stud = User.objects.all() return render(request, 'enroll/addandshow.html', {'form': fm, 'stu':stud}) -
Django pagination Listview inside a Detailsview
i'm trying to call listview inside a detailview of two different models and i want pagination of listview but passing paginate_by seem it dosent work, how have to do to? class TagsDetailView(DetailView): model = Tag paginate_by = 50 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) IL = ItemsListView(tag=tag.tag, paginate_by=8) setattr(IL, 'paginate_by', 8) context['test'] = IL.get_queryset() print(context['test']) return context -
Time out error while sending email in django
Below configs added in my settings.py, since there is no password or user name is required for this email settings, I haven't added the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings.py file EMAIL_HOST = 'sample.outlook.com' EMAIL_PORT = 25 EMAIL_USE_TLS = True FROM_EMAIL = 'no-reply@sample.com' when I tried to execute the below comments from shell from django.core.mail import send_mail send_mail("test sub","test_msg","no-reply@sample.com",["ajith@gmail.com"]) getting the below error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/.local/share/virtualenvs/paralel-P-lwtg7n/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 807, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out -
Django: authenticate & login function works but user isn't actually logged in
i have a problem related to logging a user in in Django. in the lines of code below, i have tried to use the login function to log the user in, but when the user gets to the main page the page tells them to log in (meaning that django told me that they're not authenticated); the login function doesn't raise any errors at all. login/login.py def login_user(request): if request.method == "POST": form = forms.Login(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] db_user = AuthBackend().authenticate(request, username=username, password=password) if db_user is not None: login(request, db_user, backend="django.contrib.auth.backends.ModelBackend") return HttpResponseRedirect(reverse("main:index")) else: return render(request, "login/login.html", {"form": form, "error": "Incorrect"}) else: return render(request, "login/login.html", {"form": form}) return render(request, "login/login.html", {"form": forms.Login()}) main/templates/main/index.html <!DOCTYPE html> <html> <head> <title>Timeline</title> </head> <body> {% if user.is_authenticated %} <a href="{% url 'account' %}">Account</a> {% else %} <a href="{% url 'login:login' %}">Log In</a> {% endif %} </body> </html> also, im very new to stack and making questions, so if i have to provide other info i would appreciate the reminder and ill try to be helpful as possible. thanks -
What is the best way to transfer large files through Django app hosted on HEROKU
HEROKU gives me H12 error on transferring the file to an API from my Django application ( Understood its a long running process and there is some memory/worker tradeoff I guess so. ) I am on one single hobby Dyno right now. The function just runs smoothly for around 50MB file. The file itself is coming from a different source ( requests python package ) The idea is to build a file transfer utility using Django app on HEROKU. The file will not gets stored in my app side. Its just getting from point A and sending to point B. Went through multiple discussions along with the standard HEROKU documentations, however I am struggling in between in some concepts: Will this problem be solved by background tasks really? ( If YES, I am finding explanation of the process than the direct way to do it such that I can optimise my flow ) As mentioned in standard docs, they recommend background tasks using RQ package for python, I am using Postgre SQL at moment. Will I need to install and manage Redis Database as well for this. Is this even related to Database? Some recommend using extra Worker other than … -
Django. How to filter posts with a date less than the current post?
I'm new to programming. And I don't understand methods. On the detailview post page I want to display a list of the next posts (i.e. whose time is less than the time of the current post) How do I access the date of the current post? I try: class PostDetailView(DetailView): model = Post slug_field = 'url' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['earlier_posts'] = Post.objects.filter(publication_date__lte=self.publication_date) return context Then I have an error: 'PostDetailView' object has no attribute 'publication_date' Thank you in advance -
Put Query Parameters in url request Django
I have a query that retrieves all the data but I would like to make another query with another url by adding query parameters in order to target my data search. For example when I request the following url: http://localhost:8000/api/calendars I have this result: [ { "id": 1, "plant_step_id": [ { "id": 3, "plant_id": { "id": 1, "name": "Agropyre" }, "step_title": "Sowing" } ], "start": [ 1 ], "end": [ 3 ] }, { "id": 2, "plant_step_id": [ { "id": 6, "plant_id": { "id": 6, "name": "Aubergine" }, "step_title": "Planting" } ], "start": [ 6 ], "end": [ 7 ] } ] And I would like by requesting this url: http://localhost:8000/api/plant/life/calendars?plant_id=1&step_title=Sowing I would like to have the data concerning what I requested in the url. I tried to achieve this in the view but didn't work. Here is the model: from django.db import models from multiselectfield import MultiSelectField MONTHS = ( (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ) class PlantLifeCalendar(models.Model): plant_step_id = models.ManyToManyField('perma_plant_steps.PlantStep') start = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) end = MultiSelectField(choices=MONTHS, max_choices=3, max_length=6) Here is the serializer: class PlantSerializer(serializers.ModelSerializer): class Meta: model … -
mod_wsgi-express causing ModuleNotFoundError: No module named "mod_wsgi.server"
I'm trying to deploy the Django 3.2 project with Python 3.10 on CentOS 7 but I am facing issues in it. I'm trying to run the following command to run mod_wsgi-express: mod_wsgi-express start-server django_wsgi.py --server-root /var/www --user apache --group apache --port 80 --host XYZ where XYZ is the IP of the machine i'm running this command on. I had to specify a different server root as my /tmp is noexec. The contents of django_wsgi.py are: import os import sys project_dir=os.path.dirname(__file__) if project_dir not in sys.path: sys.path.append(project_dir) from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'MY_PACKAGE_WHERE_SETTINGS_ARE.settings' application = get_wsgi_application() but I keep getting this error: [mpm_event:notice] [pid 101737:tid 139778434865344] AH00489: **Apache/2.4.52 (codeit) mod_wsgi/4.9.0 Python/3.10** configured -- resuming normal operations [core:notice] [pid 101737:tid 139778434865344] AH00094: Command line: 'httpd (mod_wsgi-express) -f /var/www/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_WITH_LISTENER_HOST -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' mod_wsgi (pid=101741): Exception occurred processing WSGI script '/var/www/handler.wsgi'. [wsgi:error] [pid 101741:tid 139778434865344] Traceback (most recent call last): [wsgi:error] [pid 101741:tid 139778434865344] File "/var/www/handler.wsgi", line 7, in <module> [wsgi:error] [pid 101741:tid 139778434865344] import mod_wsgi.server [wsgi:error] [pid 101741:tid 139778434865344] ModuleNotFoundError: No module named 'mod_wsgi.server' The error says "handler.wsgi", I don't know if that is correct or it is not accepting my …