Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"proxy_pass" directive is duplicate
Getting the error: nginx: [emerg] "proxy_pass" directive is duplicate in /etc/nginx/sites-enabled/mhprints:12 nginx: configuration file /etc/nginx/nginx.conf test failed when trying to run my django project on nginx and gunicorn. my settings in folder error points to: server { listen 80; server_name 194.146.49.249; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/dave/mhprints; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Can't find a fix, hoping somebody knows on here. -
Question for starting django web (beginner))
I have experienced problem in creating my own page on django. I follow the tutorial but get the different results. The error is page not found and Using the URLconf defined in djangonautic.urls, Django tried these URL patterns, in this order: admin/ about/ ^$ The empty path didn’t match any of these.It would be appreciate if someone can help me: urls.py from django.contrib import admin from django.urls import path from. import views urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^about/$', views.about), path(r'^$', views.homepage), path(r'^$', views.index), ] views.py from django.http import HttpResponse from django.shortcuts import render def about(request): return HttpResponse('my name is Jacky') def homepage(request): return HttpResponse('welcome home') def index(request): return HttpResponse("Hello, world I am the king") The web page will be display normally, no 404 is found -
"django.db.utils.OperationalError: no such function: lwgeom_version" Django Version 3.2.16, Spatialite Version 4.2.0 on Windows 10
I have a Django application that uses some geographic information. I have installed GDAL and installed Spatialite by downloading the windows binaries and placing them in my python directory (conda environment in my case) as detailed in this post. That was the only way I was able to get it to work without throwing an error. My database is set in settings.py as DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': BASE_DIR / 'db.sqlite3', } } When I try to test a query based on geographic coordinates such as loc = Point(location['lng'], location['lat']) radius = D(mi=20) queryset = BusinessProfile.objects.filter(businessAddress__coordinates__dwithin=(loc, 2.0)) \ .filter(businessAddress__coordinates__distance_lte=(loc, radius)) \ .annotate(distance=Distance("businessAddress__coordinates", loc)) \ .order_by("distance") I get the following error: django.db.utils.OperationalError: no such function: lwgeom_version I have already installed GDAL and spatialite, can anyone help me figure out what the problem could be here? -
Send a audio recorded file from frontend to django view
Hi im trying to send a recorded audio to django backend. I used js to record the audio, How can i send it to django backend view (Maybe using POST method). Frontend: ` <button type="button" id="record">Record</button> <button type="button" id="stopRecord" disabled>Stop</button> </p> <p> <audio id=recordedAudio></audio> <script> navigator.mediaDevices.getUserMedia({audio:true}) .then(stream => {handlerFunction(stream)}) function handlerFunction(stream) { rec = new MediaRecorder(stream); rec.ondataavailable = e => { audioChunks.push(e.data); if (rec.state == "inactive"){ let blob = new Blob(audioChunks,{type:'audio/mp3'}); recordedAudio.src = URL.createObjectURL(blob); recordedAudio.controls=true; recordedAudio.autoplay=true; sendData(blob) } } } function sendData(data) {} record.onclick = e => { record.disabled = true; record.style.backgroundColor = "blue" stopRecord.disabled=false; audioChunks = []; rec.start(); } stopRecord.onclick = e => { record.disabled = false; stop.disabled=true; record.style.backgroundColor = "red" rec.stop(); } </script> ` How can I send this recorded audio to django view? Thank you. I want to get this recorded audio file into my django views.py. -
Forbidden Apache/2.4.41 (Ubuntu) Server at djangoexample.ru Port 80
does not work on remote hosting VDS django example on request in the console (env) root@vm2212126314:~/django_project# tail -f /var/log/apache2/error.log response [Wed Dec 14 23:07:46.528001 2022] [core:error] [pid 15644:tid 139855996606208] (13)Permission denied: [client 198.16.66.157:44077] AH00035: access to / denied (filesystem path '/root/django_project') because search permissions are missing on a component of the path [Wed Dec 14 23:07:48.259732 2022] [core:error] [pid 15644:tid 139856175347456] (13)Permission denied: [client 198.16.66.157:44077] AH00035: access to / denied (filesystem path '/root/django_project') because search permissions are missing on a component of the path [Wed Dec 14 23:07:50.125290 2022] [core:error] [pid 15644:tid 139856166954752] (13)Permission denied: [client 198.16.66.157:44077] AH00035: access to / denied (filesystem path '/root/django_project') because search permissions are missing on a component of the path [Wed Dec 14 23:11:51.679078 2022] [core:error] [pid 15645:tid 139856208918272] (13)Permission denied: [client 104.164.195.218:35699] AH00035: access to / denied (filesystem path '/root/django_project') because search permissions are missing on a component of the path how fix it <Directory /root/django_project> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all Require all granted </Directory> ??? -
Django - Unable to write an interconected service layer
For several days I've been trying to implement a service layer in Django, to separate business logic from models and views. The way I do it is the following (as a example): from api.services.BoatService import BoatService class ApplicationService:boatService = BoatService() def find(self, application_id, user_id): #some business logic for search an object, raise custom exception, etc application = self.applicationService.find(args) In a different file: from api.services.ApplicationService import ApplicationService class BoatService: applicationService = ApplicationService() def find(self, boat_id, user_id): #some business logic for search an object, raise custom exception, etc boat = self.applicationService.find(args) The problem comes when I try to use methods from ApplicationService into BoatService, because I got the expected ImportError: cannot import name 'BoatService' from partially initialized module 'api.services.BoatService' (most likely due to a circular import). I need to implement dependency injection like Spring Boot (annotating with @service/@autowired) or anything that will allow me to use methods from both service interconnected (like another normal service in other framework) -
Type Validation in Django's JSONField
Problem Statement I have a Django model containing a JSONField among other fields: class MetaData(models.Model): main = models.ForeignKey() name = models.CharField() dict_field = models.JSONField() Where dict_field is a "data dump" for any remaining metadata that i don't want to include as a standalone field. Although it's a data "dump", I still want it to have basic type-validation. How can I validate the inputs of this JSONField such that it only accepts a pre-defined list of keys and their associated types, as follows: "key1": bool "key2": int "key3": Optional[int] Does django have functionality built in for this type of problem? If not, what other solutions can you recommend? (pydantic, etc.) -
sub domain pointed to the wrong website folder
I have a linux server that run multiple different website on multiple different domain which are working fine. But I created a sub domain for one of the domain which is demo.mywebsitedomain.com I did the configuration like it was a different domain which mean I created a specific nginx socket / service / nginx config file for this subdomain But when I go the my link demo.mywebsitedomain.com it run the website application of an other django application folder, it not the one who I have pointed in the socket and service file. I am verry confuse. It should run the django application whos in the testdemo folder but instead it run a different folder application. Those are the file I created for the subdomain sudo vim /etc/systemd/system/testdemo.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/testdemo.sock Environment="PATH=/usr/bin:/home/tiber/testdemo/env/bin" [Install] WantedBy=sockets.target sudo vim /etc/systemd/system/testdemo.service [Unit] Description=gunicorn daemon Requires=testdemo.socket After=network.target [Service] User=tiber Group=www-data WorkingDirectory=/home/tiber/testdemo ExecStart=/home/tiber/testdemo/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/testdemo.sock \ mysite.wsgi:application [Install] WantedBy=multi-user.target sudo vim /etc/nginx/sites-available/testdemo server { listen 80; server_name demo.mywebsitedomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/testdemo; } location /media/ { root /var/www/testdemo; } location / { include proxy_params; proxy_pass http://unix:/run/testdemo.sock; } } -
Error in installing Django and running Django-admin
I'm encountering an issue while installing Django. The error after typing in 'django-admin' persists e even after adding the directory to PATH code adding directory to PATH I was trying to install django and expected to see a list of available subcommands on typing django-admin afterwards -
Django how can i style the checkboxes in CheckboxSelectMultiple as buttons
I have a project that i am working on and this is for the buy page. Chosen_services is a many to many field and this is my forms.py: class Meta: model = Order fields = ["chosen_services"] widgets = { 'chosen_services': forms.CheckboxSelectMultiple() } I want the checkboxes to be styled as btn btn-primary and the text on the button to be 'add' when the checkbox is not checked and i want it to be styled as btn btn-secondary and have the text 'remove' when the checkbox is checked. Unclicked Clicked I tried making a custom widget but i couldn't get it to work. I also tried to add attrs={'class': 'btn btn-primary'} but when i had this the parent element of the checkboxes got styled as a button and the checkboxes still remained checkboxes but where inside the button. I want to replace the checkbox not put it inside a button. -
Creating a simple multiple users app in django
So I've got three users, a teacher, student, and admin. Both teacher and student users work fine but when I try to login using the admin form, it redirects to the student login form. I think it's because there's something wrong with the urls.py and the way the next parameter is configured but I'm not quite sure where to proceed. Any help is much appreciated. Let me know if you need more information Here are my admin views.py @login_required @admin_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) main urls.py urlpatterns = [ path('', classroom.home, name='home'), path('students/', include(([ path('', students.QuizListView.as_view(), name='quiz_list'), path('interests/', students.StudentInterestsView.as_view(), name='student_interests'), path('taken/', students.TakenQuizListView.as_view(), name='taken_quiz_list'), path('quiz/<int:pk>/', students.take_quiz, name='take_quiz'), ], 'classroom'), namespace='students')), path('teachers/', include(([ path('', teachers.QuizListView.as_view(), name='quiz_change_list'), path('quiz/add/', teachers.QuizCreateView.as_view(), name='quiz_add'), path('quiz/<int:pk>/', teachers.QuizUpdateView.as_view(), name='quiz_change'), path('quiz/<int:pk>/delete/', teachers.QuizDeleteView.as_view(), name='quiz_delete'), path('quiz/<int:pk>/results/', teachers.QuizResultsView.as_view(), name='quiz_results'), path('quiz/<int:pk>/question/add/', teachers.question_add, name='question_add'), path('quiz/<int:quiz_pk>/question/<int:question_pk>/', teachers.question_change, name='question_change'), path('quiz/<int:quiz_pk>/question/<int:question_pk>/delete/', teachers.QuestionDeleteView.as_view(), name='question_delete'), ], 'classroom'), namespace='teachers')), path('admins/', include(([ path('', admins.profile, name='profile'), ], 'classroom'), namespace='admins')), ] login urls.py urlpatterns = [ path('', include('classroom.urls')), path('accounts/', include('django.contrib.auth.urls')), … -
How to return an image as a response in Django
Doing a POST request to GPT-3 in order to get code completion output when I send some input. I seem to be getting the response I expect, but cannot actually get the code written by GPT-3. This is the response I get: ".\n\n## Challenge\n\nWrite a function called `preOrder` which takes a binary tree as its only input. Without utilizing any of the built-in methods available to your language, return an array of the values, ordered from left to right as they would be if the tree were represented by a pre-order traversal.\n\n## Approach & Efficiency\n\nI used a recursive approach to solve this problem. I created a function called `preOrder` that takes in a binary tree as its only input. I then created a variable called `output` that is an empty array. I then created a function called `_walk` that takes in a node as its only input. I then created a base case that checks if the node is null. If it is, it returns. If it is not, it pushes the value of the node into the `output` array. It then recursively calls the `_walk` function on the left and right nodes of the node. It then returns the … -
Ubuntu, Django, Gunicorn and Nginx
I've followed the digital ocean tutorial step by step in trying to get my project up and running using the packages in the title of this post. I keep getting an error returned and I cannot fix it. I've gone through the tutorial multiple times and still leads to same errors. Heres what I followed: Tutorial ERROR: nginx: [emerg] unknown directive "http://unix:/run/gunicorn.sock" in /etc/nginx/sites- enabled/mhprints:9 nginx: configuration file /etc/nginx/nginx.conf test failed SITES-ENABLED file server { listen 80; server_name mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/dave/mhprints; } location / { include proxy_params; http://unix:/run/gunicorn.sock; } } Any one have any idea? Thank you in advance for your time. -
How to get data for a given search query
I have a table for ManyToMany relationship. Where each Tutor need to input multiple days that he wants to tutor student. Like: Availability Tutor: user available_day time t1 Sun 6,7,8 t2 mon 3,4 t1 mon 1,2 I would like to get all tutor where availablity is based on search day. Model: class TutorProfile(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tutor_availablility = models.ManyToManyField( Day) queryset: def get_queryset(self): subject_param = self.request.GET.get('subject') bookday = self.request.GET.get('book_day') grade = self.request.GET.get('grade') li = list(bookday.split(",")) print("Book Info:", li) for i in range(len(li)): print(li[i]) _day_name = datetime.strptime(li[i], "%d-%m-%Y").strftime("%A") print("Day Name:", _day_name) day_num = Day.objects.get(day_name=_day_name) print("Day_Num",day_num) result = TutorProfile.objects.filter( tutor_availablility=day_num).all() return result When I run this query it only loop over one time for one day but not for multiple days. Now how may I run this query so that it will not stop after one loop. After One loop it says: An exception occurred An exception occurred I tried to apply try catch block here. But getting no clue. Why stop loop after one cycle? -
missing FROM-clause in posgressql
I'm facing the below error while executing the below SQL statement in Django after converting from sqlite to postgressql, it was working fine with sqlite. joined_data = HistoryTable.objects.raw( ''' SELECT pages_historytable.id, pages_historytable.dial, pages_historytable.request_status, pages_historytable.summary, pages_historytable.registration_date, dashboard_storesemails.emails, dashboard_storescode.agent_name FROM pages_historytable LEFT JOIN dashboard_storescode ON pages_historytable.dial = dashboard_storescode.dial LEFT JOIN dashboard_storesmails ON dashboard_storescode.shop_code = dashboard_storesmails.dtscode WHERE pages_historytable.request_status = 'Rejected' AND pages_historytable.Today_Date = %s; ''',[today]) The error is missing FROM-clause entry for table "dashboard_storesemails" LINE 2: ...le.summary, pages_historytable.registration_date, dashboard_... -
How to keep parameters next when going to another page Django
How can I keep this parameter next= from the url http://127.0.0.1:8000/login/?next=/checkout/ when i click on a href to access another page http://127.0.0.1:8000/register/ def login(request): .... .... auth.login(request, user) url = request.META.get('HTTP_REFERER') try: query = requests.utils.urlparse(url).query # next=/checkout/ params = dict(x.split('=') for x in query.split('&')) if 'next' in params: nextPage = params['next'] return redirect(nextPage) except: return redirect('home') This is on the login page, and I need that if this href is clicked it continues the parameters next=/checkout/ on the register page -
Django VSCode debugging going wrong
I'm studing some Django, mainly DRF, but some times what i do goes different of what my instructor does. Actually, i'm now facing a problem when I try to debug my code with the VSCode debugger, as he does in the classes, where, when he starts the application with the debugger, it starts normally, but when he makes a requests that passes by a certain view or serializer, the application stops at the breakpoint and wait his commands, like a normal debug. When I try the same, as the application starts, it first stops at the breakpoints, while Django is performing the system checks, and then does not stops when the request passes by the view, for example. The only step he made to configure the debugger was creating the launch.json file the VSCode recommends, here is an example of mine: { // Use o IntelliSense para saber mais sobre os atributos possíveis. // Focalizar para exibir as descrições dos atributos existentes. // Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": false, "program": "${workspaceFolder}\\src\\manage.py", "args": [ "runserver", ], "django": true, "justMyCode": false } ], } with these settings, the … -
django model form instance update / how to show only previously selected options and hide the rest
I need to completely hide just the "select" while creating new object and partialy show only previously selected while "update" without javascript if it is possible. thank you for any advice code in views.py ` def topic_create(request): form = TopicForm() if request.method == 'POST': new_tags = request.POST.get('new_tags').replace(',', " ").split() form = TopicForm(request.POST, request.FILES) if form.is_valid(): topic = form.save(commit=False) topic.save() for tag in new_tags: tag, created = Tag.objects.get_or_create(name=tag) topic.tags.add(tag) return redirect('topics') context = {'form': form} return render(request, 'blog_app/topic_form.html', context) def topic_update(request, pk): topic = Topic.objects.get(id=pk) form = TopicForm(instance=topic) if request.method == 'POST': new_tags = request.POST.get('new_tags').replace(',', " ").split() form = TopicForm(request.POST, request.FILES, instance=topic) if form.is_valid(): topic = form.save() for tag in new_tags: tag, created = Tag.objects.get_or_create(name=tag) topic.tags.add(tag) return redirect('topics') context = {'form': form} return render(request, 'blog_app/topic_form.html', context) ` this code in my form.py ` class TopicForm(ModelForm): class Meta: model = Topic fields = '__all__' widgets = { 'tags': forms.CheckboxSelectMultiple(), } ` and this is the template ` {% block content %} <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <div class="form__field"> <label>Add New</label> <textarea name="new_tags" placeholder="Separate with space or comma"></textarea> </div> … -
Export only the data registered by the user / Django import-export
Products can be exported in excel format from the Product table. But all the user's products are exported. How can I export only request.user's products? Here is view : def export_excel(request): dataset = ProductResource().export() response = HttpResponse(dataset.xlsx, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response["Content-Disposition"] = "attachment; filename=Products-" + str(datetime.datetime.now().date())+".xlsx" return response Here is resources.py : class ProductResource(resources.ModelResource): author = Field() brand_id = Field() class Meta: model = Product fields = ["id", "author", "brand_id", "name", "barcode", "unit"] export_order = ["id", "author", "brand_id", "name", "barcode", "unit"] def dehydrate_author(self, product: Product) -> str: return f"{product.author.username}" def dehydrate_brand_id(self, product: Product) -> str: return f"{product.brand_id.name}" -
User doesnt save to database Django
views.py def registerPage(request): form = UserCreateForm() if request.method=='POST': form=UserCreateForm(request.POST) if form.is_valid(): user=form.save(commit=False) user.save() return redirect('home') return render(request,'base/signup.html',{'form':form}) model.py class User(AbstractUser): name = models.CharField(max_length=200,null=True) email = models.EmailField(unique=True,null=True) bio=models.TextField(null=True) avatar = models.ImageField(upload_to='images/',null=True) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] forms.py class UserCreateForm(UserCreationForm): class Meta: model = User fields = ['name','email','password1','password2','bio','avatar'] when ever i try to sign up on html template it doesnt work but if i do it in admin panel it works how can i solve it ? -
Celery testing Django and how to properly raise an exception in a celery task and assert a retry
I have a Celery task in a Django project that sends an email utilising Django's EmailMultiAlternatives. I want to raise a ConnectionError to trigger a retry. The task works well in practice, with retries being attempted as expected when a ConnectionError exists, but I now want to test it. my_app.mailer.tasks.py from django.core.mail import EmailMultiAlternatives @app.task(bind=True, max_retries=4, base=BaseTaskEmail, ) def send_mail(self, *args, **kwargs): msg = EmailMultiAlternatives({some_data}) msg.attach_alternative({some_data}) try: msg.send(fail_silently=False) except ConnectionError as exc: self.retry(countdown=backoff(self.request.retries), exc=exc) I made the following attempt at testing, which results in an AssertionError: raise AssertionError(_error_message()) from cause AssertionError: expected call not found. Expected: send(exc=ConnectionError()) Actual: send(fail_silently=False) test.py class SendMailTest(TestCase): def setUp(self): self.message = {} @patch('my_app.mailer.tasks.EmailMultiAlternatives.send') @patch('my_app.mailer.tasks.send_mail.retry') def test_retry(self, mock_send, mock_retry): mock_send.side_effect = Retry() mock_retry.side_effect = error = ConnectionError() with raises(Retry): send_mail(kwargs=self.message) mock_retry.assert_called_with(exc=error) My question is, how I can correctly raise an exception in this task and assert that a retry has been called by the correct exception, in this case a ConnectionError. Additionally, if possible, assert that the correct number of retires have been attempted? -
How to merge queryset multiple dictionaries with common date value(not key) in django?
I have result queryset dictionaries like this. <QuerySet [ {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}, {'tags__name': 'Device', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}, {'tags__name': 'Device', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}, {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')} ]> I want result like this {'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')} {'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')} Any help will be appreciated. -
Django - Keep data filtered trough the duration of the session using django-filters
I have a view that lists all data from a model with a form that enables filtering using the django-filters library. The view also stores the filtered data in the session, inside the form_data variable. The view: def list_accsplan(request): accsplan = AccountsPlan.objects.all().order_by('code') accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan) request.session['form_data'] = accsplanfilter.data form_data = request.session.get('form_data') paginator = Paginator(accsplanfilter.qs, 30) page = request.GET.get('page') try: dataqs = paginator.page(page) except PageNotAnInteger: dataqs = paginator.page(1) except EmptyPage: dataqs = paginator.page(paginator.num_pages) return render(request, 'confi/pages/accounts_plan/list_accsplan.html', context={ 'accsplan': accsplan, 'accsplanfilter': accsplanfilter, 'dataqs': dataqs, }) The filter form is this: class AccountsPlanFilter(django_filters.FilterSet): accplantype = ChoiceFilter(choices=AccountsPlan.AccPlanType.choices, field_name='accplantype',) code = CharFilter(field_name='code', lookup_expr='icontains',) name = CharFilter(field_name='name', lookup_expr='icontains',) active = BooleanFilter(field_name='active', widget=CustomBooleanWidget,) class Meta: model = AccountsPlan fields = '__all__' What I want is to keep this list filtered as long as the session is active, even if the user changes pages and then get back to this one, but I'm stuck in how to do this. I tried to add an if statement in the view like this: if form_data: accsplan = AccountsPlan.objects.filter(**form_data) accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan) But I receive this ValidationError in the list: ValidationError at /list_accsplan/ ["the value “['true']” must be True ou False."] I was thinking that this was because I … -
How to model many-to-many database with 3 tables
I'm working on a django backend and I'm trying to model a database and want to do it the best practice way. I need a "User" table, a "Portfolios" table and a "Stocks" table. A user can have multiple portfolios which consist of multiple stocks. This is my code so far: class User(models.Model): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=25) in_cash = models.DecimalField(max_digits=15, decimal_places=2) class Portfolios(models.Model): portfolio_id = models.AutoField(primary_key=True) user_id = models.ForeignKey("User", on_delete=models.CASCADE) stock_id = models.ForeignKey("Stocks", on_delete=models.CASCADE) buy_datetime = models.DateTimeField(default=datetime.now, blank=True) number_of_shares = models.IntegerField() class Stocks(models.Model): stock_id = models.AutoField(primary_key=True) stock_symbol = models.CharField(max_length=12) In my head I would have an entry in the "Portfolios" table for each stock of a portfolio. So "Portfolios" would look like portfolioid 1, userid: 1, stockid: 1, buydate: 12.01.2019, shares: 20 portfolioid 1, userid: 1, stockid: 2, buydate: 19.02.2020, shares: 41 So there is one portfolio, which contains two stocks. But overall that doesn't seem right. If used like in my example above I can't have the portfolioid as a primary key, how can I improve this? Thanks for your time -
can i use default argument on foreignkey?
i added a str default to foreign key but when i tried to create superuser i got error with this argument : ValueError: Field 'id' expected a number but got 'personal'. heres my code : class Genders(models.Model): get_gender = models.TextField() class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True,validators=[ MaxValueValidator(100),MinValueValidator(6)]) gender = models.ForeignKey(Genders,default='personal',on_delete=models.CASCADE) can you help with this problem ? im learning django cant debug yet but i thought maybe problem is that superuser doesnt have a gender value