Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How can I share a python module and its variables between uwsgi workers using Django
I'am currently working on a Django app that uses a module I created called stream. This module starts a thread to open a camera with opencv and yield frames. Now That I am trying to run it with nginx and uwsgi I realized that the stream module gets initialized with every new worker. This causes a problem as each worker is attempting to start a new connection with the same camera. Is there a way to make this stream module globally accessible between workers instead of being initialized by every worker? (below is a snippet of my views.py) from . import stream @xframe_options_exempt @login_required def stream_log(request) -> StreamingHttpResponse: """ This endpoint requires a logged in user to view the logged data for the current stream session. It is fed through an iframe into the `view` page :param request: http request :return: StreamingHttpResponse """ try: return StreamingHttpResponse(stream.log_feed()) except: pass @login_required @gzip.gzip_page def camera_stream(request) -> StreamingHttpResponse: """ This endpoint requires a logged in user to view the stream feed from the camera. It is fed through an iframe into the `view` page :param request: http request :return: StreamingHttpResponse """ try: return StreamingHttpResponse(stream.video_camera.feed(), content_type="multipart/x-mixed-replace;boundary=frame") except: pass -
optimize solution for multi user type , two of them share manytomany field
The system is mutli user(based on signals) : Company Driver Client Company and Driver have team and can invite drivers to their teams So company and driver share the team field which is many to many field I found two solutions : First one: Team field will be in the BaseUser mode. pros: Simple implementation Cons: client user will have a team field on it’s record in database which mean redundant data. Second one: Create abstract model hold team field, then both company, driver models will inherit that abstract model. Pros: Avoid creating team field in Client user Cons: More code Code a little bit messy Increase complexity of invitation and join logic ( must be optimized to fetch if the invitation creator is a company or driver then deal depend on that) , (in first solution the creator always will be the BaseUser) Add an extra fields to invitation object refere to CompanyMembership and DriverMembership, (in first solution was just a field refere to the general membership), but this invitation object will delete after joining , will be kept in database in case the invited one does not joined , and can solve by using celery to delete expired … -
How do I work around 'circular import' in Django?
I'm getting a 'circular import' error when trying to makemigrations in Django. The two models in question are these. The error is being flagged on Team. from django.db import models from django.contrib.auth.models import User from footballapi.models.team import Team from footballapi.models.bio import Bio class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.ForeignKey(Bio, on_delete=models.CASCADE) teams = models.ManyToManyField(Team, on_delete=models.CASCADE, related_name="members") from django.db import models from footballapi.models.player import Player class Team(models.Model): name = models.CharField(max_length=50) roster_spot = models.ForeignKey(Player, on_delete=models.CASCADE) I think the issue is with the ManyToManyField, and I keep reading that I should use a string instead of the import. But I've tried every combination of words and can't find the right string. What should it be? By the way, these models are all from the same app. -
How to install Cairo on Windows 11
I'm trying to run "python manage.py makemigrations" on Windows 11. I keep getting an error saying that "OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2". I've searched the internet to see how I can install this library but all of the sources I've seen were outdated and none of the solutions worked. Has anybody been able to install cairo on Windows 11? -
How to get all referenced objects in Django?
I have two models: class ArticleCategory(models.Model): Category_name = models.CharField(max_length=50, null=False, blank=False) def __str__(self): return self.Category_name class Article(models.Model): Title = models.CharField(max_length=100, blank=False, null=False) Content = tinymce_models.HTMLField(null=False, blank=False) Category = models.ManyToManyField(ArticleCategory,blank=False) Assuming that the user will create some categories without necessarily linking them to any article, how do I get all the ArticleCategory objects that at least have one Article object linked to them? -
I understand decorators on a base level but am confused by @django.display()
Working through the django tutorials and came across the following code: @admin.display( boolean=True, ordering='pub_date', description='Published recently?', ) Had no idea what it was so I did some googling and learned what decorators are in Python. I feel comfortable with that topic. However, in all the videos and docs I went through I didn't see an example like @admin.display() Only things like @log or @timer. Pretty much just a simple class or function decorator. My guess is that @admin.display is a decorator where admin is the class and display is one of many wrapper methods(is that even possible) in that class? Just confused I guess as to the syntax as I can't find any examples like it :(