Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TIME_ZONE is set but correct default is not set for datetime field
I set TIME_ZONE = 'Asia/Tehran' into project settings also i have datetime field into my models like below from django.utils import timezone class SomeModel(models.Model): ... datetime = models.DateTimeField(default=timezone.now) but the correct default value is not set for datetime field. I did the same thing before and it was correct, maybe it could be from nginx? code is running into linux(Ubuntu) server -
Django serializer not raising exception over model constraints
I have this dummy model from django.db import models class ChertModel(models.Model): username = models.CharField(gettext_lazy('username'), max_length=150, unique=True) o2 = models.CharField(gettext_lazy('username2'), max_length=150,editable=False, default='lllss') and with serializer class ChertSer(serializers.ModelSerializer): class Meta: model = ChertModel fields = ['username','o2'] note I have an instance with username='sd' and o2='434as' so when in the view I want to update the o2 fields which is supposedly editable=False it doesnt update it which is ok but the problem is that it doesnt raise exception over model constraints. note I have checked this configuration with editable=True and the serializer applies changes thus there is no problem with serializer. class ChertView(views.APIView): def get(self, request): lt1=ChertModel.objects.get(username='sd') print('1',lt1.o2) ser=ChertSer(instance=lt1, data={'username':'sd','o2':'newo2'}, partial=True) print(ser.is_valid()) ser.is_valid(raise_exception=True) ser.save() lt1=ChertModel.objects.get(username='sd') print('2',lt1.o2) since it would make problem of changes of user not applied to model instance without acknowledging it to user. so my question is how to detect the times the updating object is not applied due to model constraints? of course I can manually detect it by checking ser.data=={'username':'sd','o2':'newo2'} but is there any more formal or common way to handle this? -
Virtual Environment for FastAPI
A quick question, do we need to create virtual environment for installing and using FastAPI. We use venv for Django right? So why not in FastAPI? -
Django Inline admin
Hi i have a model called "Files" registered with the admin it has two fields "file" and "filename" and in the same page we are showing another model fields in "JobsInline".This inline have "device ", "Lang"," AI_field" it is Multiple Select Field. I want to create multiple inline objects based on the choices selected in The multipleSelectField on saving objects of files, behind the scene. Let's say user selected file and filename , and then device is selected.I want on selecting one device and if 5 choices are selected then 5 objects of inline should be created. If you didn't understand the problem, please tell me , i am a newbie, So please ignore my mistakes if any. -
Django channels reloading or refreshing self.scope['session'] values
I have multiple consumers, and wanted to pass a value from one consumer to the other using self.scope['sessions']. They are both created and initialized at the same time. After setting and saving (self.scope['sessions'].save()) session value, I am trying to get this session value in 2nd consumer, but the value stored at self.scope in 2nd consumer will still be the value at the time this 2nd consumer was initialized (or connected). I am looking for a way to refresh or reload the self.scope in 2nd consumer so that I can use the self.scope['sessions'] value from the 1st consumer. thanks. -
Custom Model relation with Django User Model Pls help i am new to Django rest Api
I am new to Django Rest API for user model i am using Django default user model. my end end goal is when user login he will able to see data only related to him I want my value like this { "user": 1 { "id": 1, "rent_date": "23-08-2022", "rentmonth": "June", "rent_amount": 5000.0, "bijli_bill": 250.0, "other_amount": 150.0, "other_commnet": "test", "total_amount": 5400.0, "total_rent_amount": 17000.0, } } But Getting like this, user showing under rent model { "status": "success", "data": [ { "id": 1, "rent_date": "23-08-2022", "rentmonth": "June", "rent_amount": 5000.0, "bijli_bill": 250.0, "other_amount": 150.0, "other_commnet": "test", "total_amount": 5400.0, "total_rent_amount": 17000.0, "user": 1 }, { "id": 2, "rent_date": "23-08-2022", "rentmonth": "July", "rent_amount": 6000.0, "bijli_bill": 250.0, "other_amount": 150.0, "other_commnet": "test", "total_amount": 6400.0, "total_rent_amount": 17000.0, "user": 2 }, This is my Model.py from django.contrib.auth.models import User class rent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rent_date = models.DateField(auto_now_add=True) rentmonth = models.CharField(max_length=30) rent_amount = models.FloatField() bijli_bill = models.FloatField() other_amount = models.FloatField(blank=True) other_commnet = models.CharField(blank=True, max_length=200) @property def total_amount(self): return self.rent_amount + self.bijli_bill + self.other_amount this my serializers.py from rest_framework import serializers from .models import rent from django.contrib.auth.models import User from django.db.models import Sum class rentSerializer(serializers.ModelSerializer): rent_date = serializers.DateField(format="%d-%m-%Y", read_only=True) rentmonth = serializers.CharField() rent_amount = serializers.FloatField() bijli_bill = serializers.FloatField() other_amount … -
Using the data from current request only
I have a page where i enter the data and save it on the model and simultaneously some other event occurs lets say some other data creation is happening with the data for this i am using a query .all() how can i limit the creation to the current request. def some_method(): for x in mymodel.M2Mfields.all() this is creation happens for all the data in the model how can i limit the data creation to be happening only with the current data entered on the page rather than all in the model which are previously entered -
Django auth PasswordReset views not working when placed on other apps
The login/logout system for LoginView and LogoutView works fine. The password reset system for PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView however, causes an error. accounts.urls: from django.urls import path from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path( 'password-reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'), name='password_reset' ), path( 'password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done' ), path( 'password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm' ), path( 'password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete' ), ] The error: NoReverseMatch at /accounts/password-reset/ Error during template rendering In template C:\Users\Hp\Documents\Working\Personal\django\venv_socialmedia\lib\site-packages\django\contrib\admin\templates\registration\password_reset_email.html, error at line 6 5 {% block reset_link %} 6 {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} 7 {% endblock %} Upon closer inspection especially at {% url 'password_reset_confirm' uidb64=uid token=token %} (code from a file in virtual environment), I figured it does not take into consideration my accounts app. I transferred the 4 path's pertaining to password reset into my main_project.urls thus solving the error. Despite having the password reset working, I actually wanted all 4 password reset path's back to the accounts.urls. The reason for this is to be in line with django's principle of plug-and-play apps. I'm not entirely sure if this is a good or bad idea for password reset. Few solutions I have in … -
How to generate Django template as MS word?
Is there a way to build a Django template or make it like Microsoft word by making the Django template have tools and the ability to write word documents from a website instead? if we supposed that there is a domain name called: example.com so, when I open that website for example.com/word-doc/ it will open a blank page and some tools from Microsoft Word to write in. Is there any package or API to do so? -
How to optimize queries in django-admin? Too many sql queries because of foreign key
I have model of product and category: class Category(models.Model): name = models.CharField(max_length=100, unique=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) name = models.CharField(max_length=255) In admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_editable = ('name', 'category') When I go to admin page there are too many duplicated SQL queries, all of them getting categories. If i remove category from list_editable, all duplicated queries are disappear. I tried to do this: def get_queryset(self, request): qs = super(ProductAdmin, self).get_queryset(request).select_related('category') return qs It doesn't work. -
Django SUB SUB domains
How can i make django ALLOWED_HOST for sub sub domain. For example: For subdomain I can use ALLOWED_HOSTS=['.domain.com'] such that a.domain.com,b.domain.com etc.. will work. But I need x.x.domain.com where x value will change accordingly based on tenant such that a.appointment.domain.com, b.appointment.domain.com, a.test.domain.com, b.test.domain.com. How can I include x.x.domain.com (where both x changes accordingly) in my 'ALLOWED_HOSTS' -
Django: Register models to admin site dynamically on request
I have some django models registered to my admin site by declaring them in my admin.py file. I however do not want specific internal users to be able to see certain tables. Is there a way to dynamically registered models to the admin site when a request is is received? e.g something like if request.user.email has a .gmail domain don't register the user's table. admin.py from django.contrib.admin import AdminSite admin_site = MyAdminSite() for model_name, model in app.models.items(): model_admin = type(model_name + "Admin", (admin.ModelAdmin, ), {'list_display': tuple([field.name for field in model._meta.fields])}) admin.site.register(model, model_admin) -
Django vs Flutter for multiple requests
I need to create a web solution that will have simultaneous real-time updates of a lot of data.. And I'm in doubt between using Flutter Web or Django.. I would like to know which of these should be more performant, and the reasons.. If a separate backend and frontend solution would be better, or if to do everything together (django).. In terms of performance.. The pros and cons -
Incorrect Context Appearing in Django Project
I am creating a workout project where for every workout there is a list of exercises and for every exercise there is a list of sets which has specific weights and reps. Here is the model for more clarification: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) date = models.DateField(blank=True, null=True) def __str__(self): return str(self.date) + ' ' + self.name class Exercise(models.Model): training = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) def __str__(self): return self.name class Set(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='sets',blank=True, null=True) weight = models.FloatField(validators=[MinValueValidator(0)],blank=True, null=True) repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) def __str__(self): return self.exercise.name + ' set #' + str(self.order) I am trying to show the list of rep in each set for a specific excercise in the template page but I keep getting errors such as: activity() missing 1 required positional argument: 'request' or even nothing is showing at all. The most recent view I coded shows all the sets for all the excercises which is not the objective. Here is the views: def activity(self,request, **kwargs): template_name = 'my_gym/start_workout.html' excercises = Exercise.objects.all().order_by('id') sets = Set.objects.filter( set=self.object).order_by('id') context = { 'excercises': excercises, 'sets': sets, } return render(request, template_name, context) I also … -
What is the best practice for a re-pull from git?
I'm currently working with django and python from git repo. It is understandable that I should pull and establish a virtual environment (venv) in the cloned directory. I also had installed all the requirements. Someone from my team updated the repo and I had to re-pull the repo again to work with the latest version. so, what is the best practice to deal with the new/old files? normally what i would do is remove all the old files manually(without removing venv folder), but it gets old when i had to do multiple times because the files are numerous. and doing this in wsl also is harder. does removing the whole folder including the venv is the other better way? but i can expect this would be tedious too as my libraries packages are a lot too, and reinstalling would take some time. -
VSCode debugger break point doesn't for django project
I recently shifted to mac M1 from ubuntu and I have installed VS code and tried to debug the project but it didn't stop at any breakpoint. -
How to get data from views to consumers py. Django
I wanted to get the data from my views.py def index(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) return render(request, 'base.html', context={"text":"value"}) and get the data that stores in "value" print it to my consumer.py async def connect(self): await self.accept() -
How do I create a new module in django and register the classes in that module
I want to create a new module and set of classes in my app. I created a subfolder "customclasses" and put my python classes there in separate files. But when I try to access them it says not defined. -
Django use variable from template inside of urls.py
I need to create a menu, and item names/links in the menu needs to be generated dynamically. So I have the following code which is working and lists all the menu items. views.py: def idf1(request): return render(request, 'idfs/idf.html') base.html: {% extends 'base.html' %} {% block idfs %} {% for each in idf_list %} <li> <a href="/idfs/{{each}}">{{ each }}</a> </li> {% endfor %} {% endblock %} urls.py url(r'^idfs/{{each}}$', myapp.views.idf), It looks very stupid. because I used {{each}} hoping that base.html variable is accessible in the urls.py How can I use the variable inside of my urls.py? Is it even possible? -
Pipenv Django installation
I got back into django after a while. I learned to install django using pipenv originally and after coming back to it, the installation is failing for new projects? I'm not doing anything crazy, I'm literally just trying to start a new django project. I've seen some other posts on SO that mention the same error with Heroku, but I'm not using Heroku, just trying to install Django. I'm running python3 version 3.8.9 and pipenv version 2022.3.24 I get this error: Error: An error occurred while installing django! Error text: Collecting django Using cached Django-4.1-py3-none-any.whl (8.1 MB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Collecting backports.zoneinfo Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' Failed to build backports.zoneinfo error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of … -
Python Django vs PHP Laravel for social network apps?
Is it easier to develop social network apps with Python Django or PHP Laravel or are they nearly equally as easy? I want to build a robust social networking app similar to Facebook. I'm currently learning Django, but I'm curious if social networking apps are easier with PHP because PHP seems to be known for dynamic websites. -
Creating more SEO friendly urls in Django
I have a slug field for my Article model: class Article(models.Model): Title = models.CharField(max_length=100, blank=False, null=False) Hero_image = models.ImageField(upload_to='hero-images/', blank= False, null=False) Image_caption = models.CharField(max_length=50, blank=False, null=False, default=" ") Content = tinymce_models.HTMLField(null=False, blank=False) Category = models.ManyToManyField(ArticleCategory,blank=False,related_name="articles") Published_date = models.DateTimeField(auto_now_add=True) Last_modified = models.DateField(auto_now=True) slug = models.SlugField(null=False, unique=True) def get_absolute_url(self): return reverse('blog-details', kwargs={"slug": self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.Title) return super().save(*args, **kwargs) And here is the blog-details view: def blog_details(request, slug): Articles = Article.objects.get(slug=slug) context = { "Articles": Articles, } return render(request, "blog-details.html", context) The URL path for the blog-details is : path('(?P<slug>[-a-zA-Z0-9_]+)/', views.blog_details, name='blog-details'), which gives me URLs like : http://127.0.0.1:8000/blogs/(%3FPkonstantin-the-guy-who-whatevers%5B-a-zA-Z0-9_%5D+)/ I wonder if this URL format is SEO friendly, and can I make it more human-readable .i.e: http://127.0.0.1:8000/blogs/konstantin-the-guy-who-whatevers/ -
Can I create a Middleware class in one app that handles requests in other apps on the site
In reading the, Middlware Documentation I can see I can write a middleware class that will see and has access to every request in my app, which is good. What if I want my Middleware to see and handle all requests in all apps on the site? If I Subclass a core Middleware class, will that then become the base middleware that all apps will call? Is there some other way to achieve this? If I subclass one of the Middleware classes, where do I put it in my app? -
Django REST Framwork: How do I use the ListAPIView cache only for anonymous users?
I think I saw something somewhere before about using the ListAPIView cache only for anonymous users, but when I looked again, I could not find any such information. I seem to recall that it could be done in settings.py or in the decorator. Does anyone know of such a section? -
DJANGO - What is more used, Class Based Views or Function Based Views?
I know that each one has advantages and disadvantages, but I would like to know which one I should focus on more, which would be the most used in the job market?