Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to structure Django project with external python packages interacting with the same database
I am developing a Django Rest Api for which I am targeting below structure: django_project │-- django_project │--__init.py__ │-- asgi.py │-- setting.py │-- urls.py │-- wsgi.py │-- app │-- migrations │-- __init.py__ │-- admin.py │-- apps.py │-- models.py │-- tests.py │-- views.py │-- manage.py │-- media │-- static │-- templates The thing is that I would like to include an external python package that I have developed for the data processing. This package uses slqalchemy for the db mapping so I am not sure how (and where) to fit it inside my django project since there will be duplicate models definition (with sqlachemy and Djando ORM). Thanks for your help -
Confusion regarding slack modal behavior
I'm a bit confused regarding the behavior of the slack modal. Here's my use case: Upon successful modal submission, I have to perform some CRUD and send few acknowledgments to a bunch of people. I'm unable to perform this in a single call. pseudo will make more sense: Not working if data["type"] == "view_submission": # CRUD ops # acknowlegement-1 conn = http.client.HTTPSConnection("hooks.slack.com") # acknowlegement-2 # close the modal return HttpResponse(status=204) #can't close at this stage. always returns error(something went wrong) Working: if data["type"] == "view_submission": # CRUD ops # close the modal return HttpResponse(status=204) My simple question: how to perform these operations? I'm trying to do it in a single call after handling view_submission but I think the modal is expiring. If I close the modal, how can I send an acknowledgment back even if I know the incoming webhook? The function will return, right? Any help would be appreciated! -
How to authenticate custom user that doesn't extend AbstactUserModel with djangorestframework-jwt
I'm new to django rest framework and i have problem about jwt authentication .I create a manually token in signin view payload = jwt_payload_handler(serialized_data) token = jwt_encode_handler(payload) response['token'] = token but i don't know how to authenticate with that token because my Model doesn't extend AbstactUserModel. I just found how people use jwt authentication with custom users that extends AbtractUser class Shop(models.Model): uuid = models.UUIDField(default=uuid.uuid4) username = models.CharField(max_length=30) password = models.CharField(max_length=64) name = models.CharField(max_length=100, blank=True) Should i write custom Permission for this situation? Can anyone tell me what should i do? Thank you very much -
how to activate existing virtual enviroment (using pipenv)
I am working with a project in django where i am using virtual enviroment using pipenv shell (which created enviroment name (Django_and_Rest-YRrszWnq)) so in this enviroment I have installed many packages releated to this project Now I started new project and also i want to used above virtual enviroment How to activate this ((Django_and_Rest-YRrszWnq)) enviroment to new project using pipenv command ? -
Django + nginx + socket - url path not working
Whenever I try to go to www.example.com/anything it always redirects to www.example.com. It works fine if I don't use the domain. Ex: ip.ip.ip.ip/anything works. here's my sites-available server { listen 80; listen [::]:80; server_name my_ip_here; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/chris/Portfolio_v2/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django - csrf cookie not set
I've been trying for hours to send a POST request to an endpoint in my Django application from my separated VueJS frontend using Axios. The problem with my code is that whatever i try i will always get Forbidden (CSRF cookie not set.), and i can't use @crsf_exempt. I tried every possible solution i found, from changing headers names in my Axios request to setting CSRF_COOKIE_SECURE to False, nothing seems to solve this problem. Here is my request: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } console.log(cookieValue) return cookieValue; } function req(){ this.csrf_token = getCookie('csrftoken') axios({ method: 'post', url: 'http://127.0.0.1:8000/backend/testreq/', data: { //Some data here }, headers: {'Content-Type': 'application/json', 'X-CSRFToken': this.csrf_ftoken } }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }); }, The token is being sent but the outcome is always the same. The Django app is using Django-Rest-Framework too, i don't know if that's … -
Export equivalent for windows?
I am following a tutorial on building a simple website using django. I am at the stage of preparing my website for deployment. However, when I try to enter export READ_DOT_ENV_FILE=True into the terminal, I get the error message: export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + export READ_DOT_ENV_FILE=True + ~~~~~~ + CategoryInfo : ObjectNotFound: (export:String) [], CommandNotFoundE xception + FullyQualifiedErrorId : CommandNotFoundException I am a windows user, and the tutorial person is a mac user. I don't know why I am getting this error, and I hope you guys could help me export this code. Here are some codes in my settings file for your reference: READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: environ.Env.read_env() Thanks a lot! -
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 .