Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please help me with Django model object validation
I'm very new to Django and programming in general. I'm trying to do some Django admin model object validations. I'm implementing bid system. User must be able to bid straight from admin page. The code may be far from perfect... Here's models.py: class User(AbstractUser): pass class category(models.Model): category = models.CharField(max_length=50, default='Enter new category') def __str__(self): return f"{self.category}" class bid(models.Model): listing = models.ForeignKey('listing', on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2) def clean(self): if self.bid <= self.listing.Price: raise ValidationError('Please place a bid higher than starting price') if self.bid <= ??? #How should I code this? raise ValidationError('Please place a bid higher than the current highest bid') def __str__(self): return f"{self.user}, {self.listing} {self.bid}" class listing(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Title = models.CharField(max_length=50) Description = models.CharField(max_length=300) Price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"{self.Title}" -
Getting list indices must be integers in Django views
I'm scraping some data inside Django views.py and append them to a dictionary that looks like this: movie_data = { 'movie_details': [], 'actor_details' : [], 'dir_details': [], } and then append to it like below: movie_data['movie_details'].append({'title': title, 'summary': summary}) I defined a variable title = movie_data['movie_details'][0]['title'] to create objects from it but I get the error below when I try to do so: list indices must be integers or slices, not str Which already is an integer, and I've tried my code outside of Django and tried to print the data using print(movie_data['movie_details'][0]['title']) and it worked. Can anyone help me find where the error comes from? Thanks in advance. -
How to create a HomeConfig modell
I'm learning Django and I have a problem because I don't know how to put my intention a model. On my public page I would like to be able to dynamically change the content of my homepage. However, I don't want to create a PageModel - I want only a HomeConfig model with which I can define different texts, images, etc. My problem is that this model could only have one entry but a model isn't made for just one entry. -
Django, PostGreSQL; django.db.utils.IntegrityError: insertion or update in the table violates the foreign key
Out of the box git repo doesn't work. The error occurs after running pytest. django.db.utils.IntegrityError: insertion or update in the table "product_product" violates the foreign key "product_product_polymorphic_ctype_id_44f73554_fk_django_co" Here are the things I've figured out already: DETAIL: The key (polymorphic_ctype_id)=(503) is not present in the table "django_content_type". and in psql: payments=# \d+ django_content_type Tabla «public.django_content_type» Columna | Tipo | Ordenamiento | Nulable | Por omisión | Almacenamiento | Estadísticas | Descripción -----------+------------------------+--------------+----------+-------------------------------------------------+----------------+--------------+------------- id | integer | | not null | nextval('django_content_type_id_seq'::regclass) | plain | | app_label | character varying(100) | | not null | | extended | | model | character varying(100) | | not null | | extended | | Índices: "django_content_type_pkey" PRIMARY KEY, btree (id) "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE CONSTRAINT, btree (app_label, model) Referenciada por: TABLE "auth_permission" CONSTRAINT "auth_permission_content_type_id_2f476e4b_fk_django_co" FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED TABLE "django_admin_log" CONSTRAINT "django_admin_log_content_type_id_c4bce8eb_fk_django_co" FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED TABLE "product_product" CONSTRAINT "product_product_polymorphic_ctype_id_44f73554_fk_django_co" FOREIGN KEY (polymorphic_ctype_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED Método de acceso: heap payments=# table django_content_type; id | app_label | model ----+--------------+------------- 1 | admin | logentry 2 | auth | permission 3 | auth | group 4 | auth | user 5 | contenttypes | contenttype 6 | … -
Django queryset return the newest of field choices
I would like the return a queryset that is comprised of the newest (date) objects for each choice of a field name. I can do it by iterating over an ordered queryset and then progressively removing older objects with exclude(). I'm wondering if this could be done using latest(). I don't know how to run latest with each unique value of name. I don't have a lot of experience with django, I'm worried that my working code below would be slow/expensive. It groups the dogs by name, then orders it by date, then systematically removes older dates. class Dog(models.Model): # names = husky, poodle, lab, etc name = models.CharField(max_length=20) age = models.IntegerField() datemade = models.DateField(default=date.today) views.py ad = Dog.objects.all().order_by('name', 'datemade') n=0 while n < (len(ad)-1): if ad[n].name==ad[n+1].name and ad[n].datemade<=ad[n+1].datemade: ad = ad.exclude(id=ad[n].id) print(ad) n=n-1 n=n+1 -
How to fetch user selected model fields in django
I wanted to fetch the data from database according to the data selected by user input. I'am using model_name.objects.all which fetches all the data from that model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) User = settings.AUTH_USER_MODEL User_id= models.ForeignKey(User, on_delete=models.CASCADE) no_of_ques = models.IntegerField(default=10) def __str__(self): return self.Quiz_title class question(models.Model): Qid = models.AutoField(primary_key=True) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() def __str__(self): return self.Qques class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.OneToOneField(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() class result(models.Model): result = models.AutoField(primary_key=True) Quiz_id = models.OneToOneField(quiztitle, on_delete=models.CASCADE) User_id = models.OneToOneField(User, on_delete=models.CASCADE) score = models.FloatField() def __str__(self): return str(self.pk) here's html file from which user selects the quiz title to start the quiz. By clicking on the attempt quiz button user can attempt there choosen quiz . <div class="Question-container"> <div> {% for x in title %} <h1 class="title"><i class="fa fa-circle" id="quiz-icon" ></i>{{x.Quiz_title}}<button>Attempt Quiz</button></h1> {% endfor %} </div> </div> I want to fetch the data i.e question along with the option of … -
Django DRF - Axios POST
I am converting my app from jQuery/Ajax to ReactJs. Currently in the backend I am grabbing an array by doing request.data.getlist('something[]) With the same code when I am doing an axios POST i get an error. If I change the code to request.data['something'] then it works fine. What am I missing? How can I grab an array of string that working for both ajax and axios -
How to extract values from a list and insert into database
Am pretty new to Django, I have a use case where I have a list of data stored in a list, the data comes from a text area inputted by a user and stored on the variable scannedcode . Am trying to loop through and insert the values as individual records in a column but the whole list end up being inserted as ['7622210354822', '0071831003508'] . How can I have I extract and insert 7622210354822 and 0071831003508 on two different rows in SQL using Django? What I have tried so far with no luck def submit(request): scannedcode = request.POST.get('description') for code in scannedcode: print('testing data') print(code) scancodes = LabSigned(scannedcode=scannedcode) print('testing data') print(scancodes) scancodes.save() return render(request, 'detect_barcodes/detect.html') Whenever I try to print the data from the loop I get [ ' 7 6 2 2 2 1 0 3 5 4 8 2 2 ' , ' 0 0 7 1 8 3 1 0 0 3 5 0 8 ' ] instead of getting 0071831003508 7622210354822 Thank you in advance for any help -
What is the correct pathway for Django OTP body message?
I'm doing a Django project and I'm at where I want to have a custom OTP email to the users. I have tried everything I could think of to have the OTP email not just display the OTP code but also the HTML but it just displays the path of "text" I have read the docs but couldn't find much help. settings.py: text = './Templates/email.txt' html = './Templates/email.html' #OTP settings OTP_EMAIL_SENDER="" OTP_EMAIL_SUBJECT="Verification Code" OTP_EMAIL_TOKEN_TEMPLATE=text OTP_EMAIL_BODY_TEMPLATE=text OTP_EMAIL_BODY_TEMPLATE_PATH=html OTP_EMAIL_TOKEN_VALIDITY=300 email.html: <tr> <td bgcolor="#fdfbf0" style="padding:25px"> <p style="margin: 0;"> <!--the safe parameter allows us to generate html. always make sure you are passing valid html markup to the email body--> {{email_body|safe}} </p> </td> </tr> email.txt: {{email_body}} -
SQL query having two IN operator with comparison being performed index wise
I have a use case in which I have two lists which are my search criteria and I need to write a query which will result in such a way that the searching is done by taking each element from each of the list one by one and performing the query operation. Example: list1 = (1,2,3,4,5); list2 = (21,23,27,26,28); select * from table where column1 in list1 and column2 in list2; Query should work like: select * from table where column1=1 and column2=21; select * from table where column1=2 and column2=23; select * from table where column1=3 and column2=27; and so on..... Note: I have to make this query in Django, so Django's model query will also work in case SQL query doesn't fit here. -
Sort List of self referenced objects by date time : Django-RestFramework
I am new to django, I have table which store the comments, but each comment can have child comments and child comments can have another child comments. I am trying to sort them based on most recent date but only the first layer of comments are being sorted. [ { "id": 25, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "123@gmail.com" }, "comment_category": "marketing", "comment": "Marketing 1", "x": 30.0, "y": 30.0, "children": [ { "id": 26, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "abc@gmail.com" }, "comment": "Marketing", "children": [ { "id": 27, "reviewer": { "id": 3, "first_name": "Anusha", "last_name": "Savaram", "username": "Anu", "email": "abc@gmail.com" }, "comment": "Marketing 3", "children": [ { "id": 30, "reviewer": { "id": 3, "first_name": "Anusha", "last_name": "Savaram", "username": "Anu", "email": "xyz@gmail.com" }, "comment": "Marketing 5", "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": false } ], "is_parent_comment_resolved": true }, { "id": 28, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "abc12@gmail.com" }, "comment": "Technical4", "children": [ { "id": 29, "reviewer": { "id": 4, "first_name": "", "last_name": "", "username": "anusha", "email": "abc@gmail.com" }, "comment": "Tech5", "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": false, "comment_created": "1 hour ago" }, … -
Django-Python: How to Grab Alias Outlook Email in the form of JSON
I am trying to grab the alias email addresses created within the main account. How am I able to grab the JSON for all of the alias email addresses and then grab all the calendar events contents? Here is the layout of my code: https://github.com/reportex-development/Lobby-Menu/tree/main/Lobby-menu-v2-here I see that in the tutorial > graph_helper.py there is something that's trying to get_calendar_events but it seems like it is only for that one main account but I want to see all the events in the alias accounts. -
Is it possible to allow dependabot on GitHub to automatically "bump" software to new version?
Please help this learner out: I get frequent GitHub's dependabot alerts for "bumping" software versions to a more current one. My issue is I have to go into each (in my case, Django) app to pull or merge files. It tedious and time consuming to deal with my limited number of apps. How do professionals manage the process? Is there a way to allow GitHub just bump whatever needs to be bumped (assuming one doesn't mind apps being broken)? -
Django: convert DateField to string using DATE_FORMAT
I want to convert a Django DateField to a string according to the DATE_FORMAT as specified in settings.py, where I have a certain date format hard-coded. Can it be done without specifying a second (and at best superflous) date format for, e.g., strftime? -
Got an error creating the test database: database "DATABASE_NAME" already exists
I'm trying to run tests in my Django app and I suddenly started getting this error. When I go to run a test, it first tells me that the database already exists. Creating test database for alias 'default'... Got an error creating the test database: database "DATABASE_NAME" already exists Type 'yes' if you would like to try deleting the test database 'DATABASE_NAME', or 'no' to cancel: I type yes to delete the test database. At which point I get this error: Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/x/Django/myapp/./manage.py", line 23, in <module> main() File "/Users/x/Django/myapp/./manage.py", line 19, in main execute_from_command_line(sys.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 643, in setup_databases return _setup_databases( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/utils.py", line 179, in setup_databases connection.creation.create_test_db( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 74, in create_test_db call_command( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute … -
Nginx, Gunicorn, Django, Postgresql concurrency handle?
I have so many confusion on my mind about concurrency handling . I am new about this concurrency handle so everything is feels like overwhelming . First thing is suppose I can handle 10k concurrent requests with nginx . (1) can Gunicorn handle 10k concurrent requests? (2) If Gunicorn can handle 10k requests how will posgresql response to this. (3) Did Django App Create new database connection for every request(unique user) ? If this happend, How will Postgres handle 10k connection ? -
Won't able to zoom after including chartjszoom in chartjs
Failed to zoom after include the correct version of chartjs and chartjs-plugin-zoom. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.7/dist/chartjs-plugin-zoom.min.js"></script> This is my canvas tag <div class='chart-wrapper'> <div class="training-chart-area" style="width: 768px; height: 384px;"> <canvas id="trainingChart1"></canvas> </div> </div> My plugin option in my chart js function options: { plugins: { zoom: { zoom: { enabled: true, mode: 'y' }, pan: { enabled: true } } } I know I have the correct version because I tested it with another HTML file. I thought the problem may be chartjs-plugin-zoom won't work with multiple datasets within one chart, but test HTML worked perfectly fine. I have no idea where went wrong. -
How to filters field using django-filter
I need to create some filters for one table but cannot get it to work. When clicking on the Search button nothing happens. Ideally, I would like to get be able to select one or multiple category and get the results displayed with the number of objects counted. Did I missed anything in my code? Thank you models.py class Lead(models.Model): CATEGORY = ( (0, 'Education'), (1, 'Hotel'), (2, 'Construction'), (3, 'Residential'), (4, 'Facility Management'), ) businessname = models.CharField(max_length=150,blank=True, null=True) businesscategory = models.IntegerField(choices=CATEGORY, blank=True, null=True) filters.py import django_filters from .models import Lead class LeadFilter(django_filters.FilterSet): businessname = django_filters.CharFilter(lookup_expr='icontains') businesscategory = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Lead fields = ['businessname','businesscategory'] views.py @login_required(login_url="/login/") def index_leads(request): leads = Lead.objects.all() lead_filter = LeadFilter(request.GET, queryset=leads) context = { 'leads': leads, 'filter':lead_filter, } return render(request, 'analysis/index_leads.html', context) index_leads.html <form method="get"> <div class="container-fluid"> <h4 style="margin-top: 0"></h4> <div class="row"> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businesscategory.label_tag }} {% render_field filter.form.businesscategory class="form-control" %} </div> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businessname.label_tag }} {% render_field filter.form.businessname class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary float-right"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> -
Django with Unicorn losing thread local storage during requst
I've set up a request-scope cache using middleware and tried to set it to be available from anywhere using threading.local() variable. However, sometimes long requests processes drop with the following error: File "label.py", line 29, in get_from_request_cache label = cache.labels[url] AttributeError: '_thread._local' object has no attribute 'labels' However, some of the items get processed correctly, and they all depend on existence of that cache. The cache object is initialized once and is cleared at the end of the request using the following middleware: request_cache.py import threading _request_cache = threading.local() def get_request_cache(): return _request_cache class RequestCacheMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): global _request_cache response = self.get_response(request) _request_cache.__dict__.clear() return response def process_exception(self, request, exception): _request_cache.__dict__.clear() return None And the only code that accesses the cache object directly is this part: label.py import django.db.models from request_cache import get_request_cache from base import Model class Label(Model): **model fields** @staticmethod def create_for_request_cache(urls): cache = get_request_cache() urls = set(urls) if not hasattr(cache, 'labels'): cache.labels = {} new_urls = urls.symmetric_difference(set(cache.labels.keys())) entries = [Label(url=url) for url in new_urls] if entries: Label.objects.bulk_create(entries) for entry in entries: cache.labels[entry.url] = entry @staticmethod def get_from_request_cache(url): cache = get_request_cache() label = cache.labels[url] return label The request that crashes is split … -
In Wagtail is there a way to have a listing/index page list sub pages in a manually specified order without the InlinePanel listing every field?
I want to have a page (/blog/) that lists sub-pages. But I don't want to order them by most recent or anything like that. I want to order them in a manually specified way. I'd love to use an Orderable on the sub-pages, but the only way I've been able to get that to work is if I use an InlinePanel. The problem with an InlinePanel, is then Wagtail will show each page inlined with every field, and each page can be really long. Is there a way to use InlinePanel, but only show the title of each page vs. every single field? Or is there a better way to do this in Wagtail? -
How to empty a many to many field in django
I would like to empty all things within the following many to many field(weekday_with_class): all_existing_class.weekday_with_class = None Here is the models.py: weekday_with_class = models.ManyToManyField('Weekday', blank=True, related_name='weekday_with_class') However, if I execute the above code, I get this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use weekday_with_class.set() instead. How is it possible to basically make my weekday_with_class empty for an instance? Thank you, and please leave a comment if you need any more information. -
Is there such a thing as a conditional "ON DELETE CASCADE" in Django?
Is there a simple way, using on_delete, to delete the object containing a ForeignKey when that ForeignKey is deleted (like models.CASCADE would normally do) but just the ForeignKey relationship to None if some condition is met (like models.SET_NULL would normally do). Here is some code: class SomeThing(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="things", on_delete=models.CONDITIONAL_CASCADE, # obviously this is wrong ) is_private = models.BooleanField(default=False) >>> user = User(username="bob").save() >>> public_thing = SomeThing(is_private=False) >>> private_thing = SomeThing(is_private=True) >>> user.things.add(public_thing) >>> user.things.add(private_thing) >>> user.delete() When user is deleted I would like private_thing to be deleted along w/ user, but public_thing to not be deleted and for public_thing.user to be set to None. Thanks. -
Error while using signals, Django doesnt see a inbuild User model app_label
I'm learning django signals and when I'm trying to use simple one which creates Profile directly after new User is created( by default django User model) and whenever I try to runserver, I get this error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. HOWEVER: django.contrib.contenttypes is in INSTALLED_APPS I'm newbie and I'm stuck..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'bootstrapform', 'basic', ] # urls """Filmweb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from basic.views import Main, ActorsListView, ActorModifyView, ActorCreateView, \ ActorDeleteView, Films, FilmCreateView, FilmModifyView, FilmDeleteView, Register, RateIt, FilmDetails, Profile, \ RolesView, RoleModifyView, RestFilmView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ … -
Import recipe from a website using Django REST Framework and React Native
So I am working on a meal planning mobile application and have seemed to hit a roadblock. Apparently, the client wants a feature where if a user clicks on the "Import Recipe" Button in the application, A browser should open which would allow the user to surf the internet and if the client lands on a page that has a recipe listed. The application detects that feature and gives the user a pop-up that "a recipe has been found on this page, Would you like to add it?". I am a bit stuck on how to approach this problem. Any guidance in the right direction would be a great help. Kind Regards. Tech Stack is React Native on the Front-End and Django REST Framework on the backend -
Converting function based views to class based views
I'm trying to convert this function based view to a class based view by using the existing CreateView functionality: def manager(request): if request.method == 'POST': if request.POST.get('q3_name3[first]'): SEND = Manager() SEND.first_name = request.POST.get('q3_name3[first]') SEND.last_name = request.POST.get('q3_name3[last]') SEND.gender = request.POST.get('q4_gender4') SEND.address = request.POST.get('q6_address') SEND.phone_number = request.POST.get('q8_phoneNumber[full]') SEND.birth_date = request.POST.get('q9_birthDate') SEND.save() return render(request, 'manager.html') else: return render(request, 'manager.html') However I already have a form created using HTML and I've only come across tutorials that let Django automatically create the form. How can I use my existing form and convert this into a class based view using CreateView? Is there a way to tell Django to take this input box ID as the data in the Object?