Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Check if request.POST field is empty
I have a form that may be submitted with some fields as blank/empty values, but when I run: if request.POST['field']: it always returns true, even if the field has not been filled in, how can I check if a field has been completed or left blank? -
I'm following Python Fullstack by Perrian data facing error with Faker libararies
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from faker import Faker import os os.environ.setdefault('DJANGO_SETTINGD_MODULE','first_project.settigs' ) import django django.setup() # rand numbers import random from first_app.models import AccessRecord,WebPage,Topic error :- facing django.setup() error file structure:- file Structure total code:- code -
fetching specific data from JSON with python
I want to fetch specific data form JSON . Right now I can fetch all of the data and convert it into JSON format. But I only want to fetch "home_team" and "away_team" of all the sets. My code to fetch all of the data is:` import json import requests reap = requests.get('https://app.sportdataapi.com/api/v1/soccer/matches?apikey=64572f90-88d6-11eb-8a43-7106c933e99d&season_id=496&date_from=2020-09-19&fbclid=IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4') data = reap.json() print(data) And my JSON data is: {'query': {'apikey': '64572f90-88d6-11eb-8a43-7106c933e99d', 'season_id': '496', 'date_from': '2020-09-19', 'fbclid': 'IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4'}, 'data': [{'match_id': 139415, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, 'name': 'Regular Season'}, 'group': {'group_id': 222, 'group_name': 'Bundesliga'}, 'round': {'round_id': 18564, 'name': '1', 'is_current': None}, 'referee_id': 433, 'home_team': {'team_id': 3993, 'name': '1. FC Union Berlin', 'short_code': 'UNI', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2819.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'away_team': {'team_id': 4075, 'name': 'FC Augsburg', 'short_code': 'FCA', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2814.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'stats': {'home_score': 1, 'away_score': 3, 'ht_score': '0-1', 'ft_score': '1-3', 'et_score': None, 'ps_score': None}, 'venue': {'venue_id': 1870, 'name': 'An der alten Forsterei', 'capacity': 22012, 'city': 'Berlin', 'country_id': 48}}, {'match_id': 139451, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, … -
post function is called twice django python
I am facing problem wherein post function of class view in django is called twice. I am doing a long operation in one of the sub functions. So after some time, post is again called. Please help me. How can I make it run once only. Thanks. -
i have a dynnamic html table so how can i add multiple rows with same name and id+1 in django database its only added first row in database
i have javascript to increment id as a +1 so how can i add those html rows into database i am trying to add those dynamiclly rows which is genrated by javascript but i am not able to add those rows please help me models.py class New_Order(models.Model): sno = models.AutoField(primary_key=True) hscode = models.CharField(max_length=50) Product_Category = models.CharField(max_length=50) Finish = models.CharField(max_length=50) Edge = models.CharField(max_length=50) Product_Name = models.CharField(max_length=50) Product_Nomenclature = models.CharField(max_length=50) Product_Type = models.CharField(max_length=50) Length = models.CharField(max_length=50) Breadth = models.CharField(max_length=50) Thickness = models.CharField(max_length=50) Patio_Pack = models.CharField(max_length=50) Crate = models.IntegerField() Measure = models.IntegerField() Measure_Unit = models.IntegerField() Pcs_or_Crate = models.IntegerField() Crate_Start = models.IntegerField() Crate_End = models.IntegerField() Crate_Buffer = models.IntegerField() Container_Qty = models.IntegerField() Percentage = models.IntegerField() Desc = models.CharField(max_length=50) Price = models.IntegerField() def __str__(self): return self.hscode i am trying through name but all name are same in dynamiclly table so those values not adding in database can you all please guide me how its possible views.py def pro(request): prod = Product_Catagory.objects.all() any = Finishe.objects.all() edg = Edge.objects.all() prodn = Product_Name.objects.all() prodnn = Product_Nomenclature.objects.all() prodt = Product_Type.objects.all() len = Length.objects.all() bre = Breadth.objects.all() thick = Thicknes.objects.all() pat = Patio_Pack.objects.all() context = {'prod':prod, 'any':any, 'edg':edg, 'prodn':prodn, 'prodnn':prodnn, 'prodt':prodt, 'len':len, 'bre':bre, 'thick':thick, 'pat':pat} if request.method == "POST": hscode = … -
How to use JQV map in Django?
I want to create a JQV country web for my dashboard. I have a Customer model and this model has a country field. This field is connected with a foreign key and I can get country codes and JQV map is accepting country codes. I created an array in my views and when I print it works. But when I put in the data field of the map chart, does not show anything. How can I fix it? models.py class Customer(models.Model): ... country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) class Country(models.Model): ... country_code = models.CharField(max_length=5) views.py def approval_context_processor(request): ... countries_iso = Customer.objects.values_list('country__country_code', flat=True).distinct() ... for cn in countries_iso: arr.append(cn) print(arr) // it works truely. else: pend_list = 0 submit_list = 0 context = { ... 'arr': arr } return context dashboard.html ... <div class="mapcontainer"> <div id="map-example" class="vmap" style="height: 400px"></div> </div> <script> var country_list = [] {% for country in arr %} country_list.push( '{{ country }}' ) {% endfor %} window.alert(country_list) //It works truely $('#map-example').vectorMap( { map: 'world_en', backgroundColor: 'transparent', borderColor: '#fff', borderWidth: 2, color: '#e4e4e4', enableZoom: true, hoverColor: '#35cd3a', hoverOpacity: null, normalizeFunction: 'linear', scaleColors: ['#b6d6ff', '#005ace'], selectedColor: '#35cd3a', selectedRegions: [country_list], showTooltip: true, onRegionClick: function(element, code, region) { return false; }, onResize: …