Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to place a button in each row of table in django management form
In my Django application, I have a form with Parent/Child model objects laid out using loop. To dynamically add child form instances, I am using Django dynamic formset. Every thing works fine including saving of user inputs without hassle. So far, so good. However, now my user wants that I place one button before a particular field (spl_instructions) in each of the dynamically rendered rows (of fields). The instant field spl_instructions (of the child table) is a CharField of 255 chracters and is being rendered as Textarea in the page. The "button" is intended to be used to open the field spl_instructions if and when there is a need to enter text in the field. This route is being taken to conserve space. models.py class ProductAssy(models.Model): prod_assy_id = models.AutoField(primary_key=True, ...) prod_assy_num = models.CharField(max_length=24, ...) prod_assy_type = models.ForeignKey(MaterialType, ...) short_text = models.CharField(max_length=55, verbose_name="Description") # ... Rest of the fields class BillOfMatlItems(models.Model): bom_item_id = models.AutoField(primary_key=True, ...) prod_assy_id = models.ForeignKey(ProductAssy, ...) short_text = models.CharField(max_length=55, verbose_name="Description") spl_instructions = models.CharField(max_length=255, ...) # ... Rest of the fields forms.py class CreateProdAssyForm(forms.ModelForm): class Meta: model = ProductAssy fields = (...) class CreateAssyBomForm(forms.ModelForm): class Meta: model = BillOfMatlItems fields = (...) widgets = { 'short_text': forms.TextInput(attrs={'style': 'width:300px; text-align:right;'}), … -
Django use context variable passed from view in the url pattern
I have a view function passing in an integer as a context and renders a HTML file. def youtube(request, gateid=0): print(gateid) return render(request, "streamapp/youtube.html", {'gateid': gateid}) Inside the HTML file called youtube.html, I want to use this argument gateid inside a URL pattern which calls in another view. existing code: <a href='{% url 'video_feed' gateid=0 %}' /> So instead of hard coding the gateid=0 to zero in the above <a /> tag, I wanna make use of the context variable passed, how do I do that? -
Problems to load an image from my context in django
{% load static %} I want to load an image from my static files but the name of the image depends of my context The data come from Open Weather map API -
How to get time slot in django for doctor appointment
I have 2 models Schedule and Appointment.How can i get the duration of doctor in a diffrent time slots for 15 minutes.I am getting blank in this models. class Schedule(models.Model): doctor=models.ForeignKey(Doctor) open=models.TimeField() close=models.TimeField() class Appointment(models.Model): patient=modles.ForeignKey(Patient) doctor=models.ForeignKey(Doctor) date=models.DateField() time_slot=models.TimeField() -
What's the most pythonic way to parse multipart/form-data with array-like name structure in Django?
I have a structure like this: ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[4]" message ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[5]" message ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[6]" message How should I parse it to have an array of messages to parse it further? I use Django and I suppose I should use Django forms to do this but I've not seen anything regarding this in the docs or here on this site. -
Django ORM. How to distinguish, recognize or identify objects from each other
As title describes, I want to distinguish objects from each other. For example, I have Application objects and AdmissionBase objects. Application is an application for student to apply to university, whereas AdmissionBase is financial base to apply - paid, grant, financial support etc. How can I distinguish grant base from paid and financial support and vice versa without querying by their name attribute (the project must support i18n)?. Their name values might change some time later. My current solution is that I use code attribute which is in every reference object. There are written human-readable constants for admission bases, like PAID, GRANT or F_SUP. This might be good solution, but the project is for several universities. Which means entering on each university owned server updating code attribute to several objects (other classes use the same code attribute, it comes from abstract base class) plus such objects come from other APIs (government APIs) that do not contain code attribute. Here is the code so you can understand class AbstractReference(models.Model): uid = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=128) # in this attribute human-readable constants are written code = models.CharField(max_length=128) class Meta: abstract = True # this is used just a reference in … -
Comment inside of the Django DetailView
I need to add comments in the Post Detailed View. I am able to submit the comment form but it is not saving the comment, instead, when I click on the submit button the page is reloaded and the comment doesn't get saved. In models.py class Comment(models.Model): post=models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments") name=models.CharField(max_length=200) comment=models.TextField() created_date=models.DateTimeField(default=timezone.now) approved_comment=models.BooleanField(default=False) def __str__(self): return self.comment In forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model=Comment fields=['name','comment'] In views.py: from django.views.generic.edit import ModelFormMixin from .forms import CommentForm class PostDetailView(ModelFormMixin,DetailView): model=Post form_class=CommentForm def get_context_data(self,*args,**kwargs): context=super().get_context_data(**kwargs) context['form']=self.get_form() return context def post(self,request,*args,**kwargs): self.object=self.get_object() form=self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self,form): form.instance.post=self.object form.save() return super().form_valid(form) -
document direction change using javascript
I'm trying to change document layout from Arabic to English and so the body direction should be changed from rtl to ltr i have already written the JavaScript function and it works for a second only,the document changes direction to ltr and then goes back, any idea on how to fix this? function layout(){ document.body.style.direction="ltr"; } -
run tasks every day at 8 AM in django
i am working on a web app in django and i need to send some random numbers to database , EVERY DAY at 8 AM. i was trynig to use celery but it did not work (im working on windows and from a tutorial i've heard celery does not work on windows!!!).Also i tried django-extensions and django-cron but it needs some changes in cron that i've found it is for linux and as i said before,im on windows. What should i do? Any help would be appreciated. -
visual studio code-should I install python in virtual environment in the folder of my project?
I am a newbie. I have set up my virtual environment in a project folder on my desktop, I also used pip install to install django 2.2 in this project folder on my desktop. I have python installed, but it is in another folder elsewhere on my computer, do I need to install python in the same project folder on my desktop? I am getting messages in virtual studio, which say, "visual studio code, workspace contains pipfile but 'pipenv' was not found". Also when try to use pip install to install python into the project folder on my desktop I get an error message in terminal(I am using a mac) which says, pip install python3.8 ERROR: Could not find a version that satisfies the requirement python3.8 (from versions: none) ERROR: No matching distribution found for python3.8 I'm also getting error messages which say: visual studio code no python interpreter is selected & there is no pip installer available in the selected environment So overall, do I need to install python in the project folder and if so, how do I do this? Do i need to install the python interpreter as well? I have had a problem with bash wherein … -
Is there a way i could select which group i want my user to belong to using a custom template?
Lets say You want to create a user and you want to associate the user with a specific group i.e a user should either be an Admin, Seller and Customer. I dont need the user to always be a customer like in the below code. group = Group.objects.get(name='Customer') user.groups.add(group) -
How to Return MEDIA URL in Template
I Create This Function to return a Media URL of a File in Templates but it Show in HTML like http://example.com/history/('/media/exam/returns/files.png',) @property def ReturnAttachment(self): from ResultManagement.models import Result attachment = Result.objects.filter(examinee=self.examinee, exam=self.exam) attachment_url = attachment[0].attachment.url if self.hasReturnAttachment(): #print("URL", attachment) return attachment_url, How can I fix it? Thanks in Advance -
How choose the right serializer depends on specific field ? e.g. type
I'd like to serialize an input from an API to check if the format is valid ProfileSerializer(payload).is_valid() profile.py from rest_framework import serializers from .node import NodeSerializer class ProfileSerializer(serializers.Serializer): node = NodeSerializer(many=True) node.py from rest_framework import serializers from .point import PointSerializer class NodeSerializer(serializers.Serializer): id = serializers.IntegerField() points = PointSerializer(many=True) type = serializers.CharField(max_length=50) The issue is the node format, depend on the type -> SEGMENT, ARC, ... I need to select the right serializer. So I create a serialier for each type type -> SEGMENT, ARC, ... but I can't figure out how to use them inside the ProfileSerializer. How I can catch the type field and use it inside a provider parser function profile.py from rest_framework import serializers from .segment import SegmentSerializer from .thread import ThreadSerializer map_type2serializer= { "THREAD": ThreadSerializer, "SEGMENT": SegmentSerializer } def parseur_provider(type): p = map_type2serializer.get(type, None) if(p is None): raise ValueError("Type {type} is not register") return p class ProfileSerializer(serializers.Serializer): node = parseur_provider(type)(many=True) -
Cannot assign "<QuerySet []>": " must be a "" instance
I am trying to save this field from Forms.py, which seems to be causing this error: Cannot assign "<QuerySet [Vehicles: Toyota]>": "Group.vehicles" must be a "Vehicle" instance. Everything saves correctly through the admin page but not through the form. class GroupForm(forms.ModelForm): vehicles = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Vehicles.objects.all()) class Meta: model = Group Models.py: class Vehicles(models.Model): Vehicles = models.CharField(max_length=30, null=True, blank=True) MaxRange = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) Speed = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) def __str__(self): return self.Vehicles class Group(models.Model): group = models.CharField(max_length=30, blank=True) vehicles = models.ForeignKey(Vehicles, null=True, on_delete=models.CASCADE) def __str__(self): return self.group 'Group' consists of one type of vehicle. views.py: def home(request): group = Group.objects.all() form = GroupForm() if request.method == 'POST': form = GroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.vehicles = form.cleaned_data['vehicles'] obj.save() return redirect('/') context = {'group': group, 'form': form} return render(request, 'calculator/Input.html', context) Thanks you for any input -
How to understand the following Python function code?
How to understand the following code? This code is a snippet of Django source code. I am trying to understand 1. How the nested function works below? 2. The function returns itself, so is it a recursive function? 3. Why does the check_password(raw_password, self.password, setter) in return can have three parameters? def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) -
VSCode Debug - Prepend command when launching for django?
I've recently started using VSCode to debug with Django and it's worked out pretty well. I use a system for managing my environment variables however that requires the use of it's keyword first (keys python manage.py runserver) Debugging works fine for firing up a standard Django install - but I can't seem to get the python debugger to run the above statement. In my launch.json I've tried a few configurations like the following: # launch.json { "name": "Python: Django", "type": "python", "request": "launch", "preLaunchTask": "keys-run", "program": "${workspaceFolder}/manage.py", "args": [ "runserver" ], "django": true } # tasks.json { "type": "shell", "label": "keys-run", "command": "keys" } I've tried this as well: { "name": "Python: Django", "type": "python", "request": "launch", "program": "keys", "args": [ "python", "manage.py", "runserver" ], "django": true } The second config give me an error that there is no such file or directory '/home/username/project_directory/keys' But from the command line (zsh) I can run the command: keys python manage.py runserver and it loads my environment variables as it should, then loads up and runs django without issue. What is the best way to get this into VSCode debugger? -
Django add urls from project to another project
I have an existing project (let's name it main) on Django and several applications in it. There is a separate project, also in django, and one application inside it (we will call this the second one). Here is a generalized file structure for project "second": my_second_project │ manage.py │ models.py │ my_models.py │ my_views.py │ ├───myapp │ │ admin.py │ │ apps.py │ │ Funcs.py │ │ models.py │ │ tests.py │ │ urls.py <-- from here urls import to project urls file │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ └───...│ ├───my_second_project │ │ asgi.py │ │ settings.py │ │ urls.py <-- HERE all urls i need │ │ wsgi.py │ │ __init__.py ├───templates │ ... │ └───__pycache__ models.cpython-37.pyc Here is a generalized file structure for project "main": main_project ├───app ... │ ├───... ├───main_project │ ├───media │ │ └───user_uploads │ ├───settings │ │ └───base.py │ └───urls.py ├───app ... │ ├───... ├───app ... │ ├───... └───static ├... I need to integrate "second" project into my existing one (main project), ideally without making any changes to the second project. I tried to do it in the same way that applications are integrated (via urls include), but it … -
How to clone on the updated files from github to the droplet in digital Ocean
I have a django website deployed in digital ocean which requires to be updated. I learn that the deployment method is using github. I do not have access to the github account but i can commit and push to the repository from the bash. Is there a way i can clone the only updates files from the git repo to my digital ocean droplet -
I am passing an object to a template in Django but I can not call it
I am in Django, I am making a list of objects in my views.py so I can pass it to my template and show those properties in my page. I create the list of objects and their properties like this: views.py: def courseListView(request): object_list = {} courses = Course.objects.all() for course in courses: object_list[course] = { 'prog': int(lessonsCompleted.objects.filter(user=request.user.id, course=course.id).count() / course.lessons.count() * 100), 'title': course.title, 'slug': course.slug, 'thumbnail': course.thumbnail, 'get_absolute_url': '/' + course.slug, } context = { 'object_list': object_list, } return render(request, "courses/course_list.html", context) In this way I am populating a object called object_list with a number of objects I extract from my Course model. In the template I try calling the properties of the objects in object_list like this: template: {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/courses.css' %}"> <div class="container d-flex justify-content-center"> <div class="row"> <h1>Cursos</h1> <div class="container-fluid mt-4 d-flex card-deck justify-content-center"> {% for object in object_list %} <div class="row justify-content-center"> <div class="col-auto mb-3"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="/static/{{ object.thumbnail }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></h5> <div class="w3-light-grey w3-round-xlarge"> <div class="w3-container w3-blue w3-round-xlarge" id="progress-{{ object.slug }}" style="width:{{ object.prog }}%;">{{ object.prog }}%</div> </div> <div class="card-footer"> … -
Django aggregation of aggregation - Cannot compute Sum is an aggregate
I'm trying to perform an aggregate of an aggregate, but looks like is not possible (SQL doens't allow it) Let's start defining what contains the queryset: DW00 2020-01-01 2020-03-31 653.38 DW00 2020-01-01 2020-03-31 8,346.54 DW00 2020-04-01 2020-06-30 488.00 DW00 2020-04-01 2020-06-30 8,346.54 DW00 2020-07-01 2020-09-30 488.00 DW00 2020-07-01 2020-09-30 8,390.07 R00 2020-01-01 2020-03-31 6,877.11 R00 2020-04-01 2020-06-30 6,877.11 R00 2020-07-01 2020-09-30 6,877.11 The values are respectively: condition_type, calculation_from, calculation_to and net. Now we want sum the row that have same condition_type and same competence period (calculation_from, calculation_to) this translate to rows 1 and 2 merged together, rows 4 and 5 and finally 6 and 7. sap_payments = sap_payments.values('condition_type', 'calculation_from', 'calculation_to') \ .annotate(competence=Sum('net')) \ .order_by() This will return another queryset that contains: {'competence': Decimal('8999.92'), 'calculation_from': datetime.date(2020, 1, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 3, 31)} {'competence': Decimal('8834.54'), 'calculation_from': datetime.date(2020, 4, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 6, 30)} {'competence': Decimal('8878.07'), 'calculation_from': datetime.date(2020, 7, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 9, 30)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 1, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 3, 31)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 4, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 6, 30)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 7, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 9, 30)} Now we want calculate the days diff … -
django double filter with the same field
How to double filter with the same field? this is my sample below, i didnt get any data , i just want to filter the Status = 'cut off completed' and Status = 'cut off completed' but i didnt get any data from it. deliverySchedule = DeliverySchedule.objects.filter(Status = 'cut off completed').filter(Status = 'Active').order_by('deliverySchedule') my data from django admin -
What is the best way to compare time in sql?
I am creating a django project for dental clinic appointment booking. Was wondering what is the best way to compare the date and time using sql or any other methods. Eg the dr has booked an appointment for 10/6/2020 13-1. for the next appointment how do I validate the available slots to avoid overlapping ? -
Django - RelatedObjectDoesNotExist even after default value have been written
I have extended default User model with "phone' field. I would like user to update their phone number after sign up. The problem is that for new created user 'phone' object is seen as empty even after default value have been written in code. If I want update phone number via form - I get an error : RelatedObjectDoesNotExist at /phone User has no profile. When I check user's attributtes via admin panel I see that field has default value (111 in my case), but for some reason when I load template there is empty object error. models.py: # extending profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(max_length=12, default=111) views.py: def update_profile(request): profile_form = ProfileForm(instance=request.user.profile) return render(request, 'phone.html', { 'profile_form': profile_form }) phone.html <form method="post"> {% csrf_token %} {{ profile_form.as_p }} <button type="submit">Save changes</button> </form> signals.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(max_length=12, default=111) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Django: global template not found after creating settings module
I am struggling with paths in Django. I have the following directory structure: application # created by django | |--application |--apps # apps created by django's startapp command |--app_1 |-- ... |--__init__.py | |--app_2 |-- ... |--__init__.py |--__init__.py | |--settings |--__init__.py |--base.py |--development.py |--production.py |--__init__.py |--asgi.py |--urls.py |--wsgi.py | |--static |--css |--js |--fonts |--images | |--templates |--meta |--head.html |--javascript.html |--includes |--home.html | |--requirements.txt I just created the settings directory using this tutorial Improve your Django project with these best practices. So the __init__.py is has a single line from .development import *. The file development.py has from .base import * DEBUG = True and base.py includes all the stuff of the old settings.py file. After I did that, my templates are not working anymore, and I guess this will also happen to the static files. When I want to access the page, django returned: TemplateDoesNotExist at /blog/includes/home.html This is my setup in base.py for static files and templates. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] My BASE_DIR is Django Project\application\application. And this is my … -
I'm using python-social-auth but my app isn't logging out when the user logs out of Google
I have python-social-auth working to authorize my app and everything works great. I can log into my app via OAuth2 and log out via typical Django logout. My problem: if a user logs out of Google (from GMail, for example), it does not log me out of my Django app. I am still authorized as the Google user even though Google is logged out. I have tried refreshing tokens via the load strategy below to "force" a check to make sure Google is still logged in and that isn't working. social = request.user.social_auth.get(provider='google-oauth2') access_token = social.get_access_token(load_strategy()) social.refresh_token(load_strategy()) I feel like I'm going down the wrong road. All I want to do is validate that Google is logged into still so I can consider my OAuth2 session valid. Is there a way to do this integrity check? What am I doing wrong or do I need to do? My research so far suggests what I want is not even possible - I don't like that answer so hoping for a different one here.