Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest test failing when run with other tests but passes when run by itself
I very basic test that checks if a user that is not logged in can connect to my websocket that is as follows: @pytest.mark.asyncio async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator): connected, subprotocol = await unauthenticated_websocket_communicator.connect() assert subprotocol == 3000 # subprotocol 3000 is Unauthorised assert connected is False This test passes when i test it by itself from the cli using pytest -k test_unauthenticated_cant_connect_to_websocket but fails when i use pytest from the cli my consumer connect function is as follows: async def websocket_connect(self, event: dict) -> None: if self.scope["user"].is_anonymous: await self.close(code=3000) else: await self.accept() I have a number of other async tests with similar types of code but they all pass. Any suggestions would be much appreciated -
access foreignkey field from other field which is foreign key to other
I have model 3 models model 1 2 and 3 i need to access model 1 from model 3 model 2 has foreign key relation with model 1 and model 3 to model 2 how can access model 3 to model 1 class Record(models.Model): name = model.CharField(max_length=255) class Task(model.Model): name = models.CharField(max_length=255) record = models.ForeignKey(max_length) class Subtask(models.Model): name = models.CharField() subtask_of = models.Foreignkey('Task') I need to access the record name from Subtask how can i achieve that -
Django models multiple inheritance, class meta
I have my models in my app but I can play with the inheritance. This is a tree of my models :enter image description here We can see a double inheritance on ParticulierV, PaticulierF, AssociationF, EntrepriseF and EntrepiriseV. I need to be able to find a user by his statut (FournisseurStatut or VendeurStatut), but also to access to parameters (like email, username...) from Base, because some actioons apply to all type of user (exemple : check email). I don't need a data table for base, FournisseurStatut and VendeurStatut. I don't know how I have to configure my meta class for that. Here my models : # -*- coding: utf-8 -*- import uuid from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Base(models.Model): """ basic model - email - password - id - date joined - last_login """ id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) email = models.EmailField(unique=True, db_index=True) # check email validate_email = models.BooleanField(default=False) # review password place password = models.CharField(db_index=True, max_length=50) # hacher date_joined = models.DateTimeField(_("date joined"), default=timezone.now) last_login = models.DateTimeField(_("last login"), blank=True, null=True) class Meta: abstract = True class SupplierStatus(models.Model): """ Supplier status id supplier """ id_SupplierStatus = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) # do a … -
can I add my script/apis to my Django project? If so how can I do this
So I am building a Django web app, and I want to allow users to search for their desired crypto currency and then return the price. I plan on getting the price from coinbase or some other site that already presents this information. How would I go about this. I figure I would have to wrote the script to get the price under views.py. What would be the best approach? Can I add a web scrapping script that already does this to django? Or would I have to connect say coinbases api to my Django project. If so how do I do this? -
Fetch and return category and all related objects
I have a Bookmark and a BookmarkCategory object. I'd like to be able to fetch JSON that looks like this: GET -> localhost:8000/api/bookmarks [ "python": { "title": "Python", "bookmarks": [ { "title": "Python Documentation", "url": "https://docs.python.org" } ] }, "javascript": { "title": "Javascript", "bookmarks": [ { "title": "Python Documentation", "url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript" } ] } ] Here's my models: class BookmarkCategory(models.Model): title = models.CharField(max_length=255) class Bookmark(models.Model): title = models.CharField(max_length=255) url = models.CharField(max_length=255) category = models.ManyToManyField(BookmarkCategory) Here's how I would query all the BookmarkCategory objects: from .models import BookmarkCategory bookmarks = BookmarkCategory.objects.all() The JSON doesn't have to look exactly like this. I just need to get all my BookmarkCategory objects along with all the related Bookmark objects so I can iterate over them after I make a GET request to fetch them. -
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 …