Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Employee Leave types conditions in DJango rest framework
I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me. If employee select Cl, he got total 12 cl and he can avail monthly once and cl can carryforward upto 3 leaves after that it will expire, then sl means quarterly 2 available, then half day leaves, what will be the logic here and how should i progress? class LeaveType(models.Model): Leave_type = ( ('CL', 'Casual Leave'), ('SL', 'Sick Leave'), ('ML', 'Medical Leave'), ('Comp Off', 'Compensation'), ('L.O.P', 'Loss of Pay') ) Leave_Choice = ( ('Full Day', 'Full … -
docker forgets to install dependency from requirements file
I am trying to troubleshoot a tutorial on udemy on Windows 10 but when I run my containers the django app does not seem to want to load celery as a module. I tried a few different versions but still get the same error message. The celery worker seems fine. Does anyone here see my issue and help me understand what is happening? The tutorial's original code is here on his github but most of my code is a straight copy from him. Here is a link to the repo of what I have covered so far. error message: postgres | 2022-11-14 03:17:27.850 UTC [1] LOG: database system is ready to accept connections flower | PostgreSQL is ready!!!!.....:-) celery_worker | PostgreSQL is ready!!!!.....:-) django-api | PostgreSQL is ready!!!!.....:-) django-api | Traceback (most recent call last): django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv django-api | self.execute(*args, **cmd_options) django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute django-api | output = self.handle(*args, **options) django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 86, in wrapped django-api | saved_locale = translation.get_language() django-api | File "/usr/local/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 254, in get_language django-api | return _trans.get_language() django-api | File "/usr/local/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ django-api | if settings.USE_I18N: django-api | … -
django rest_framework with basic auth, how to consume api with django
I created an API with basic authentication and I was wondering how can i consume it with an username and password this is my endpoint http://127.0.0.1:8000/Clerk/ I try to consume it by def display_clerk_view(request): displaytable = requests.get('http://127.0.0.1:8000/Clerk/') jsonobj = displaytable.json() return render(request, 'clearance/clerk_view.html', {"ClerkClearanceItems": jsonobj}) this block of code and it's giving me error Unauthorized: /Clerk/ I'm planning to use django all-auth with google as provider but for now I want to know how consuming api with authentication works -
django summernote to aws3 connection problem
django summernote can be uploaded and shown locally, but if i connect summernote aws s3, it will be uploaded, but the image cannot be imported. Does anyone know? -
Filter dropdown in django forms
In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part. class InfringementForm(ModelForm): def __init__(self, user, *args, **kwargs): super(InfringementForm,self).__init__(*args, **kwargs) self.fields['marketplace'].queryset = Marketplace.objects.filter(groups__user=self.user) class Meta: model = Infringement class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name fields = ['name', 'link', 'infringer', 'player', 'remove', 'status', 'screenshot','marketplace'] models.py class Marketplace (models.Model): name = models.CharField(max_length=100) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) -
django deply support LANGUAGES (local vs host)
I was programming my Django site normally .. and I set some data in the database in the Arabic language it was work find in my locl pc useing pycharm editer On my local pc its looks like this: photo 1 and then I buy sharing host on Namecheap and deploy my site after entering some data into my database in the Arabic language I find it like this! photo 2 It looks like the system Namecheap does not support the language or what! -
Control the order of the database columns before proceeding to makemigrations in Django
Is there a way to control the database column ordering, directly within a Django model? I know I can manually edit the migration file after makemigrations to adapt it to my needs, but is there a way to do so, prior to the makemigrations call? This can be especially useful when initializing the database. -
I'm building a expense tracker app following a guide and the Pipenv shell command will not work!!! Python 3.11, Windows 10
As I've said I'm building a expense tracker web app. This is for my university course. I found a video series that builds one step by step. I wanted to follow this video to get a nice walk through to help me understand how to approach this task. https://www.youtube.com/watch?v=tYPx-fcICts&list=PLx-q4INfd95G-wrEjKDAcTB1K-8n1sIiz&index=2 (Link for the video for context). Anyways the video wants you to use Django and to install it I must first create a virtual environment using pipenv. I installed it and everything checked to make sure it was actually installed. But when i went to create the enviorment in the folder of the project using the "pipenv shell" command it give me an error which is "PermissionError: [WinError 5] Access is denied". For the life of me I cannot figure this out. I've been at it for hours. Please i need help on how to get this fixed as this video series is perfect for my project. I'm using python 3.11 and I'm on windows 10. I also followed the steps in the video exactly so that should give you some context. Honestly I just started coding so i really don't know what to even try. I've tried finding answers online … -
I get this error :[Errno 2] No such file or directory: 'ffprobe'
I have installed ffmpeg as a dependency in my conda env but still get this error. Can anyone help pls ? -
Create custom discord user django allauth
How can I add an element to user in the database, like when a user signs up with discord OAuth2 the database saves so little information. I want to add multiple fields to the User module in the db, but I don't want to give the user the option to input this info, like I don't want the user to give me his discord id, I want to get it from discord directly and save it to the user db Currently allauth only saves creation date, last login date, first name, username, email. I want to a lot more, I want to add discord access token, id, and much more, is there a way to add these fields to the User directly instead of creating a new module that copies User and adds the id and other fields? I have searched a lot but I couldn't really figure a way out -
React and Django: CSRF Token is not set on production, and especially for create method
on development, the csrf cookie used to be set normally if it is not in available in application tab in dev tool, however on production, whenever i try to create a new post, it tells me " CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header has incorrect length." however, the plot-twist here, is that with other post requests such as when you login, or signup, it works perfectly and fine, so i figured it seems to be a problem with create method in django (BUT with login , even though login works perfectly fine, and that i am logged in using session based authentication, it seem like session_id and csrf are invisible in application tab? I assume it is because the website is on production and for security reasons, it wont show the session_id there. However, whenever i try to look at network tab after i try to create a post and fail, it looks like x-csrftoken is undefined but, there is another key called cookie which includes both csrftoken and session_id please note that this only occur on production, i never faced such issue on development server, and look at settings.py code after the view code for more … -
How to exclude null values in queryset for charts.js
I am trying to get the count of infringements in the market place for the logged in user. The logged user is part of a group. The problem I am having is its still counting values for marketplace items that doesn't belong to the group. It adds 0 in the queryset breaking my charts, u = request.user.groups.all()[0].id mar_count = > Marketplace.objects.annotate(infringement_count=Count('infringement', filter=Q(groups=u))) The result 'Ebay','Amazon','Facebook','Wallmart', '0','0','0','0','1','1','1','1', I should be getting 'Ebay','Amazon','Facebook','Wallmart', '1','1','1','1', How do I exclude counting the marketplace when its no part of the logged in users group? I am new. Thanks -
How can i import LDAP file in Django, Python?
I can't find any function that can import an .ldif file. Does anybody know how can I read an .ldif file and parse it? Thanks. -
How to fix Cannot assign "": "" must be a "" instance? when it is created in view?
I want to create model with view when the user is created, but I got and error: Cannot assign "<User:test1234": "Customer_info.customer" must be a "Customer" instance. Here are the models that I have and which I want to be created automatically when user is registered. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) points = models.FloatField(default = 0.0) ... class Customer_info(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) deposit = models.FloatField(default = 0.0) And in views.py after registering those models are creating def reg(request): form = CreateUserForm() if "register-btn" in request.POST: form = CreateUserForm(request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) Customer.objects.create( user=new_user, points=0.0 ) Customer_info.objects.create( customer = new_user, deposit = 0.0 ) response = redirect('profile') return response return render(request, 'main.html') -
Making website responsive to devices other than desktop pc
I've been tasked to try and make my friend a portfolio website(my real first project). I think I've made a mistake of only focusing on designing for desktop and forgetting about other devices. Here's a link to the site so you can see how it is responding; https://vsworldtest.herokuapp.com/ As you can see its not responding as I would like it when loading on a mobile phone. Still some tweaks needed and some cleaning of the css for desktop but it is more than viable for testing at the moment. If you have any idea of what I could do to make this responsive for mobile devices and tablets please share with me. Code to follow: CSS <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, user-scalable=0"> <title>vstheWorld</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"/> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"> </script> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap'); * { box-sizing: border-box; } .container-top { margin: 500px; } hr { color: white; margin-bottom: 20px; } .banner-image { text-align: center; } body { {% load static %} background-image: url("{% static 'images/purple.jpg' %}"); padding: 15px; font-family: 'Roboto', sans-serif; font-weight: bold; background-repeat: no-repeat; background-size: 100% 200%; position: relative; } /* Center website */ main { max-width: 100%%; … -
How do you create a function to check the attribute of another field in a separate model?
class Trait(models.Model): name = models.CharField(max_length=20) animal_types = models.ManyToManyField(AnimalType) # slots = models.CharField(default=None, null=True, max_length=4) #slots is meant to hold a value that determines where it can be placed in animal model #i.e. null means anywhere, "2" means only trait 2 #def TraitPlace(self): def __str__(self): return self.name #need to add animal details like age and gender to a separate model or integrate/hardcode into animal model as they're only 7 options class ANIMAL(models.Model): animal_type = models.ForeignKey(AnimalType, on_delete = models.CASCADE) first_trait = models.ForeignKey(Trait, on_delete = models.CASCADE) #first trait and animal required as animals always exist and have at least one trait # second_trait= models.ForeignKey(Trait, on_delete = models.CASCADE) # third_trait= models.ForeignKey(Trait, on_delete=models.CASCADE) I've got an animal model which is used to create an animal with up to 3 traits, the problem is that some traits have specific placement restrictions, i.e. "lithe" can only be in position 3, and glistening can only be in positions 2 and 3. It was suggested to add an additional "slots" field under the trait model. I understand logically how it's supposed to work out, but am struggling with implementation. I tried to look up documentation and use hasattr under my first_trait but that didn't work or I just didn't … -
How can I show payment update for a specific appointment?
So I'm trying to make a section under each appointment details that shows their payment transactions of the appointment specifically. all my tries so far didn't work, i can only show all payment updates which is not the wanted result obviously. this is the code: views.py def appointment_details(request, id): search_patient_form = SearchPatient() current_user_phone = request.session.get('user') current_user = get_object_or_404(Doctor, phone = current_user_phone) if current_user: if request.method == 'POST': searchPatient = SearchPatient(request.POST) if searchPatient.is_valid(): patient_id_phone = searchPatient.cleaned_data['patient_id_phone'] return redirect('search_patient', id_phone=patient_id_phone) else: appointment = get_object_or_404(Appointment, id = id) updates = PaymentUpDate.objects.all() return render(request, 'about-appointment.html', { 'current_user': current_user, 'sayfa': 'appointments', 'appointment': appointment, 'updates': updates, 'search_patient_form': search_patient_form }) else: return redirect('login') models.py This is the class the makes the updates class PaymentUpDate(models.Model): payment_date = models.DateTimeField(auto_now_add=True) payment_amount = models.CharField(max_length=550) I've tried doing the same approach as I did to show a specific appointment, which is: appointment = get_object_or_404(Appointment, id = id) to the updates, which looked something like : updates = get_object_or_404(PaymentUpDate, id = id) which resulted in the following error : TypeError at /appointment-details/3 'PaymentUpDate' object is not iterable and i also tried this guide: How to show every user specific payment for them in django?, which made my code look like this: class PaymentUpDate(models.Model): … -
How can I solve this indentation problem in my Django project
I'm a beginner in Django. I was trying to add a method inside the OrderItem class. But the visual studio code is showing an indentation error. I'm not sure what is wrong here. Anyone can help me, please? The indentation error is showing on the @property and get_total() ` class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total ` Pelase see the attached screenshot. -
How to filter exported data by a value on database using django export import
I want to export a student data from my database and filter it by roles column. Views.py def export_siswa(request): user = userResource() dataset = user.export() response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Data_Siswa.xls' return response resource.py class userResource(resources.ModelResource): username = Field(attribute='username', column_name='Username') namadepan = Field(attribute='namadepan', column_name='Nama depan') namabelakang = Field(attribute='namabelakang',column_name='Nama belakang') email = Field(attribute='email',column_name='Email') jeniskelamin = Field(attribute='jeniskelamin',column_name='Jenis kelamin') tanggallahir = Field(attribute='tanggallahir',column_name='Tanggal lahir') agama = Field(attribute='agama',column_name='Agama') alamat = Field(attribute='alamat',column_name='Alamat') telepon = Field(attribute='telepon',column_name='Telepon') class Meta: model = modelUser fields = ['username','namadepan','namabelakang','email','jeniskelamin','tanggallahir','agama','alamat','telepon','role'] export_order = ['username','namadepan','namabelakang','email','jeniskelamin','tanggallahir','agama','alamat','telepon','role'] That is my code for the views and resource.py .. but they show all of the data .. i want the exported data is a student with "student" roles -
Django forms template dropdown with unique identifier for each iteration of a forloop
I am trying to generate a unique ID for each iteration of a for loop item. The item generated is a drop down menu and the number of times it s generated will depend on the number of incidents that are active. The the problem I am having is that the ID of the dropdown is the same for each dropdown menu. In this case id="id_status" when viewed via the browser page source Is there a way to generate for example id="id_status_1" for the first dropdown, then id="id_status_2" for the second one and so on? I tried to implement something with forloop.counter and also javascript's setAttribute("id", "uniqueIdentifier"), but have been racking my brain for hours now without success models.py from django.db import models ... ... class IncidentStatus(models.Model): status = models.CharField(max_length=128) def __str__(self): return self.status forms.py: from .models import IncidentStatus ... ... class IncidentStatusAssigneeForm(ModelForm): status = forms.ModelChoiceField(queryset=IncidentStatus.objects.all().order_by('status'), empty_label='Select a Status', label='') class Meta: model = IncidentStatus fields = ('status',) views.py: from .models import IncidentStatus from .forms import IncidentStatusAssigneeForm ... ... def set_status(req): all_statuses_a = IncidentStatusAssigneeForm() all_incidents = Incident.objects.all ... ... context = {'all_statuses_a': all_statuses_a, 'all_incidents': all_incidents, ....} return render(req, 'incident_main/assignee.html', context) template.html: {% for incident in all_incidents %} {{ all_statuses_a }} … -
Make an appointnment between a period of given time
I have a model Schedule, where doctor can set time of work. All appointments are gonna be for 30 min. What should I do? class Schedule(models.Model): doctor = models.OneToOneField('DoctorProfile', on_delete=models.CASCADE) WEEKDAYS = ( ('Mn', 'Понедельник'), ('Tue', 'Вторник'), ('W', 'Среда'), ('Th', 'Четверг'), ('Fr', 'Пятница'), ('St', 'Суббота'), ('Sn', 'Воскресенье'), ) weekday = MultiSelectField(max_length=5, choices=WEEKDAYS) start_time = models.TimeField() end_time = models.TimeField() -
VSCode Django HTML, JS, CSS guide for proper autocomplete and linting
I need some help here, hopefully in the proper place for this. Googled my eyes out in the last few weeks but havent come across a proper solution to configure VSCode properly. There is tons of talented coders out the who make awesome extensions, but its getting overwhelming and confusing sometimes. Im learning Python and Django, unable to have proper Linting and autocorrect to work with Django HTML. Found many bits of pieces on one or other part configurations but looking for something complete. Bootstrap, CSS, Javascript autocomplete not working when document type set to Django HTML or Django template tags not working when set to HTML. What is the best configuration for Python, Javascript, CSS, Django HTML ? I like to auto suggest of Bootstrap classes, JavaScript snippets and CSS properties but they dont work when Django HTML selected, the opposite when doc type set to HTML. Loosing my mind over this and probably need to delete all VSCode config or even the whole app and start it fresh but looking for a proper guide/tutorial to follow first.... -
Attach, display and submit forms to each product id displayed within a for loop (Django)
I am looking to integrate a form to each product, included within a loop. Each form is independent for the others: if one form is submitted, the others wont need to be. Currently the form is not validating. I think it's because I haven't managed to attach the form to the specific product id and I am not sure how to do that. When applying a form to a specific Id on a single page, I would simply proceed with def function(request, product_id). This is not an option here, as I am displaying several products on the same page. models.py class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review =models.TextField(max_length=250, blank=True) rating =models.IntegerField(choices=RATING, default=0) forms.py class ReviewForm(forms.ModelForm): venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False) class Meta: model = ReviewRating fields = ['review', 'rating','venue'] widgets = { 'venue': forms.TextInput(attrs={'class':'form-select', 'placeholder':'Enter name'}), } views.py def show_event(request, event_id): submitted = False form = '' form = 'ReviewForm' if request.method =="POST": form = ReviewForm(request.POST) if form .is_valid(): data = form .save(commit=False) data.product_id = product_id #<-- How do I define product_id? data.user_id = request.user.id data.save() else : print(form .errors) else: form = ReviewForm() event = Event.objects.get(pk=event_id) categories = Product.objects.filter(event=event_id) menu = event.product.filter(event=event_id) return render(request, 'main/show_event.html',{'event':event, 'categories':categories,'menu':menu,'form':form,'submitted':submitted}) … -
How can I download an audio mp3 file and save it?
My View: class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) data = response.json() return JsonResponse(data) My response : { "url": "https://result.s3.amazonaws.com/2022-11-13/61566981.mp3" } Not sure how to proceed here, can anyone help ?---------------------- -
Deploy django as a api url using nginx and gunicorn
I am using Django with Gunicorn and Nginx. I have a domain and i want Django to point to domain/api. I am able to point the Django to domain/api but Django complains that /api path is not found. Ideally i don't want to create /api url in django. i want domain/api to point to django home page. Below is the current nginx configuration. server { location /api { try_files $uri @proxy_api; } location /admin{ try_files $uri @proxy_api; } location @proxy_api { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_set_header X-Url-Scheme $scheme; }