Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way in Django to load a template in 'sections' or 'chunks' a sort of pagination as you scoll?
The reason I ask is that I'm parsing a large List into a Django template, we're talking about 100,000 items being rendered into a table and it's painfully slow at loading! or is there a method that I've completely missed? I'm currently using {% regroup %} to group headers together. -
Counting all items linked to foreign key
I'm looking for a solution to combine in one view information from two models. One model is for "node" definition. Second model is "drive" definition, where I have foreign key for "node". One "node" can contain many drives. In a template I need to show all assigned drives for a given node in a list view. I'm interested in count, a number of drives assigned to given node. I don't have any new idea how calculate this information and pass to template. Should I count this as a "pure python"? I believe there is a way in Django as this doesn't look very complex. View: class NodeListView(ListView): template_name = 'nodes/nodes_list.html' queryset = Node.objects.all() context_object_name = 'nodes' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) drives = Drive.objects.all() context.update({ 'drives': drives }) return context Models: class Node(models.Model): name = models.CharField(max_length=32) .... more .... class Drive(models.Model): node = models.ForeignKey(Node, related_name='nodes', on_delete=models.CASCADE) .... more .... -
How to return values from Relational Databases if certain criteria is met; Django
I am having difficulty rendering a view (myprojects) that renders the projects that a user is a part of, which is contained in uProjects. I created an object_list that filters uProjects to see if user=user assigned this list to the context and returned render(request, 'myprojects.html', context). Then I created a for statement in the html to list all projects. Here is my code (I've listed the models, views, and html, please let me know if you need more.): models.py: class Project(models.Model): name = models.CharField(max_length=30) #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True) bPic = models.ImageField(default='defaultproban.jpg', upload_to='project_banner') class Meta: verbose_name_plural= "projects" def __str__(self): return self.name class uProjects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="u") project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="uProj") ifAccepted = models.BooleanField(null = True, blank=False, default=False) #ifLeader = models.BooleanField(null = False, blank=False) ifAdmin = models.BooleanField(null = True, blank=False, default=False) title = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.user.username + ',' + self.project.name views.py: @login_required def myProjects(request): object_list=uProjects.objects.filter(user=user) context = { 'object_list': object_list, } return render(request, 'myprojects.html', context) myprojects.html {% extends "main/base.html" %} {%block title %}My Projects{% endblock %} {% block content %} <ul> {% for project in object_list %} <li> Project: {{project.name}}, of {{project.department}} Department. <a href="/project/{{project.name}}/">View Details.</a> </li> {% endfor %} </ul> {% … -
Is there a way to use order_by in Django to specify the order in which the results are returned?
So far I have seen only ascending and descending uses for order_by. I want to order_by(Risk) but have the results returned in High, Med, Low order (These are my options in the field), not based on alphabet sorting, the way order_by is done by default. -
MPTT- Category Tree Subcategory not showing category
I was trying to create categories and subcategories using mptt library in django environment. mptt lib installed successfully. Category(name) model created in model.py(file).In Admin.py mptt. MPTT- Category Tree Subcategory isn't showing any category created using below code in admin.py panel MPTTAdmin --> it doesnot show any list_display and Categories and subcategories values as shown in the attached picture below. [category in admin][1] It is showing 10 categorys instead of subcatogries [1]: https://i.stack.imgur.com/2GtfA.png # Register your models here. from product.models import Category,Product,Images from mptt.admin import DraggableMPTTAdmin class CategoryAdmin(admin.ModelAdmin): list_display = ['title','parent', 'status'] list_filter = ['status'] #mptt class CategoryAdmin2(DraggableMPTTAdmin): mptt_indent_field = "title" list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title',) def get_queryset(self, request): qs = super().get_queryset(request) # Add cumulative product count qs = Category.objects.add_related_count( qs, Product, 'category', 'products_cumulative_count', cumulative=True) # Add non cumulative product count qs = Category.objects.add_related_count(qs, Product, 'category', 'products_count', cumulative=False) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Related products (for this specific category)' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Related products (in tree)' #product pictures class ProductImageInline(admin.TabularInline): model = Images extra = 5 #5 similar pictures class ProductAdmin(admin.ModelAdmin): list_display = ['title','category', 'status'] list_filter = ['category'] # readonly_fields = ('image_tag',) inlines = [ProductImageInline] admin.site.register(Category,CategoryAdmin2) admin.site.register(Product,ProductAdmin) admin.site.register(Images) models.py … -
Django change an existing field to foreign key
I used to have a model like this: class Car(models.Model): manufacturer_id = models.IntegerField() There is another model Manufacturer that the id field refers to. However, I realized that it would be useful to use django's built-in foreign key functionality, so I changed the model to this: class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer) This actually works fine immediately, queries work without errors, everything is great, except that if I try to run migrations, Django outputs the following: - Remove field manufacturer_id from car - Add field manufacturer to car Doing this migration would clear all the existing relationships in the database, so I don't want to do that. I don't really want any migrations at all, since queries like Car.objects.get(manufacturer__name="Toyota") work fine. I would like a proper database foreign key constraint, but it's not a high priority. So my question is this: Is there a way to make a migration or something else that allows me to convert a existing field to a foreign key? I can't use --fake since I need to reliably work across dev, prod, and my coworkers computers. -
Django admin saves a copy of the object instead of overwrite
I have a model with OneToOneFiled named alg_id, and when I go to admin panel and change this filed in existing object, than a new object is created, but I'd like to overwrite same object with different alg_id. When I change other simple text fileds - all works fine. If I change alg_id to one, that already exists in Database, than that object gets overwritten - will be better if I'll get a warning here.. How could I achieve that? ps. this project use 2.2.6 Django version -
Django TrigramSimilarity returns eroors with Full Text Search on GIN index
Hello I'm trying to make search on Django with postgresql/FTS on a GIN indexed column but get a weird error. This error does ot appear on CharField but only on a SearchField: the Postgresql Database has the pg_trgm extension installed (within a Django migrations) This is the Objects : class Language(models.Model): code = models.CharField(primary_key=True, max_length=5, verbose_name=_("code")) label = models.CharField(max_length=50, verbose_name=_("label")) search = SearchVectorField(null=True) objects = Language_Manager() class Meta: verbose_name = _("language") verbose_name_plural = _("languages") indexes = [ GinIndex(fields=["search"], name="search_index",), ] def save(self): fields = [x for x in dir(self) if x[:5] == "label"] labels = [getattr(self, field) for field in fields if getattr(self, field)] self.search = self.search + " ".join(labels) super().save() and here is my query : from core.models import Language as LanguageCode from django.contrib.postgres.search import TrigramSimilarity LanguageCode.objects.all().annotate(sim=TrigramSimilarity("search", "english")) it returns an error message : LINE 1: ...e_language"."label_ko", "core_language"."search", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. if I use a standard CharField instead of a GIN indexed SearchField, the error does not occurs : from core.models import Language as LanguageCode from django.contrib.postgres.search import TrigramSimilarity LanguageCode.objects.all().annotate(sim=TrigramSimilarity("label", "english")) <MultilingualQuerySet [<Language: Language object (fr)>, <Language: Language object (en)>, >><Language: Language … -
Speed of website after separation of database
I have recently separated postgresql database from django web-app. now the database and web-app are on two different servers but the problem is that I/O is slow. Is it normal or I should change some settings? do I need to refactor some parts of the code? -
Access many-to-many reverse lookup from @property in model with Django
I have two models: class Concordance(models.Model): name = models.CharField(max_length=64) tunes = models.ManyToManyField(MsTune, related_name="concordances") def __str__(self): return self.name class MsTune(models.Model): name = models.CharField(max_length=255, db_index=True) # title (source) [etc...] @property def concordances(self): for concordance in self__concordances.all: for t in concordance.tunes.all: [stuff] return '-' + t.name My problem is that self__concordances.all always appear to be none even though there is data. What am I missing? -
django passing context data from post method
here is my views.py class DoctorDetailView(generic.DetailView): model = Doctor context_object_name = "doctor" template_name = "adminplus/pages/doctor_profile.html" def get_context_data(self, **kwargs): context = super(DoctorDetailView, self).get_context_data(**kwargs) data = { "edit_form": forms.DoctorEditForm(instance=self.object), "password_change_form": forms.PasswordChangeForm(self.object.user), } context.update(data) return context def post(self, request, *args, **kwargs): if request.POST.get("change-password"): form = forms.PasswordChangeForm(request.POST) if form.is_valid(): print("valid form here!") # ... else: print("invalid form : ", form.errors) return render(request, self.template_name, ?? ) I've no idea how can i pass get_context_data back to my template. (or anything that works.. idk new to django:) ~Thanks in advance -
How to run custom model validations for M2M in clean() when adding a new model instance
I have a model in Django with a ManyToManyField relationship to another model. Something that looks like this: class MyModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) models = models.ManyToManyField( OtherModel, related_name='my_models', ) In my clean() method, I have a bunch of custom validation rules that are run in the model fields. Some of them actually run in the ManyToManyField. All validations work fine when creating model instances with an uploader tool that parses data from a csv into a model instance or when saving an existing model in the Admin. However, I want to be able to add model instances directly in the Admin but because of the ManyToMany relationship, which I found out that is not set until after the save() method, some validations throw a ValueError: "<MyModel: Some Model>" needs to have a value for field "id" before this many-to-many relationship can be used. ([ref][1]) Then, what I did is a very ugly hack to to the validation in the clean() method to bypass it by catching the ValueError: def _some_validation(self): try: if self.my_models.count() == 0: raise ValidationError("This is an error message thrown by ...") except ValueError as e: print(e) Then it works fine to add a model instance … -
Custom sorting Queryset for columnview
Moin Moin! I have a model for appointments: from django.conf import settings from django.db import models class Appointment(models.Model): DateTime= models.DateTimeField(blank=True, null=True) Name= models.CharField(max_length=30, blank=True, null=True) Name= models.CharField(max_length=30, blank=True, null=True) def __str__(self): return str(self.DatumZeit) The table Appointment cointains an DateTime for every 10 minutes for each day. For viewing it on the frontend in div's (bootstrap - row -col) I want the queryset to order that I have eg Appointment 1 to 12 in Column A, Appointment 13 to 24 in Column B, and so on. In my views.py I tried it like this: appointments = Appointments.objects.all() number = appointments.count() if (number % 4 == 0): block = number // 4 rest = 0 else: block = number // 3 rest = number % 4 x = 1 appointments2 = () for i in range(1, number): appointments2 += appointments[x + block] if x == 4: x = 1 else: x += 1 I get an error because it seems not to be possible to copy a row of a queryset to an list. Someone could give me an hint to the way to go? -
Change Django static directory name
Django static directory name is set to static by default. Can it be changed to something else?. If i could change it to cssandjs could this bring any errors to my project? and does that also mean that in templates i would load static by {% load cssandjs %} instead of {% load static %}? -
Django - why am i not logged in after authenticating?
I'm having a nightmare setting up Authentication from a Vue SPA to a Django backend, i'm using the standard Django session authentication and this library: django-rest-registration. The problem with my code is that, after logging in i receive a Logged in succesfully response, but then if i try to hit a Django endpoint that simply prints to my console request.user.is_authenticated i always get False, so according to Django i'm not authenticated. After logging in, i see the session being added to my database, so that part should be working. Here is my code: Axios login (notice that i disabled CSRF just for development): axios({ method: 'post', url: 'http://127.0.0.1:8000/api/v1/accounts/login/', data: { 'login':'root', 'password':'test', }, }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }); This returns Logged in succesfully. Now if i try this: Axios is_auth(){ const data = {}; axios.post("http://127.0.0.1:8000/backend/is_authenticated/", data) .then(response => console.log(response['data'])); }, Django def is_authenticated(request): print(request.user) print(request.user.is_authenticated) >> Anonymous False The session is set on the database, so i think the problem might be with Axios. Do i have to send a cookie or something else? Any advice is appreciated. -
Formatação de dados em tela django admin
Bom dia Sou novo em programação e estou com um problema que não consigo resolver. Estou trabalhando em um sistema python e django e estou precisando formatar valores que aparecem na tela do django adimin.. Ex: tenho uma lista em tela com valores e varias casas decimais que precisa ser formatada porem não posso alterar meu calculo no código, teria que ser algo de interface no django admin mesmo. Fico no aguardo obrigado -
Django, Query filter by multiple time interval overlaps
I have a Worker and Task model. The Worker has working hours (working_hours) and the Task has time to work (working_time). These time fields are associated with the TimeInterval model as ManyToManyField. Each interval has a start and an end time. I used a ManyToManyField because the Worker and Task can have multiple intervals for working hours. For example, a worker can work in the intervals from 07:00 to 12:00 and from 15:00 to 18:00. And the task must be completed from 13:00 to 17:00. I need to make a query which tasks are suitable for a worker during working hours. Time intervals for work must overlap. How can i do it? I tried to get working time intervals from a specific worker, then in a loop form a condition for filtering using Q-objects. Like this: my_worker = Worker.objects.get(id=1) my_worker_working_hours = my_worker.working_hours.all() time_conditions = [] for interval in my_worker_working_hours: time_conditions.append( Q( Q(working_time__start__lte=interval.end) & Q(working_time__end__gte=interval.start) ) ) suitable_task = Task.objects.filter(*time_conditions) This works if the Task has only one working_time interval. Otherwise, filter does not work correctly. My models: class Worker(models.Model): name = models.CharField(max_length=10) working_hours = models.ManyToManyField(TimeInterval) class Task(models.Model): name = models.CharField(max_length=10) is_assigned = models.BooleanField(default=False) working_time = models.ManyToManyField(TimeInterval) class TimeInterval(models.Model): start = … -
how to config passenger_wsgi file when django is installed in another folder (Cpanel)?
0 . in Capnel : 1 . I created a python app named pythonapp 2 . I used terminal and run : pip install django 3 . I used terminal and run : django-admin startproject myproject (without . at the end of command , i need project folder tree in this form) passenger_wsgi.py is located in : /home/mysite/pythonapp/passenger_wsgi.py wsgi.py is located in : /home/mysite/pythonapp/myproject/myproject/wsgi.py how should i edit passenger_wsgi.py to run django ? Note : from myproject.myproject.wsgi import application did not worked, and caused Internal error 500 . -
Why is my individual Tweet ID number changing last few digits to "0" when retrieving tweets though Tweepy?
Background: I'm using Tweepy python library to access the twitter API to retrieve cryptocurrency tweets. My application uses a Django backend and a ReactJs frontend. While my web-app will show the retrieved tweet itself, I intend to also have a clickable link available, to re-route to the original on Twitter. My Django Rest Framework API is retrieving the correct Tweet ID number in full when returning a JSON. However, when I'm retrieving from the Rest Framework API to my Frontend, the last few digits of the Tweet ID number is changed to "0". I wonder if this is a default protection measure that Twitter uses? Thanks in advance for all your help! Please see below for more clarity under "bitcoin_tweet_link": Django Rest API: Front-End of Website: App.js: <div className="center-column-tweet"> <div className="item-row-tweets"> <div className="left"> <span><b>@{tasks.bitcoin_tweet_user}</b><br/><br/>"{tasks.bitcoin_tweet}"<br/><b>Link:</b> https://twitter.com/twitter/statuses/{tasks.bitcoin_tweet_link}</span> </div> </div> </div> -
Django add fields to createsuperuser command
I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the createsuperuser command to query once for the user table and once for the residence table. This could then look like this: C:\Users\Project>python manage.py createsuperuser username: input firstname: input lastname: input password: ***** country: input city: input street: input -
How do I validate that a user is at least 13 years old?
I have created a login and registration app in Python for use with Django and I have been using it in a few different projects. My only problem trying to apply it to some projects is I can't figure out how to make sure a user can only register if they are at least 13 years old. This is my models.py and what I have imported for the validations. from django.db import models from datetime import date, datetime import re import bcrypt class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=150) birthday = models.DateField() password = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() This is the only validation I have accompanying the birthday input so far. I have other validations, but this is the only one pertaining to birthday. def registration_validator(self, post_data): errors = {} user_birthday = datetime.strptime(post_data['birthday'], '%Y-%m-%d') if user_birthday > datetime.today(): errors["release_date"] = "User birthday must be in the past!" return errors_login My views.py that handles processing the registration. def process_registration(request): errors = User.objects.registration_validator(request.POST) if len(errors) > 0: for key, value in errors.items(): messages.error(request, value, extra_tags='register') return redirect('/') else: first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] birthday = request.POST['birthday'] pw_hash = … -
How to solve from django.utils.importlib import import_module ImportError: No module named importlib
Currently I am upgrading my old Django project from django 1.8 to django 1.9 and current my python version is 2.7.12 and i am getting this error File "/home/projectfolder/myproject/local/lib/python2.7/site-packages/social_auth/models.py", line 4, in <module> from django.utils.importlib import import_module ImportError: No module named importlib The same errors i am getting in different paths.For example File "/home/projectfolder/myproject/local/lib/python2.7/site-packages/social_auth/utils.py", line 4, in <module> Now my doubt is should we replace this line - "from django.utils.importlib import import_module " as "from django.utils.module_loading import import_module" in all the paths Or is there any other alternative to get rid of this issue ? -
Make add_action visible to only one model in Django
This is my models.py from app named article from django.contrib import admin from .models import Article, Group from django.contrib import messages class ArticleAdmin(admin.ModelAdmin): def publish_selected_articles(modeladmin, request, queryset): queryset.update(publish_status=True) messages.success(request, "Selected Record(s) Marked as Published") admin.site.add_action(publish_selected_articles, "Publish selected articles") admin.site.register(Article, ArticleAdmin) This code adds action of Publish selected articles to all models. Well, the docs says the same. See here What I want is to have Publish selected articles action button visible only to this this class (i.e. ArticleAdmin). I could also use disable_action as docs shows. I have 5 action buttons and about 10 Apps. So writing disable_action about 50 times does not seem to be a good idea. And what if I some other developer develops more apps in future. Is there a easy solution for this? How can I make add_action visible to specific class in Django model ? Any help is appreciable. Thanks in advance. -
Why django remove GET params from Url? [closed]
I have '^(?P<slug>[\w-]+)/$' url pattern. When I visit page localhost/app/example_slug/?aaa=bbb, I can access parameter inside my class based view via self.request.GET.get('aaa'), but in browser's address bar all GET params are removed. Can't understand the reason. -
Django queryset with Q gives wrong length
I'm struggling with or query. It give me weird output. In models file i have as shown below: class Server: addres_ip=models.GenericIPAddressField() class Interface: addres_ip=models.CharField(max_length=15,default='127.0.0.1',blank=True) server=models.ForeignKey(Server,default=None,blank=True,null=True,on_delete=models.CASCADE) In db i have added a Server object with addres_ip='10.0.10.11' and with his Interface with addres_ip='10.1.1.2'. When i query: Server.objects.filter(addres_ip='10.0.10.11') I get 1 result and it's correct Interface.objects.filter(addres_ip='10.0.10.11') I get 0 results and it's correct as well but when I query: Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11')) i get 7 results........ Am i missing something ? there should be 1 result ..I think but not sure right now ? Thank you in advance