Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save multiple items in same form django
let say these are the inputs of user, in my view it's well validated form.is_valid(). item code | description | unit | quantity --------------------------------------------------------------- #itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1 #itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2 #itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3 reqeust.POST.getlist('description') return a list -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3'] How can i save all the cells that the user enter to my MaterialIndent model?? just like in myview i could only save the last item only !! # models class MaterialIndent(models.Model): material_indent_id = models.AutoField(primary_key=True) date_request = models.DateTimeField(auto_now_add=True) local_code = models.CharField(max_length=10, default='Local') quotation = models.FileField(upload_to='files/', null=True, blank=True) description = models.CharField(max_length=200) unit = models.CharField(max_length=100) quantity_requested = models.DecimalField(max_digits=12, decimal_places=2) quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True) request_for = models.CharField(max_length=50) requester = models.ForeignKey(User, on_delete=models.CASCADE) priority = models.CharField(max_length=100) status = models.CharField(max_length=50, default='Store Checking') def __str__(self): return str(self.material_indent_id) # form class MaterialIndentForm(ModelForm): class Meta: model = MaterialIndent fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation'] # views def test(request): available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True) if request.method == 'POST': form = MaterialIndentForm(request.POST, request.FILES) if form.is_valid(): length = len(request.POST.getlist('local_code')) post = form.save(commit=False) for r in range(length): local_code = request.POST.getlist('local_code')[r] description = request.POST.getlist('description')[r] unit = request.POST.getlist('unit')[r] quantity_requested = request.POST.getlist('quantity_requested')[r] post.local_code = local_code post.description = description post.unit = unit post.quantity_requested = … -
DJango, custom filter with list_display custom method
I'm trying to filter by the custom method i made for language column. In admin.py i have the following; from django.contrib import admin from .models import * class MovieAdminModel(admin.ModelAdmin): search_fields= ('title_en') list_display = ('get_language',) list_filter = ('get_language') def get_language(self, obj): if obj.language==1: return 'Persian With English Subtitle' else: return 'Persian' get_language.admin_order_field = "language" get_language.short_description = "language" In list_filter i use get_language and this error is returned The value of 'list_filter[0]' refers to 'get_language', which does not refer to a Field. If i use language in list_filter , the filters shows yes or no. Filter should show either Persian With English Subtitle or Persian. How do i solve? -
Scheduling a function in python/django
I have a form and a function. The function will run in exactly 60 seconds after the form has been submitted. N.B. time.sleep() is not an option here #django #python -
CreateView doesn't save object , throws 'this field is required ' error
models.py is : class Todo(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True) title=models.CharField(max_length=200) desc=models.TextField(null=True,blank=True) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['created'] views.py is: class TaskCreate(generic.CreateView): model = Todo fields = '__all__' template_name = 'create.html' success_url = reverse_lazy('home') create.html is: <body> <a href="{% url 'home' %}">go back</a> {{ form.as_p }} <form method="post"> {% csrf_token %} <input type="submit" value="submit"> </form> </body> Whenever I submit data from create.html form it doesn't save it to the database and throws this field is required on 'user' field. How do I resolve this? -
Import Error: cannot import name 'User' from partially initialized module 'auctions.models
class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,blank=True, null=True,related_name='userComment') listing = models.ForeignKey(Listing, on_delete=models.CASCADE,blank=True, null=True,related_name="listingComment") message = models.IntegerField(max_length=200) def str(self): return f"{self.author} comment on {self.listing}" -
how to add if/else statement to base.html?
I'm trying to put the if/else statement to my base.html file. The idea is to have if/else as a part of the template that will be an extension for my HTML files. The problem is, I'm not sure what syntax would look like. Previously, I had an HTML page (called the essay-page) with some content and if/else statement hardcoded to this particular page. But I want to have if/else as a part of my template too, so I could use it with several pages. Essay-page with hardcoded if/else: {% block body %} {% if essay_found %} <article> <img src="" alt=""> <section id="location"> <h2>Other infos</h2> <address>This essay was made in <span>LOCATION</span> (ADDRESS).</address> </section> <section id="details"> <h2>What's this essay about?</h2> <p>{{ essay_description }}</p> <footer> <p>Need more details? <a href="">Please contact me</a> (but don't spam ;))</p> </footer> </section> <section id="registration"> <h2>Send me your request and job offers!</h2> FORM </section> </article> {% else %} <h2>No essay found for this slug, sorry! </h2> {% endif %} {% endblock%} now I try to put this if/else to my base.html (without a success): <main> {% block body %} {% if essay_found %} {% block article %}{% endblock %} {% else %} <h2>No essay found for this slug, … -
Orm Model coonetion to Mysql Database
I'm trying to perform insert and update operations through Django ORM into MySQL Database but I don't know how to do it. Can anyone please help me with this operation? -
Django how to send html-designed email bodies
On my Django project I am trying to send beautiful mails with colorful body and so on. My mail body constructing function looks like the following: def construct_mail_body(): user = User.objects.get(id=1) context = { 'username': user.username, } template = render_to_string('mail/mail_body.html', context=context) message = strip_tags(template) return message mail_body.html: {% load static %} <h3>Hello <span style="color: red;">{{ username }}</span>,</h3> <h3>You've successfully completed our Tutorial!></h3> <h3>Congratulations!</h3> But it doesn't work as expected. My mail bodies looks like: Body 1: Body 2 (Btw, why this happens? Why the mail is in purple?): So how to make HTML tags work properly and is it possible to add some styling properties of css? Thanks! -
What is the original purpose of Django apps? What are the use cases of Django apps?
I'm building a website that'll use a Bootstrap template similar to the image shown below. I intend to add an authentication and authorization functionality using OAuth 2. The main menu will consist of: Homepage link Statistics app link NLP app link Computer vision app link Contacts page link Login button Without using Django, the homepage would just be index.html, the Statistics app would be a statistics.html page which interacts with the backend to show some plots, the NLP app would be an nlp.html page which interacts with the backend to display some NLP processed text and so on. When using Django, how am I supposed to structure it? Should I create a separate NLP Django app, and a separate Statistics Django app and a separate Homepage Django app? I'm already surprised that I had to create an app just to be able to have a homepage, and then had to add path('', include('homepage.urls')), to urlpatterns to redirect / to the homepage app. If I use the Bootstrap template for the homepage app, then how would I share the JS files, the CSS files and other boilerplate files of the template with the other apps of my website? Once the user … -
how to trigger an event of web socket (Django Channels) whenever new object of model has been created via django signals
This is my signal @receiver(post_save, sender=ChannelGroup) def channel_list_signal(sender, instance, created, **kwargs): try: print("signals") channel_layer = get_channel_layer() print(channel_layer) channel_layer.group_send( "channellist", { 'type': 'send_notification', 'message': "Done", }) print("return 'Done'") return "Done" except Exception as e: raise Exception(f"Something went wrong in channel_list signal {e}") This is my consumer class ListChannelConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = "channellist" self.channel_layer = None self.msg = None self.channels = [] # self.connected = False async def connect(self): user_id = self.scope["url_route"]["kwargs"]["user_id"] is_user_present = await check_user(user_id) print(self.channel_layer) # group_id = sender + receiver if is_user_present: self.user_name = is_user_present.username await self.channel_layer.group_add( "channellist", "temp" ) await self.accept() channel = await get_channels(is_user_present.username) await self.send(text_data=json.dumps({ "payload": "connected", "Channels": channel }, default=str)) else: raise Exception(f"User not present in database or private chat does not exists") async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def send_notification(self, event): print(event) event_data = QueryDict.dict(event) channels = event_data.get('message') # Send message to WebSocket self.channels = await get_channels(self.user_name) await self.send(text_data=json.dumps({ "Success": "channels", "message": channels })) What i am trying to achieve is i want to trigger send_notification event whenever i create new channel in my db but when i tried so it is not working actually i try to check the what … -
Map should count distance as per current Address in Django
I am new to Django, and I want to check if the entered address should not be far more than 2 hours from the current location using Map. I am sharing the screenshot of the UI. After adding the complete address I want to check if the entered address is how much far from the current address. and gave alert if addrees is far than 2 hours. I have tried this but not working. from django.contrib.gis.measure import Distance p2 = Event.objects.get(id=3).position for event in Event.objects.all().exclude(id=3).annotate(distance=Distance('position', p2)): print('{0} - {1}'.format(event.id, event.distance.m)) -
Why this ValidationError occur when deleting objects in Django model?
As far as I know, there are two ways to delete an object in the Django admin panel: delete one by one from the screen of each record -> Screen Transition delete items selected with check boxes from the record list screen -> Screen Transition The following ValidationError occurs only when trying to delete with the second way and the object cannot be deleted. (see image below) Please tell me how to fix this error. ValidationError at /admin/my_app_name/schedule/ ['“Oct. 2, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] Below is the code that seems relevant. # models.py from django.db import models from django.utils.timezone import now class ScheduleType(models.Model): choices = ( ('normal', 'normal'), ('am', 'am'), ) schedule_type = models.CharField(max_length=32, choices=choices, primary_key=True) start_time = models.TimeField() end_time = models.TimeField() class Schedule(models.Model): choices = ( ('type1', 'type1'), ('type2', 'type2'), ) date = models.DateField(default=now, primary_key=True) is_working = models.BooleanField(default=True) schedule_type = models.ForeignKey(ScheduleType, on_delete=models.SET_NULL, null=True) service1_type = models.CharField(max_length=32, choices=choices) offer_service2= models.BooleanField(default=True) offer_service3= models.BooleanField(default=True) info = models.CharField(max_length=128, default='This is a normal day.') def __str__(self): return str(self.date) -
TypeError: unsupported operand type(s) for | [closed]
I'm getting the following linting error using Django Q objects: TypeError: unsupported operand type(s) for | The below is my code (it does work but not sure why I'm getting this linting error). Also the error disappears when I remove the third Q object. if request.GET: if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search critera") return redirect(reverse('products')) queries = Q( name__icontains=query) | Q(description__icontains=query) | Q( excerpt__icontains=query) products = products.filter(queries) -
Django + React Ecommerce project [Stripe payment connecting problem]
I've got a problem with Stripe connecting to my e-commerce website based on Django + React. I've got an e-commerce website in that I want to connect Stripe as a payment system. My website has about 200 products so I want to create a system when [Order.TotalPrice] is taken to Stripe (ofc. from the server side) and Payment is done. I care about the most trivial version of the code, because I want to add it to my website. I'aint a professionalist, so I really care of simplicity because of my skills. Thanks.! Thanks, dudes a lot! -
Django Signals pick up instances and choose the right one
I need a custom function based on date for calculations. I want to use signals for that, Plan is, When user updates a date, then the signal looks for everything what has the range of that date and uses the instances within the date range -
How can I get the data from a POST request using regular function. Django
I have this code from my views.py that working well, getting the data from my raspberry. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def overview(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) return render(request, 'myhtml') now, I'm trying to use this code in another py file, regular function in my graph. py but it's not working. It's not showing any error and not printing any. def update_extend_traces_traceselect(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) I think the request is not working in a regular function. Is there another way to get the data? -
Reverse for "" not found. "" is not a valid view function or pattern name
I am a beginner in django and while I learnin dajngo from youtube I got this problem note that I do every thing like course step by step and I searched on solution to this problem for hours and I didn't find anything. when I pass url dynamically it causes a problem "Reverse for 'room' not found. 'room' is not a valid view function or pattern name." home.html {% extends "main.html" %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h3>{{ room.id }} -- <a href="{% url 'room' room.id %}">{{ room.name }}</h3></a> </div> {% endfor %} </div> </div> {% endblock %} room.html {% extends 'main.html' %} {% block content %} <h1>Room Page </h1> <h1>{{ room_r.name }}</h1> {% endblock content %} views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. rooms = [ {'id': 1, 'name': 'lets learn python!'}, {'id': 2, 'name': 'Desgin with me'}, {'id': 3, 'name': 'Frontend developer'}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def room(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'room_r': room} return render(request, 'base/room.html',context) urls.py from django.shortcuts import … -
Django: Perform GROUP BY over a view queryset
I need to perform group by over a queryset of objects already filtered by standard django filters in order to filter by how many objects in queryset are related to same foreign key object. My code now (does not work): class CustomerTicketsViewSet(AbstractViewSet): queryset = CustomerTicket.objects.all() serializer_class = CustomerTicketSerializer def filter_queryset(self, queryset): queryset_initial = queryset queryset = super().filter_queryset(queryset) tr2smp = int(self.request.GET.get('tickets_related_to_same_topic_gte', False)) if self.action == "list" and tr2smp: queryset = queryset.values('topic_id').annotate(tickets_to_same_topic=Count('topic'))\ .filter(tickets_to_same_topic__gte=tr2smp).distinct() return queryset If I filtered over all objects, I could have used CustomerTicket.objects.values('measuring_point_id').annotate(Count('measuring_point_id')) but how can I do the same thing with QuerySet? -
Django doesn't group by if I omit order_by() clause
I was trying to find an answer for this question in documentation but I unfortunately did not succeed. In documentation it states that if I want to group my objects and Count them I should use the following: MyObject.objects.values('field_to_group_by').annotate(Count('field_to_count')) However it doesn't work. But when I add simple order_by it does: MyObject.objects.values('field_to_group_by').annotate(Count('field_to_count')).order_by() Any idea why is that? They didn't mention that in documentation. -
Create Django Team / Player where order does matter
I'm creating a database of all races that are won by Athletes of our club. Goal is to have an overview of all the races that are won, but also a per_athlete count of the wins. A person in the database can be either be an athlete or a coach, or both, but not during the same race. A race can be with 1, 2,4 or 8 persons and the order of the athletes does matter, so I therefore think that a ManyToMany field is not working (only showed up to 4). I now solved it with 8 OneToOneField's. There must always be 1 athlete, so the first cannot be blank. class Person(models.Model): letters = models.CharField(max_length=10, blank = False) name = models.CharField(max_length = 100, blank = True) tussen = models.CharField(max_length = 50, blank = True) lastname = models.CharField(max_length = 100, blank = False) starting_year = models.IntegerField(blank = True) class RaceWin(models.Model): name = models.CharField(max_length =100, blank = False) year = models.IntegerField(blank = False) month = models.IntegerField(blank = True, null = True) athlete_1 = models.OneToOneField(Person, on_delete = models.CASCADE, related_name='athlete1', blank = False) athlete_2 = models.OneToOneField(Person, on_delete = models.SET_NULL, related_name='athlete2', blank = True, null = True) athlete_3 = models.OneToOneField(Person, on_delete = models.SET_NULL, related_name='athlete3', … -
Border not rendering properly in xhtml2pdf django
Unable to render borders properly in xhtml2pdf. It is applying to individual elements. Here is invoice template for rendering:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SRS Mess | Invoice</title> <style> @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Merriweather&display=swap'); body{ font-family: 'Poppins', sans-serif; user-select: none; } /* Keeping paragraph together */ p{ margin: 0; -pdf-keep-with-next: true; } *, ::after, ::before { box-sizing: border-box; } @media (prefers-reduced-motion: no-preference) { :root { scroll-behavior: smooth; } } .container{ --bs-gutter-x: 1.5rem; width: 100%; padding-right: 7.5rem; padding-left: 7.5rem; margin-right: auto; margin-left: auto; } .text-center { text-align: center !important; } .mt-3 { margin-top: 1rem !important; } .mt-2 { margin-top: 0.5rem !important; } .text-danger { color: rgba(220, 53, 69, 1) !important; } </style> </head> <body> <div class="container mt-2 mb-2" style="background: rgb(237, 237, 255); border-top: 2px solid black; border-bottom: 2px solid black; border-left: 2px solid black; border-right: 2px solid black; border-radius: 1rem;"> <div class="text-center mt-3"> <img src="{{ST_ROOT}}/logo.png" alt="" height="200" width="200"> <p class="mt-2" style="font-size: 1.5rem; color: orange;">SRS Mess</p> <br> <p style="font-family: 'Merriweather', serif; font-size: 2rem; text-decoration: underline;">INVOICE</p> <p style="font-size: 1.5rem; font-weight:bold; color: green;">Monthly Mess subscription of Rs. {{amount}} /- </p> </div> <br> <div class="details"> <p><strong>Name: </strong>{{name}}</p> <p><strong>Email: </strong>{{email}}</p> <p><strong>Mobile: </strong>{{mobile}}</p> <p><strong>Hostel: </strong>{{hostel}} {{room}}</p> <p><strong>Branch: </strong>{{branch}}</p> <p><strong>Date: </strong>{{date}}</p> <p><strong>Time: </strong>{{time}}</p> </div> <br> <div class="subscriptions … -
What is the difference between signal and middleware in Django?
I dont understand what is the difference between this two function in Django. Both is doing something before or after request/response. Just like context switch or decorator. Can anyone tell me how to use this two Django function properly. -
How to assign a user to an employee in Django
I am a beginner in django and trying to create a web application for my task. I am trying to assign a user to every to employee. The idea is that user(in my class Employee) brings a list of user options that have not yet been assigned to the new employee to be registered My model class Employee(): name = models.CharField(max_length=100) job = models.CharField(max_length=30) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return'{}'.format(self.name,self.job,self.user) My form class EmployeeForm(forms.ModelForm): user= forms.ModelChoiceField(queryset=User.objects.filter(id=Employee.user)) class Meta: model = Employee fields = [ 'name', 'job', 'user' ] My view def register_employee(request): if request.method == 'POST': form = EmployeeForm(request.POST) if form.is_valid(): form.save() return redirect('/') return redirect('list_employee') else: form = EmployeeForm() return render(request, 'employee/employee_form.html',{'form': form}) -
The correct way of modifying data before saving a model via the admin site
Django 4.1 models.py class Video(models.Model): phrase_id = models.IntegerField(default=-1, blank=False, null=False, validators=[MinValueValidator(0)]) # This field will be read only in the admin site. # Its only purpose is to ensure cascade deletion. _phrase = models.ForeignKey("vocabulary_phrases.Phrase", on_delete=models.CASCADE, default="", blank=True, null=True) admin.py class VideoAdmin(admin.ModelAdmin): list_display = ["phrase_id", "name", ] list_filter = ['phrase_id'] readonly_fields = ('_phrase',) form = VideoForm admin.site.register(Video, VideoAdmin) forms.py class VideoForm(ModelForm): def clean(self): if ("phrase_id" in self.changed_data) and self.cleaned_data.get("phrase_id"): phrase_id = self.cleaned_data["phrase_id"] _phrase = _get_phrase(phrase_id) self.cleaned_data["_phrase"] = _phrase return self.cleaned_data class Meta: model = Video exclude = [] In the admin site a user inserts an integer for phrase_id. Then in the admin form I wanted to substitute self.cleaned_data with Phrase instance I extract from the database. Well, the problem is that after saving, _phrase field is empty. Thid is the documentation: https://docs.djangoproject.com/en/4.1/ref/forms/validation/ It reads as follows: The form subclass’s clean() method... This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data Well, I have modified the cleaned_data, but it seems to have no effect on what is saved. My idea was: data are validated before saving, substitute cleaned_data, then your own data will be saved. I seem to have been wrong. Could … -
Django button submit not work after using javascript code
This would be my Registration page. When the script html tag testscript.js code is remove or commented out, the register button works perfectly fine but when I input the testscript.js, the register button is kind of disabled. So, I think the problem is the javascript code because that's the only part of the code that blocks the function of the register button. Here's my source code: views.py: def registration(request): form = CustomUserCreationForm() print("Working Form") if request.method == 'POST': form = CustomUserCreationForm(request.POST) print("Form Submitted") if form.is_valid(): form.save() context = {'form' : form} return render(request, 'activities/index.html', context) index.html: <!DOCTYPE html> <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"> <link rel="stylesheet" href="../static/CSS/styles.css"> <link rel="stylesheet" href="../static/CSS/font-awesome/css/all.min.css"> <link rel="stylesheet" href="../static/CSS/css/bootstrap.min.css"> <script src="../static/Javascript/js/jquery.min.js"></script> <title>Document</title> </head> <body> <!-- Header --> <div class="site-header" > <nav class="navbar fixed-top navbar-expand-lg navbar-dark index__navbar scrolled"> <div class="container-fluid"> <div> <img class="navbar-icon" style="margin-left:15px;" src="../static/Media/avatar.png" alt="dasma-logo"> <span id="hideHomeTitle" class="brand__name" style="color:#2c5f2dff;">Preschooler Profiling and Monitoring</span> </a> </div> </div> </nav> </div> <!-- Form --> <div class="container-fluid" id="homeBody"> <br> <div class="form"> <div class="form-toggle"></div> <div class="form-panel one"> <div class="form-header"> <h1>Login</h1> </div> <div class="form-content"> <form action=""> <div class="form-group"> <label for="">Username</label> <input type="text" id="username" name="username"> </div> <div class="form-group"> <label for="">Password</label> <input type="password" id="password" name="password"> </div> <div class="form-group"> <label …