Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Attribute Error - 'ForwardManyToOneDescriptor' object has no attribute 'courses'
I have created different models and in the Division model I am taking reference of many models and their primary key is referenced as a foreign key in Division Model. I have declared courses as a model attribute in the Batch Model. This is my models.py file class lab_load(models.Model): lab_code = models.CharField(max_length=10,null=True) subject_name = models.CharField(max_length=100,null=True) subject_abv = models.CharField(max_length=10,null=True) lab_load = models.IntegerField(null=True) semester = models.IntegerField(null=True) max_numb_students = models.CharField(max_length=65,null=True) instructors = models.ManyToManyField(Instructor) def __str__(self): return f'{self.lab_code} {self.subject_name} {self.subject_abv}' class Batch(models.Model): bat_name = models.CharField(max_length=50) courses = models.ManyToManyField(lab_load) @property def get_courses(self): return self.courses def __str__(self): return self.bat_name class Division(models.Model): division_id = models.CharField(max_length=25, primary_key=True) batch = models.ForeignKey(Batch, on_delete=models.CASCADE,blank=True, null=True) num_lab_in_week = models.IntegerField(default=0) course = models.ForeignKey(lab_load, on_delete=models.CASCADE, blank=True, null=True) lab_time = models.ForeignKey(LabTime, on_delete=models.CASCADE, blank=True, null=True) room = models.ForeignKey(LabRoom,on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, blank=True, null=True) def set_labroom(self, labroom): division = Division.objects.get(pk = self.division_id) division.room = labroom division.save() def set_labTime(self, labTime): division = Division.objects.get(pk = self.division_id) division.lab_time = labTime division.save() def set_instructor(self, instructor): division = Division.objects.get(pk=self.division_id) division.instructor = instructor division.save() My views.py file class Data: def __init__(self): self._rooms = Room.objects.all() self._meetingTimes = MeetingTime.objects.all() self._instructors = Instructor.objects.all() self._courses = Course.objects.all() self._depts = Department.objects.all() self._labrooms = LabRoom.objects.all() self._labTimes = LabTime.objects.all() self._labcourses = lab_load.objects.all() self._bats = Batch.objects.all() def get_rooms(self): … -
Problem with audio in Django,<audio> doesn't work
I want to do audio-player in Django,but i have some problems. Here is my models.py class Music(models.Model): name = models.CharField(max_length=50) author = models.CharField(max_length=100) audio_file = models.FileField(upload_to='D:/pythonProject/music/player/templates/music/', blank=True) def __str__(self): return f"{self.author}---{self.name}" views.py def main_page(request): music_list=Music.objects.all() return render(request, 'player/main_page.html', {'music_list': music_list}) and template {% if music_list %} {% for music in music_list %} <audio controls> <source src="{{music.audio_file}}" type="audio/mpeg"> </audio> {% endfor %} {% endif %} When i started my page,i have this : main_page Also,i have "GET / HTTP/1.1" 200 169" in my terminal. Can someone help me with this? Thank!) -
Choice Field Instance Not Displaying Correct Data But Other Fields Are
I am trying to display a ModelForm with prepopulated instance data. It works fine except for the ChoiceField which always displays the first choice given in forms.py ('LP') rather than the choice provided by the instance. View: def review(request): order = Order.objects.get(user__pk=request.user.id) form = ProjectReviewForm(instance=order) context = { 'form': form, } return render(request, 'users/projectreview.html', context) Forms: class ReviewForm(forms.ModelForm): LAND = 'LP' // #INSTANCE ALWAYS SHOWS THIS RATHER THAN INSTANCE DATA DATA = 'DC' STATIC = 'SW' CHOICES = ( (LAND, 'LP'), (DATA, 'DC'), (STATIC, 'SW') ) product = forms.ChoiceField(choices=CHOICES, widget=forms.Select(attrs={'class': 'form-field w-input'}),) class Meta: model = Order fields = '__all__' template: <form method="POST" class="contact-form"> {% csrf_token %} <h2 class="form-heading-small">Please make sure everything you've submitted is correct.</h2> {{ form }} <button type="submit" data-wait="Please wait..." class="button w-button">Looks good!</button> </form> -
Static media images are not displaying in Django
I am working on an online bookstore app. I have a book details page that displays book information in a table, including the book cover image. I am having an issue where the images display correctly when I runserver, however a team member is unable to get the images to display after pulling my code from Github. **all books template:** {% extends 'bookstore/main.html' %} {% load crispy_forms_tags %} {% load static %} from .models import Product {% block content %} <div class="container"> <p> <h1 style="text-align:center;color:green;"> GeekText Complete List of Books<br> </h1> <h3 style="text-align:center;color:green;"> Click the Book Name for More Details </h3> </p> <!-- Bootstrap table class --> <div class="container"> <div class="col-md-12"> <table id="myTable" class="table table-striped tablesorter"> <thead> <tr> <th scope="col">ID #</td> <th scope="col">Book Title</td> <th scope="col">Genre</th> <th data-sorter="false" scope="col">Cover Image</td> <th scope="col">Author</td> </tr> </thead> <tbody> {% for item in items %} <tr> <td scope="row">{{ item.id }}</td> <td><a href="{% url 'book_details_with_pk' id=item.id %}">{{ item.name }}</a></td> <td>{{ item.genre }}</td> <td><img src="{% static item.image %}" width="75" height="100"/></td> <td>{{ item.author }}</td> <td><a href="{% url 'addtocart' item.id %}" class="btn btn-primary">Add To Cart</a> </tr> {% endfor %} </tbody> </table> {% endblock %} </div> </div> </div> **views.py** from django.shortcuts import render, redirect from django.db.models import Q from … -
Which framework could adapt Graphql more better (Django , Flask or FastAPI)?
I have a project which is to build a server-side backend application using Graphql. I have told just to build api endpoints using python(on any of the framework). So I decided to implement graphql . I am having a issue to select between (Django , Flask and FastAPI). So, which framework could adapt the graphql environment in more efficient way(Django , Flask or FastAPI) ? Speed of api also matters alot because real time will transfer . -
Extract title from a webpage using Python
I want to extract title from a webpage using Python. I followed the instructions in below link and got the title of most websites. https://www.geeksforgeeks.org/extract-title-from-a-webpage-using-python/ # importing the modules import requests from bs4 import BeautifulSoup # target url url = 'https://www.geeksforgeeks.org/' # making requests instance reqs = requests.get(url) # using the BeaitifulSoup module soup = BeautifulSoup(reqs.text, 'html.parser') # displaying the title print("Title of the website is : ") for title in soup.find_all('title'): print(title.get_text()) But I can't get title of website 1688.com. Example: https://detail.1688.com/offer/629606486448.html Can you help me to get the title of this page? Thanks! -
Why does template see only one file in static?
I am trying to display a photo. Created new folder 'img' in static, but the template does not see new folder, it sees only old one. Or when I add new files in the old folder it does not see it. Could not find the problem. Maybe it should be updated somehow? -
Post fullcalendar calendar.getevents() array object to bakend
When I try to send fullcalendar events to my Django backend, it seems that ajax is not sending the proper data... How can I send those events to the backend properly? I am using jquery ajax, here is my code: $.ajax({ url: '/home/update_event/', method: 'POST', data: calendar.getEvents(), success: (e)=>{ $('#information').text('Your event is saved') } }); -
Django admin action not repeating
I have the following Admin action (in my admin.py file) which in designed to download pdf files for selected items. It seems to be working apart from the fact that it will only create and download a pdf for the first item in the queryset. I think the problem lies in the 'return response' line but I don't know what else to use in its place. Any input would be great, I'm stomped! @admin.register(ReleaseForm) class ReleaseAdmin(admin.ModelAdmin): def participant(self, obj): return str(obj.customer.last_name) + ", " + str(obj.customer.first_name) def training(self, obj): return str(obj.order.training_registered.name) def print_release(self, request, queryset): updated=queryset.count() print (updated) for obj in queryset.all(): customer=obj.customer order=Order.objects.get(customer=customer) firstname = obj.customer.first_name lastname = obj.customer.last_name nwta = order.training_registered.name data = {'order':order,'firstname': firstname, 'lastname': lastname, 'nwta':nwta,} pdf=release_render_to_pdf('accounts/pdf_template.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Release_%s_%s.pdf" %(lastname,nwta,) content="attachment; filename=%s" %(filename) response['Content-Disposition'] = content print(obj.customer) return response self.message_user(request, ngettext( '%d Relase Form was successfully printed.', '%d Relase Forms were successfully printed.', updated, ) % updated, messages.SUCCESS) print_release.short_description="Print Release Form(s)" list_display = ('participant','release_status','release_date_submitted' ,'note' ) actions = ['print_release'] ordering = ('customer',) list_filter = ('customer__order__training_registered__training__name','customer__order__training_registered', 'customer__order__regstatus','release_status','release_date_submitted' ,'note') search_fields = ('participant','note') -
How to Deploy Django website to GCP Cloud Run using VS Code
I need guidance to deploy my existing django website which is in my windows machine to Google Cloud Platform's Cloud Run using VS Code. I saw there's a documentation related to it but I'm not able to understand what all to change in my django's settings.py and how will the database would be configured. Please guide me as what all should I change to my django app so that I can deploy it through my VS Code. -
Domain Not Getting Linked to Amazon AWS fby Django Nginx
I have used this tutorial - https://dev.to/subhamuralikrishna/deploying-django-application-to-aws-ec2-instance-2a81 ( I changed the os to ubuntu from ami and I skipped the database part as I wanted it to be db.sqllite3 only. I bought my domain from Hostinger- gyanism.in and gyanism.xyz . i Created two ec2 instances for each domain following the same procedure and both of them didn't work. After hosting with nginx they both show only loading but they never load. I changed the nameservers properly and it has been more than one day now but the site doesn't seem to load either. I am attaching screenshots of the rest details - Hostinger nameservers spec for gyanism.in -- Route 53 Spec - My server file in etc/nginx/sites-available - my server file in etc/nginx/sites-enabled - Nginx is working fine and gunicorn is working fine too. But on domain the site is not showing! Please Help urgently -
Django. Remind to email events
I'm new to django, and I need to create a browser-based event reminder application and an email that I will write in the application. Is it possible to do this on pure django, or do you need something to use in addition. In which direction should I look for information? -
Update multiple objects in django rest
I have blogs and I do reorder. When I send multiple objects by postman and then update and save by loop I get an error. These are the objects of what i send -> [ { "id":18, "name": "a", "is_active": true, "author_name": 1, "category": 1, "tag": [1,2], "order": 888888 }, { "id": 17, "name": "a", "is_active": true, "author_name": 1, "category": 1, "tag": [ 1 ], "order": 999999999 } ] but i have this error -> { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } this is my code- > serializer.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ['id', 'name', 'is_active', 'author_name','category','tag','order'] extra_kwargs = { 'is_active': {'read_only': True}, 'id':{"read_only":False} } view.py class UpdateOrder(generics.UpdateAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() def put(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) for i in serializer.validated_data: blog = Blog.objects.get(id=i["id"]) serializer = BlogSerializer(instance=blog, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() -
How to filter foreign key field by text input in django-filter
I have a City model which contains names of all cities of my country. Also I have Post model with foreign key set to City model. And I created filter to let user filter Posts by city name: class PostFilter(django_filters.FilterSet): class Meta: model = Post fields = ['city'] And the problem is that, basically foreign key field contains id of related object and filter will find nothing if user inputs actual city name. So, how do I make it so that when user enters city name, it actually works? -
Create Custom Model for Permission and Roles in Django
I want to create Custom Permissions and Role Tables so that i can list/update user's permissions and roles from the front end using DRF. I don't want to use Django Admin panel to do that. I have Created the models as seen in the below image. Now how do i use them for authentication -
django logging - can't print logs to file
I'm trying to setup Logging in my Django project... my first attempt, supposedly very simple, has been a failure so far. This is my LOGGING in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { # 'special': { # '()': 'project.logging.SpecialFilter', # 'foo': 'bar', # }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', # 'filters': ['special'] }, 'file':{ 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': './logs/log_file1.log', 'formatter': 'verbose', }, 'apps_handler':{ 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': './logs/apps_logs.log', 'formatter': 'verbose', } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, **'Equipment': { 'handlers': ['console', 'apps_handler'], 'level': 'INFO', # 'filters': ['special'] }** } } As suggested here: Django: logging only for my project's apps I'm trying to isolate my apps' logs in a separated file, and since my app is named Equipment I made the Equipment logger As a first try in my Equipment app in the views.py file I tried this: **import … -
write script in django template
I have a database of ads and want to show them in a template. The datetime of these ads are in the milliseconds since epoch format and must be converted to the 'a time ago' format. I wrote this code in views.py and working well for just one ads. How can I change that to working for all ads in database? class crawler(generic.ListView): paginate_by = 12 model = models.Catalogue template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) for cat in models.Catalogue.objects.all(): if cat.source_id == 3: date = float(cat.datetime) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') context['time_ago'] = time_ago return context How can I write this code in script? -
How to get appended/prepended element value in Django POST.?
I have a form in which initially 3 fields are there, 'Job Category', 'Manpower Quantity and 'Country'. I am using Jquery to prepend elements more than 4 times. Now I want to fetch the prepended elements values using the Django POST method. Plz, help me as i am new in Django. Thanks in advance. -
How can i regroup some columns in django?
Here is my view : clients = models.Client.objects.all() sellin = models.Sellinvoice.objects.filter(client_id__in = clients) It is my template: <table> <tr> <th>ClientName</th> <th>Price</th> </tr> {% regroup sellin by client.name list %} {% for cl in list %} <tr> <td>{{ cl.grouper }}</td> <td>{{ cl.client.price }}</td> </tr> {% endfor %} </table> Result is: ClientName Price (if user have two invoice this column added automatically) john doe 30000 30000 (problem) maria 12000 david 43000 Some user have two invoice and I can regroup ClientName but how can regroup Prices? -
My docker image in google cloud run doesn't read css file
I create my website with Django composed with docker. GitHub is here . When I compile this docker image, the app shows a webpage with CSS, on the other hand when I deploy this docker image on the google cloud run then it shows only HTML file, I mean it doesn't include CSS file so that it shows just text. Does anyone know why this happened? If someone knows, please let me know the ways to show my website with styles. -
Attach information from another model to a model with Django
On my Django chat application, users have access rights to a Company and access rights to some chat rooms of this company. They need a Company access right to be granted access to a chat room. When a user connects to a room, I would like to display in a column all users which have a company access right for the related company and for each of those if they have an access to the chat room (checkboxes) so that users can easily be added or removed from the chatroom by clicking on the checkbox. To display this list of users, I can manually build a Python object with all company access rights, and for each of those add a field indicating if the person also has access to the room. Isn't there a pure Django way to do that ? Here are my models: class CompanyAccessRight(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name="accessrights") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="authorizedpeople") class Room(models.Model): acessrights = models.ManyToManyField(CompanyAccessRight, through='RoomAccessRight') class RoomAccessRight(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='accessrightsforroom') accessrights = models.ForeignKey(CompanyAccessRight, on_delete=models.CASCADE, related_name='chatarforcompanyar') -
Stock Code Generator with Django & Database
I am coding a program for the my company about the automatic stock code generator webservice. Normally, i am taking the stock codes from the excel file, but at the moment i am going to use a postgresql database. Our company stock code's has meaningful number(if material is Black code is like this "Black.1", if its also has different color it's like this "White.1" I have started a app with Django and i have created this script's models. But i can't understand how can i proceed. Thanks in advance. -
How we use AJAX in Django to send video file of script.js to views.py?
This is Script.js downloadButton.addEventListener('click', () => { const blob = new Blob(recordedBlobs, {type: 'video/mp4'}); const url = window.URL.createObjectURL(blob); a.style.display = 'none'; a.href = url; a.download = 'test.mp4'; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 100); /* On submiting the form, send the POST ajax request to server and after successfull submission display the object. */ $("#downloadButton").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type: 'POST', url: "{% url 'post_video' %}", data: serializedData, success: function (response) { // on successfull creating object // 1. clear the form. $("#downloadButton").trigger('reset'); }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) }) }); Views.py def Video_Recording(request): return render(request, "HafrApp/Start_Interview.html") def post_video(request): print('hy') # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": form = FriendForm(request.POST) fs = FileSystemStorage() filename = fs.save(form.name, form) print('hy') return JsonResponse({"error": ""}, status=400) Urls.py path('post/ajax', views.postFriend, name = "post_friend"), path('Start_Interview', views.Video_Recording), Start_Interview.html <!DOCTYPE html> <html> <head> <title>Media Recorder in Javascript</title> {% load static %} <link rel="stylesheet" href="{% static 'Candidate/main.css' %}" /> </head> <body> <div … -
Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance
I'm working on a project "Beauty Parlour Management System" and I got this error (Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance.) anyone here can help me, please. When I am filling a book appointment form then I got this error. models.py class Service(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) image = models.ImageField(upload_to='uploads/productImg') class Appointment(models.Model): your_name = models.CharField(max_length=100) your_phone = models.CharField(max_length=10) your_email = models.EmailField(max_length=200) your_service = models.ForeignKey('Service', on_delete=models.CASCADE, default=1) your_date = models.DateField() views.py def appointments(request): if request.method == 'GET': return render(request, 'core/bookappointment.html') else: your_name = request.POST.get('your-name') your_phone = request.POST.get('your-phone') your_email = request.POST.get('your-email') your_service = request.POST.get('your-service') your_date = request.POST.get('your-date') details = Appointment( your_name = your_name, your_phone = your_phone, your_email = your_email, your_service = your_service, your_date = your_date) details.save() return render(request, 'core/appointments.html') -
Why does .gitignore downloads files during pull and creating conflicts when modified?
So this problem is at two fronts. One locally and one on ec2 instance where I'm trying to pull from github. I force pushed (git push origin main -f) from local to github with all folders and files. I pulled it on server using git pull origin main. Then I added static_files/ and .env to my .gitignore locally and got it committed and git push origin main. Now I deleted static_files folder and .env from github. So the first problem is when I now take a git pull origin main, it deletes the folder and .env. Secondly, I modified .env and .gitignore on my server using sudo nano but even when .env is ignored it shows conflicts during git pull origin main as, CONFLICT (content): Merge conflict in .gitignore CONFLICT (modify/delete): .env deleted in 6d0cc45a49f2faf3bbbacd and modified in HEAD. Version HEAD of .env left in tree. Automatic merge failed; fix conflicts and then commit the result.