Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating relationship between Student and Class in Django
I am trying to create models where I can have relationship between Students and ClassName tables so that I can get all users using using ClassName.objects.get() and ClassName using Student.objects.get() method? I am completely stuck here. Should I add more fields to Student model? from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): pass class ClassName(models.Model): grade = models.IntegerField() section = models.CharField(max_length=1) def __str__(self): return f"{self.grade} - {self.section}" class Student(models.Model): first_name = models.CharField(max_length=124, null=False) middle_name = models.CharField(max_length=124, default='') last_name = models.CharField(max_length=124, null=False) name = models.CharField(max_length=124, default=f"{first_name} {middle_name} {last_name}") father_name = models.CharField(max_length=124, null=False) phone_number = models.CharField(max_length=20, null=False) date_of_birth = models.DateField() national_id= models.CharField(max_length=15, null=False) student_class = models.ForeignKey(ClassName, on_delete=models.DO_NOTHING) def __str__(self): return f"{self.first_name} {self.middle_name} {self.last_name}" I am trying to find a method to get all users using using ClassName.objects.get() and ClassName using Student.objects.get() method? -
What is .pyi in django?
What is .pyi file in Django? For example stubs>django-stubs>db>models>expression.pyi ? -
How to import a function or variable from a sibling of the current parent app 5 levels upper of the current app in Django?
I want to import some functions a constants variables from 5 levels upper of the current app of Django application. My problem is that the package that I want to import from, is outside of the Django application, so Django isn't aware of it. project structure: ├── lawcrawler │ ├── get_all_amended_laws_urls.py # import a function from this file │ ├── lawcrawler │ │ └── spiders │ │ └── settings.py # import variables from this file │ │ ├── project │ ├── apps │ │ ├── laws │ │ ├── management │ │ ├── commands │ │ ├── add_list_of_amended_laws.py # import function and variables to this file │ ├── manage.py I have tried relative import like this: from .......lawcrawler.lawcrawler.spiders.settings import SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query and this: from .....lawcrawler import get_all_amended_urls but got this error: ImportError: attempted relative import with no known parent package How to import the functions and variables or solve this issue? -
Is there a chance that emails are sent in parallel and thus `mail.outbox.clear()` doesn't really clear outbox in my django tests?
I have written django tests to check my outbox emails as shown below class TestX(TestCase): def setUp(self): # Clear outbox. mail.outbox.clear() super().setUp() def tearDown(self): # Clear outbox. mail.outbox.clear() super().tearDown() however, performing assertions e.g self.assertEqual(len(mail.outbox), 1) fails with the len(mail.outbox) showing a large number as compared to the emails I've sent using send mail. I know there are other apps also sending emails so I'm wondering if the emails are being sent in parallel and thus my clear isn't effective or what might be the issue? -
Is it possible to sort queryset without hitting the db again?
Is there any approach to avoid hitting db when the queryset needs to be returned in a specific order? If a queryset would be returned when a page is loaded qs = Student.objects.all()[start:end] But it also provides UI for users to view the query in ascending or descending order. So, at Django server. Queries should be performed qs = Student.objects.all()[start:end] qs2 = Student.objects.filter(id__in=qs).order_by("-id") To reduce the db hitting, is there any other better approach to avoid frequent query and db hit? I wonder I would store the query result in browser and return the results but it looks so complex... -
Difference between render( ) and redirect( ) in django?
what is exactly the difference between render( ) and redirect( ) in django? I know redirect will send another request to the URL and render will render the template with the given context. But still something makes me not fully understand it. Maybe anyone can explain it well can help me a lot. Do I have to first render the template before using redirect function. For eg: I have two templates home.html and signin.html. def home(request): return render(request, 'home.html') def logout(request): return redirect('signin') or without writing def home can I redirect to home.html like below def logout(request): return redirect('signin') -
Trying to Resolve a "Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead." error
I am a student working on a project for my coding bootcamp and I'm having to resolve an issue with a many to many field. The theme of the project is app that lets users post screenshots from various video game and label them bases on category, 3rd party editing and capture tools. I'm trying to write code for POST and PUT requests that will allow a user to select several objects in a React.js form. I'd also try and test whatever solution I get in postman. I've added fixtures into my database and the fixtures work, but when attempting to test by using raw JSON in the body like this: ` "category": 1, or "category": [ 1, 2, 3 ] ` I get the error show in the title of this post. I'm using Python 3.9.10 and Django 4.14. my model looks like this: screenshot.py ` from django.db import models from .archer import Archer from .editingtool import EditingTool from .capturetool import CaptureTool from .category import Category class Screenshot(models.Model): archer = models.ForeignKey (Archer, on_delete=models.CASCADE) image = models.CharField(max_length=255, null=True) content = models.TextField() captureTool = models.ForeignKey (CaptureTool, on_delete=models.CASCADE) editingTool = models.ForeignKey (EditingTool, on_delete=models.CASCADE) category = models.ManyToManyField ('Category', through='ScreenshotCategory') timestamp = models.DateField(auto_now_add=True) ` … -
django celery database transaction auto commit
I use celery group feature to group my async tasks, like job_flow = group( tasks.init_a.si(id, data), tasks.init_b.si(id, data) ) res = job_flow() In init_a function, I have some code ta = tablea.objects.get(id=id) ta.desc = 'done' ta.save() Then in init_b(), I will to check the ta.desc is done or not, but I can not get the ta.desc to done. But I use ./manage shell to check the ta.desc value is changed to done. Why I can not in init_b() to get the real ta.desc value? Django (1.5.6) celery (3.1.23) -
Passing Django request object into script to build absolute URI?
I am trying to build a one time script by passing in a django request in order to build an absolute URI. I am using the HttpRequest() method as follows... request = HttpRequest() And passing it into the function that I am calling when running my script. I keep running into a KeyError My script that is being ran is as follows, from django.http import HttpRequest for form in forms: form_data = get_data(form) for user in User.objects.all(): request = HttpRequest() config_user_forms(request, user) Errors out with the following, File "config_user_forms.py", line 65, in <module> redeploy_form(request, user) File "/tmp/8dae22604556cc2/users/admin/users.py", line 654, in redeploy_form build_url = request.build_absolute_uri( File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 223, in build_url location = self._current_scheme_host + location File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/utils/functional.py", line 45, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 240, in _current_scheme_host return "{}://{}".format(self.scheme, self.get_host()) File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 121, in get_host host = self._get_raw_host() File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 111, in _get_raw_host host = self.META["SERVER_NAME"] KeyError: 'SERVER_NAME' I am a bit stumped on a work around, and appreciate any help in advance! -
How to run "SELECT FOR UPDATE" for the default "Delete selected" in Django Admin Actions?
I have Person model as shown below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, this is Person admin below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, when clicking Go to go to delete the selected persons as shown below: Then, clicking Yes I'm sure to delete the selected persons: Only DELETE query is run in transaction as shown below: Now, how can I run SELECT FOR UPDATE for the default "Delete selected" in Django Admin Actions? -
Cannot generate instances of abstract factory UserFactory ( Factory boy)
factory.errors.FactoryError: Cannot generate instances of abstract factory UserFactory; Ensure UserFactory.Meta.model is set and UserFactory.Meta.abstract is either not set or False. Im using factory boy library To test my functions my class UserFactory Here enter image description here Here Model User I'm inheritance from class abstract user enter image description here I added class meta abstract and still not working I added class meta abstract and still not working -
How can I use Date Range with Sum and Order By in Django
I am working on a project where I have an Income Model with description among other fields as shown below. The description is a choice field and I want to use Date Range to Sum by each description. i.e. I would want to sum all amount for each description and display their total in HTML Template. Below is what I have tried but I am getting error which says too many values to unpack (expected 2). Models code: CATEGORY_INCOME = ( ('Photocopy', 'Photocopy'), ('Type & Print', 'Type & Print'), ('Normal Print', 'Normal Print'), ('Color Print', 'Color Print'), ('Passport', 'Passport'), ('Graphic Design', 'Graphic Design'), ('Admission Check', 'Admission Check'), ('Lamination', 'Lamination'), ('Document Scan', 'Document Scan'), ('Email Creation', 'Email Creation'), ('Email Check', 'Email Check'), ('Online Application', 'Online Application'), ('Agreement Form', 'Agreement Form'), ('Envelope / Binding Film', 'Envelope / Binding Film'), ('Web Development ', 'Web Development'), ) class Income(models.Model): description = models.CharField(max_length=100, choices=CATEGORY_INCOME, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Income Sources' def __str__(self): return self.description Views Code def generate_reports(request): searchForm = IncomeSearchForm(request.POST or None) searchExpensesForm = ExpensesSearchForm(request.POST or None) if request.method == "POST" and searchForm.is_valid() and searchExpensesForm.is_valid(): listIncome = … -
Raise Error 404 using django-hosts in Django
I have the following problem. I'm using django-hosts for subdomains like blog.example.com, es.example.com. The problem is that there are urls where I manage id, such as: blog.example.com/url/id And suppose the user doesn't touch anything, because everything is an OK 200 but if the user goes from clever and touches the id to one that doesn't exist, the site returns a 404. But here comes the problem, when using django-hosts if I do a handler404 in the urls of the subdomain. It throws me an Error 500 and if I then do a handler500 in the urls of the subdomain, literally, it breaks the server, since then apache tells me that there is a problem in the server. Here I leave my url.py of the subdomain. from django.urls import path from django.views.generic.base import TemplateView from django.conf.urls import handler404, handler500 from django.conf import settings from django.conf.urls.static import static from django.contrib.sitemaps.views import sitemap # MODULO PROPIO from . import views from .sitemaps import MapaDeSitio sitemaps = { 'blog': MapaDeSitio } urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ # SITIO path('', views.indexView, name='IndexView'), path('articulo/<str:url>/<int:id>', views.ArticuloView, name="ArticuloView"), # SEO path('robots.txt', views.RobotsView.as_view()), path('BingSiteAuth.xml', TemplateView.as_view(template_name="blog/BingSiteAuth.xml", content_type="text/xml")), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] # MANEJO DE ERRORES HTTP handler404 … -
Query M2M from Django template language
This might be a rookie problem but I cannot find a way around it. I am trying to implement add recipe to favourites. The view and model work properly as when I hit the button once it sends the request and adds the recipe to the user's favourites. Then when clicked again it removes it correctly from the database. Alas now when i try to make visible on the template I ran into trouble with the template language. I cannot find a way to check if the current user's profile has liked the paginated recipe. I have the following class based list view class Home(ListView): model = Recipe template_name = 'home.html' cloudinary_name = settings.CLOUDINARY_STORAGE.get('CLOUD_NAME') extra_context = { 'cloudinary_name': cloudinary_name, } paginate_by = 2 def get_queryset(self): return Recipe.objects.order_by('id').prefetch_related('profile__recipecomment_set__recipe') and the following Recipe model class Recipe(models.Model): title = models.CharField( max_length=TITLE_MAX_LENGTH, validators=( MaxLengthValidator(TITLE_MAX_LENGTH), MinLengthValidator(TITLE_MIN_LENGTH), ), null=False, blank=False, ) profile = models.ForeignKey( Profile, on_delete=models.RESTRICT, null=False, blank=True, editable=False, ) favourites = models.ManyToManyField( Profile, related_name='favourite', default=None, blank=True, ) the template.html is as follows {% for recipe in page_obj %} {% if request.user.profile.id in recipe.favorites %} <button>Recipe added to favourites</button> {% else %} <button>Add to favourites</button> {% endif %} {% endfor %} the pagination works, everything else … -
I am trying to edit basic crud command with basic application using python django
I can create an obj just find. I want to pre load the form have a user make a change and update/save it in the db. After an edit is made it adds " ", (), [[[enter image description here](https://i.stack.imgur.com/Tan5A.png)](https://i.stack.imgur.com/jGJsK.png)](https://i.stack.imgur.com/WKowu.png)marks and commas after everything. I have tried to use the replace function to remove the ""'s, still doesnt do any good? I just want to edit and save without adding characters to my data. I tried value={{task.reminder}} and it shows fine on my page, after I check the edit it will show "Take trash out", All I need is Take trash out. Thank you!!!!!!!! the photos showed what I tried, however, I have no idea how to fix. Thank you. -
Google Calendar API v3 error after allowing permission using oauth2.0
I followed the quickstart example to integrate my django app with google calendar. The difference from quickstart to my situation is that i just want to generate a URL and send it back to my user, through from google_auth_oauthlib.flow import InstalledAppFlow SCOPES = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(f"{PATH_TO_FILE}/{CLIENT_SECRET_FILE}", SCOPES) (auth_url, state) = flow.authorization_url() if is_dev(): auth_url += '&redirect_uri=http%3A%2F%2Flocalhost%3A43759%2F' print(auth_url) (OBS: I added this is_dev option, because no redirect_uri was not considered) I get this printed URL and get this steps: 1- The URL from auth_url printed when i ran the program 2- After choosing my user 3- and BAM, I cant proceed (i am redirected to localhost:47759 and cant access) What should I do? -
What is the best practice of handling buttons in Djnago?
I am not sure about the best practice on generating a high amount of buttons, that will connect with Django backend, after they are clicked. I am currently making sample online store in Django as my first project, so I can learn the framework. Each product on the page is going to have a button to add the product to the cart of a logged user. Should I make every button as a form, or handle the buttons with JS and fetch API. I did not fail to notice, Django heavily relies on forms as a default way to get user input, but making a so many generated forms on one page (the products are going to be a list) just doesn't feels right I was thinking of the solution like this: document.querySelectorAll('.add_product').forEach(e => { e.addEventListener('click', e => // POST request (with crsf cookie and all) // redirecting the user, depending on the output ) }) Just get all buttons, get data-pk from <button>, and send it with the JS Fetch API as POST request to Django endpoint The thing I don't like about it is, I see potential CORS Issues, and I do not know if this is the … -
How can i filtering tags with Alpine.js
I want to filter the tags based on user clicks. But the problem is when I use the HTML tag, everything becomes hidden as I cannot see any content on the page. Even when clicking on a specific tag, I do not see any results.The result after using The model.py : class Challenge_code(models.Model): #create a table auther = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200, null = False) body =RichTextUploadingField(blank=True, null=True) image = models.ImageField(null = True,blank=True ,upload_to='attach/') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) tags = TaggableManager() def __str__(self): return self.title serializers.py from rest_framework import serializers from taggit.serializers import (TagListSerializerField, TaggitSerializer) from .models import Challenge_code class ChallengeSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Challenge_code #fielsds = ('id','title','body','image','tags') fields = '__all__' the urls.py : urlpatterns =[ path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<slug:tag_slug>', views.ChallengePage, name='tag'), path('challenge-list/', views.ChallengeListAPIView.as_view(), name='challenge-list'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) class ChallengeListAPIView(ListAPIView): queryset = Challenge_code.objects.all() serializer_class = ChallengeSerializer The ChallengePage HTML page : <script defer src="https://unpkg.com/alpinejs@3.9.0/dist/cdn.min.js"></script> <div style="text-align: center;" x-data = "{tag: 'ALL', challenges: []}" x-init="challenges = await (await fetch('/challenge-list')).json()"> {% for tag in tags %} … -
The page of my website does not load on iPhones
I made my first website (https://pasta-la-vista.ck.ua/), but I ran into a problem. The site works on a computer and Android, but the menu page (https://pasta-la-vista.ck.ua/menu/) does not load on an iPhone. I couldn't find any information about what this is related to, so I hope to find help here. I fixed all the errors that appeared in the console but it didn't help me. I also looked for information on the Internet, but did not find anything Thank you all in advance for your help! -
I have a django app in a ubuntu virtual machine and can't remotely access the postgres database
I deployed an application in django on GCP in a VM (ubuntu 22.04 01 LTS) The app is working normally, database is postgresql. But I can't remotely access the database, I always get timeout error. My settings.py .... DATABASES = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE'), 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USER'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), } } ... My .env file : # Postgres DATABASE_ENGINE = 'django.db.backends.postgresql' DATABASE_NAME = "basededados" DATABASE_USER = "user" DATABASE_PASSWORD = "senha" DATABASE_HOST = "127.0.0.1" DATABASE_PORT = "5432" I created the database like this: sudo -u postgres psql CREATE ROLE user WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'senha'; CREATE DATABASE basededados WITH OWNER user; GRANT ALL PRIVILEGES ON DATABASE basededados TO user; I already set up the postgres.conf file: listen_addresses = '*' And the pg_hba.conf file**:** # IPv4 local connections: host all all 0.0.0.0/0 md5 I alredy allowed port 5432 through the firewall by executing: sudo ufw allow 5432/tcp I'm trying to access the DB like this: psql -h {Virtual machine IP} -d basededados -U user the error: psql: error: connection to server at {Virtual machine IP}, port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Am I … -
admin is not able to approve post for the required like field django
In my django project, users can create posts. but the admin has to approve the post first. Then the users can see the posts created by them in their timeline. The users can like or unlike post from the post-detail page. However, when the admin logs in from the django admin panel to approve post and click the save button, it shows that the like field is required. How can I solve this problem so that the admin can approve the post? blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # first I installed ckeditor by this command: pip install django-ckeditor # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) @property def total_likes(self): return self.like.count() users/models.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your … -
Failed to execute 'fetch' on 'WorkerGlobalScope'
I'm trying to pass variables from background.js file to views.py in Django. I tried many ways to do it and I write the following code, it seems to work but I stuck with this error. I searched a lot for a solution but I didn't found anything yet //background.js fetch("http://127.0.0.1:8000/my_app/views") .then(response => response.text()) .then(responseText => { // Extract the X-CSRF-TOKEN cookie from the response let csrfToken = getCookieValue(responseText, "csrftoken"); // Set up the data to send to the server let data = { variable1: "value1", variable2: "value2" }; // Make the request to the server with the X-CSRF-TOKEN header fetch("http://127.0.0.1:8000/my_app/views", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken } }) .then(response => response.json()) .then(responseData => { console.log(responseData); }); }); // Helper function to extract a cookie value from a string function getCookieValue(text, name) { let start = text.indexOf(name + "=") + name.length + 1; let end = text.indexOf(";", start); if (end === -1) { end = text.length; } return text.substring(start, end); } the error is the follwing: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Invalid value please help me.. -
How do I adapt my import statements to my folder structure in Django?
I just set up a basic folder structure for a new project, however I am doing it a bit different than the standard file structure, since my front-end is in React and will be in a separate git repository. The problem is, my virtual environment is installed in the "backend-django" project and when I try to access my package imports (that I installed in my virtual env) in backend/settings.py it does not recognize them. As an example: I pip installed django-environ into my venv but when I go to settings.py (like I normally do) and import environ, I get a 'no module named environ' error. This is my first foray into Django (clearly). For reference, I have previously only used Flask for Python projects. Any help is appreciated! A mockup of my basic folder structure is here: folder structure I have already tried from backend-django import environ and from . import environ. I am still getting the same error. -
Django allauth render login fields manually user or email not displayed
I'm trying to display the login fields manually, instead of using: {{form.as_p}} I'm setting allauth as follows in order to login with email: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True In HTML I have the following: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> {{form.email}} <label class="form-label" for="form2Example1">Email address</label> </div> <!-- Password input --> <div class="form-outline mb-4"> {{form.password}} <label class="form-label" for="form2Example2">Password</label> </div> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="btn btn-lg btn-block btn-primary" type="submit">{% trans "Sign In" %}</button> </form> The email field is not being displayed, I have also tried with: {{form.user}} and the field is not displayed -
Nginx subdomain running the wrong web application
so I have a ubuntu server that run two different website with two different domain: www.firstwebsite.com www.secondwebsite.com But when I create an AAA record to create a subdomain with the first domain (like this) demo.firstwebsite.com If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com) I tried creating a specific socket&service file for the subdomain for it still run the web application of the second domain. Im not sure what is causing that and how to fix that? thank you