Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How can i create this type of Django Admin (as shown in the pic)
Chick Here for the Pic..... This is the Admin template, here the Model options are on left side and the content stored in the model is on right side. -
Trouble rendering a variable in Django
I'm trying to "create" a variable and render it in my template but for some reason I can't manage to do it. Here's my view.py: def test(request): person = {'firstname': 'Craig', 'lastname': 'Daniels'} weather = "sunny" context = { 'person': person, 'weather': weather, } return render(request, 'home/dashboard.html', context) and in my template dashboard.html : <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> Any idea on what I'm doing wrong? -
I can't delete users from my app in Django
I am developing a webpage for elderly people in Django for my internship. I received some code already done from another coworker but for some reason when I try to delete users from the /admin site it gives me and error. In addition, I only have one form to register and login in the webpage but it gives another error. login view: def login_view(request): if request.user.is_authenticated: return redirect(reverse('portada')) mensaje = 'El usuario no estaba registrado' if request.method == 'POST': username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate( username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect(reverse('portada')) else: return render(request, 'accounts/login.html', {'error_message': 'Your account has been disabled'}) else: mensaje = 'Se va a registrar un usuario' form = RegistroUserForm(request.POST, request.FILES) if form.is_valid(): cleaned_data = form.cleaned_data dia = form.cleaned_data['dia'] mes = form.cleaned_data['mes'] year = form.cleaned_data['year'] password = dia + mes + year + 'year' user_model = User.objects.create_user(username=username, password=password) user_model.save() user_profile = UserProfile() user_profile.user = user_model user_profile.save() username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate(username=username, password=password) if β¦ -
Django Foreign Key to Filtered Object got errors: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I have problem that i never face before. I have custom user model on models.py class User(AbstractUser): username = models.CharField( max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) these users associated with Groups : maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> in other app called cleaning, I want have an object that associated with these users filtered by each group. So in my cleaning app models.py User = get_user_model() user_maker = User.objects.filter(groups__name='maker') user_checker = User.objects.filter(groups__name='checker') user_signer = User.objects.filter(groups__name='signer') class cln_daily(models.Model): . . . user_maker = models.ForeignKey(user_maker,on_delete=models.CASCADE, blank=True, null=True) user_checker = models.ForeignKey(user_checker,on_delete=models.CASCADE, blank=True, null=True) user_signer = models.ForeignKey(user_signer,on_delete=models.CASCADE, blank=True, null=True) but then I got an error that said django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. . . . File "D:\gtipwa\lib\site-packages\django\apps\registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. any idea how to use filtered object in foreign key?? I'm not sure but i think the problem is caused by double underscore in object filter. I have no idea how to fix them. -
Wagtail internal link urls arent working properly
in my rich body text fields, when an internal page is used for a link, the url that gets attached to the a tag is "https//example.com/example", ie it's missing the colon and the link doesnt work. I get the error "https's server ip address could not be found". any idea why it is doing this? thanks -
Django: Inject code post pk/id generation and before save in DB
TL;DR: Is there a way to inject code post pk / id generation but before the object is saved in the db? Hello, So I am currently working on duplicating django objects. I have a duplicate function which enforces new object generation upon saving by setting pk and uid to None on a deep clone of my object: def gen_uuid() -> str: """Return a str representation of a uuid4""" return str(uuid4()) class Entry(PolymorphicModel): """Base class providing a custom lock permission, a name and a uid to replace Django's default id DB column.""" uid = models.CharField( unique=True, primary_key=True, db_index=True, default=gen_uuid, max_length=36, help_text="Object's primary key, it cannot be enforced and will be generated randomly. " "Example: c8daa3ac-3dd0-44e9-ba2a-b0cbd1c8d8ae.", ) name = models.CharField(max_length=128, help_text="Name of the object.") folder = models.ForeignKey( Folder, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="files", help_text="Primary key to the folder containing the object.", ) content = JSONField( default=dict, blank=True, help_text="JSON representation of the graph." ) def save(self, *args, **kwargs): """Handles entry saving and duplicate management This function is overridden so the models can be created with the name. This function does not fill missing duplicate numbers. It will create duplicates in such pattern: entry_name entry_name (2) entry_name (3) """ # Does some stuff... β¦ -
No Response after calling the API
I am working on a project, where I am making a call to the API https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The%20Irishman%22,%22content_types%22:[%22movie%22]%7D I am making the call to the API, using the code import requests data = requests.get('https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The Irishman%22,%22content_types%22:[%22movie%22]%7D') print(data.json()) But, today when I made the call to the same API, it gave me None Response, and when I tried making the same API call on my browser, it worked fine. I made a minor change, that while making a call to the API, I added a header specifying the browser details, like header = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" } and now the code is working fine. Can anybody tell me why it is so, that the request was working fine earlier but why I had to specify the header now ?