Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Password Reset timeout
Whenever I want to reset password, my browser goes timeout. I have the same EMAIL_HOST_USER and EMAIL_HOST_PASSWORD than in dev environment, yet it doens't work in Production. settings.py with open('/etc/config.json') as config_file: config = json.load(config_file) LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = config.get('EMAIL_PASSWORD') config.json { "SECRET_KEY":"***", "EMAIL_USER":"***", "EMAIL_PASSWORD":"***" } -
Show checkbox only when a specific form-field is non-empty (Django)
I have a model class my_model(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) last_price = models.FloatField(default=0) will_buy= models.BooleanField(default=False) and my form class my_form(forms.ModelForm): class Meta: model = my_model In my template I want will_buy first being visible when last_price is filled in. Best of all will be as a kind "slow unpacking", but first of all I just need it to be hidden when last_price is empty. -
pipenv virtual environment name disappears everytime the VS Code terminal is refreshed
I was working on a Django project after activating the virtual environment created through pipenv. The virtual environment name given in brackets (lead-manager-full-stack-8btqndKQ) in the vs code terminal disappears everytime i runpython manage.py runserver When i select the powershell as terminal and runs pipenv shell again in order to activate the environment again it shows : Shell for C:\Users\USER.virtualenvs\lead-manager-full-stack-8btqndKQ already activated. No action taken to avoid nested environments. But it still doesn't show the virtual environment name inside the brackets like it is supposed to show. Then i tried to run pipenv shell in cmd and this time it shows the virtual environment name in bracket in the terminal. But whenever i reload the terminal or choose new terminal, it doesn't show the virtual environment. There must be a way to activate the virtual environment at all time, even after reloading the terminal if i am in a folder containing virtual environment right? Because activating virtual environment everytime i reloads the terminal doesn't seem like a good approach. -
Django tables connection
I have 3 django tables connected like this: Is there anyway to make a querry for table Table that will get id_equip from table equip? models.py class Vendor(models.Model): vendor_name = models.CharField(max_length=50) def __str__(self): return self.vendor_name class Equipment(models.Model): equipment_name = models.CharField(max_length=50) id_vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None) def __str__(self): return self.equipment_name class Table(models.Model): table_name = models.CharField(max_length=100) id_vend = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None) id_equip = models.ManyToManyField(Equipment) -
Shiftleft scan (SLS) vulnerability on read_excel of uploaded file
I'm working on a website using Django and to be safe we run everything through shiftleft scan. The website allows user to import "assignments" using an excel file. The question is: how do I do this safely such that it is shiftleft scan compliant? The code: class ImportView(generic.FormView): template_name = 'assignments/import.html' form_class = ImportForm success_url = reverse_lazy('assignment_import') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): # handle upload here assignments = pd.read_excel(request.FILES['file'].file) for i, assignment in assignments.iterrows(): assignment_obj = Assignment() assignment_obj.name = assignment['name'] assignment_obj.save() return self.form_valid(form) else: return self.form_invalid(form) The ciritical vulnerability the SLS returns: { "rule_id": "taint-traversal", "rule_name": "Directory Traversal", "severity": "CRITICAL", "cwe_category": "CWE-22", "owasp_category": "a5-broken-access-control", "source": { "label": "request", "line_number": 188, "path": "/app/survey/views.py" }, "source_trigger_word": "Framework function URL parameter", "source_type": "Framework_Parameter", "sink": { "label": "~call_2 = ret_pandas.read_excel(request.FILES[file].file, ...", "line_number": 196, "path": "/app/survey/views.py" }, "sink_trigger_word": "read_excel(", "sink_type": "Exfiltration", "type": "Vulnerability", "reassignment_nodes": [], "description": "Exfiltration of data (Path Traversal) due to user data from `request in views.py:188` influencing file operations in `views.py:196`.", "short_description": "Exfiltration of data (Path Traversal) due to user data from `request in views.py:188` influencing file operations in `views.py:196`." }, My MEDIA_ROOT is setup as follows (from settings.py, I realize that mix the pathlib.Path with os.path, … -
AttributeError: module 'djangoschool' has no attribute 'wsgi'
I once finished deploy it on another server without this error, but I try this with new server and install my new window server 2019.I start do it again but it got an error. I deploy my django project on IIS.I follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ When I browse my website on localhost. It got error messages like this. Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python37\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'djangoschool' has no attribute 'wsgi' StdOut: StdErr: web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python37\python.exe|c:\python37\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub2\wwwroot\djangoschool" /> <add key="WSGI_HANDLER" value="djangoschool.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="djangoschool.settings" /> </appSettings> </configuration> settings.py """ Django settings for djangoschool project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
I am unable to format the logic for my project models in django
I'm working on a student result management app. I have other parts working but the logic of the marks entry and model creations have sent me lost. I need entry for marks for the various subjects for a group of students(students in particular streams for specific exams). A student belongs to a stream which belongs to a class which belongs to a particular school. I've created models for Marks, Subjects, School, Klass, Exam, Stream, Student. I've had no issues with the Student, Klass, Stream and School models. My problem is on the entry of the marks. Should I have Subjects and Marks models or can all these be put in one model or does each subject have it's model? Here are my trials. class Students(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE,help_text='A school must have a name') adm = models.IntegerField(unique=True,validators=[MinValueValidator(0), MaxValueValidator(1000),] ) name = models.CharField(max_length=200,help_text="Student's name") klass = models.ForeignKey(Klass, on_delete=models.CASCADE,null=True) stream = models.ForeignKey(Stream,on_delete=models.CASCADE,null=True) class Klass(models.Model): name = models.CharField(max_length=20,help_text='Class/Form in the school') school = models.ForeignKey(School,on_delete=models.CASCADE) class Stream(models.Model): name = models.CharField(max_length=50) klass = models.ForeignKey(Klass,on_delete=models.CASCADE) school = models.ForeignKey(School,on_delete=models.CASCADE) class Exam(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.SET_NULL, null=True) term = models.ForeignKey(Term,on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=20) klass= models.ManyToManyField("students.Klass", related_name='klass',) class Marks(models.Model): school = models.ForeignKey(School,on_delete=models.SET_NULL,null=True,blank=True) year = models.ForeignKey(Year,on_delete=models.SET_NULL,null=True,blank=True) term = … -
Centos OS apache Django web app 500 Internal Server Error
I want to deploy my django website on Centos 8. My application is in /var/www/html/myproject. I created a new conf file (myproject.conf) in /etc/httpd/conf.d Alias /static/ /var/www/html/myproject/static/ WSGIScriptAlias / /var/www/html/myproject/myapp/wsgi.py WSGIPythonPath /var/www/html/myproject <Directory /var/www/html/myproject/myapp> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/html/myproject/static> Require all granted </Directory> When I restart the apache and I put the ip address, I have a 500 Internal Server Error. I don't understand why I got this error. Thank you for your help. -
Go to specific page using Django Pagination with restframework
I have a question about going to specific page using pagination in Django restframework. (Data needs to be rendered to HTML) Example: model.py class Book(models.Model): title = models.CharField(max_length=30) author = models.CharField(max_length=30) views.py class BookListView(viewsets.ModelViewSet): permission_classes = (AllowAny, ) template_name = 'booklist.html' queryset = Book.objects.all() renderer_classes = [TemplateHTMLRenderer] pagination_class = BookPagination serializer_class = BookSerializer def list(self, request): queryset = Book.objects.all() serializer = ProtocolSerializer(queryset, many=True) page = self.paginate_queryset(serializer.data) return self.get_paginated_response(page) I can show the paginated item with the codes above. And there are next and previous links in HTML. However, I need page list like [1,2,3,....], not just next and previous. I can view the data on the 3rd page by just click button 3. I need some steps to do this. 1: Retrieve the target page number(I don't know how to do this) 2: Get the data of on that page 3: Render to HTML I hope someone can help me with this. -
Image is not showing in python project
<div class="owl-carousel" id="slider1"> {% for b in bottomwears %} <a href="{% url 'product-detail' b.id %}" class="btn"><div class="item"><img src="{{b.product_image.url}}" alt="" height="300px"><span class="fw-bold">{{b.title}}</span><br><span class="fs-5">Rs. {{b.discounted_price}}</span></div></a> {% endfor %} </div> Below is the screen shoot of website where image is not shown. -
Django ORM object.related.id vs object.related_id after used select_related('related')
Let's suppose that we have this models: class Product(models.Model): .... price = models.DecimalField(max_digits=12, decimal_places=2) class Order(models.Model): .... product= models.ForeignKey(Product) After used select_related for query like that Order.objects.filter(...).select_related('product'), is there any performance difference between order.product.id and order.product_id? -
checkbox value not getting posted in Views.py Django
i have code which should post values of selected checkbox to Views.py after a button click , but for me it is sending me an empty list when trying to print the checkbox value in views.py So below is my code . Views.py if request.method=='POST': if 'submit' in request.POST: user_list = request.POST.getlist('myarray') print(user_list) html <form method="post">{% csrf_token %} <!-- <div class="w-full sm:w-auto flex items-center sm:ml-auto mt-3 sm:mt-0"> <label class="form-check-label ml-0 sm:ml-2" for="show-example-5">Show Server List</label> <input data-target="#document-editor" class="show-code form-check-switch mr-0 ml-3" type="checkbox" id="show-example-5"> </div> --> <button id= "AnchroTagForButton" name="submit" href=""> <span></span> <span></span> <span></span> <span></span> button </button> </div> <div class="p-5" id="document-editor"> <div class="preview"> <!-- <div class="alert alert-primary alert-dismissible show flex items-center mb-2" role="alert"> <i data-feather="alert-octagon" class="w-6 h-6 mr-2"></i>{{note}}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> <i data-feather="x" class="w-4 h-4"></i> </button> </div> --> <!-- <div data-editor="document" class="editor document-editor"> --> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>Server</th> <th>Name</th> <th>Labels</th> </tr> </thead> <tbody> {% for datas in customerserver %} <tr> <td> <div class="form-check form-switch"> <input class="form-check-input" name="Servers" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </form> So here i have to collect all checkbox values selected /(Checkbox name:Servers) , and post it in views.py , but here when i try to print it in views.py . it … -
Relations in Django
I have 3 tables called Customer, Order and Barcode. A customer can have multiple order object and Object can have multiple barcodes I want a new table that is populated when the order is successful. For example, it can have like c_id o_id b 1 2 [xxx, xfxx, xxasfx] 1 3 [yyy, asf, xasdfxx] 1 4 [xcxx, xxax, xvxx] 2 5 [xxrx, xxtx, xxyx] I have tried the following: class Order(models.Model): order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Barcode(models.Model): barcode_id = models.CharField(max_length=75, unique=True) order_id = models.ForeignKey(Order, on_delete=models.CASCADE) class Customer(models.Model): customer_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order_id = models.ManyToOneRel(Order, on_delete=models.CASCADE) How do I create a final relation for the new table? Thanks in advance -
Django - how can i add an additional check in my login?
I'm creating a single page application that uses Django's session authentication on the backend. Django is using django-allauth for everything authentication-related. I would like to add an additional step to my login where the user inputs a code and Django must verify that code too, other than password and username. How can i do that? Note that i'm using Django as an API, so i don't need to edit the form and add another field, i only need to add another check to the authentication backend, so something very easy: if the code is right, than proceed to check username and password too, else return an error. The problem is that i don't know where to add this check. I think i need to work on the authentication backend, but i'm stuck here. Here is the allauth authentication backend: class AuthenticationBackend(ModelBackend): def authenticate(self, request, **credentials): ret = None if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: ret = self._authenticate_by_email(**credentials) elif app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.USERNAME_EMAIL: ret = self._authenticate_by_email(**credentials) if not ret: ret = self._authenticate_by_username(**credentials) else: ret = self._authenticate_by_username(**credentials) return ret def _authenticate_by_username(self, **credentials): username_field = app_settings.USER_MODEL_USERNAME_FIELD username = credentials.get("username") password = credentials.get("password") User = get_user_model() if not username_field or username is None or password is None: … -
django response method POST don't render to the html template
I have two request function in views one is with .get method and the other one with .post. Both of the function works properly because in the the terminal the code is 200. [01/Apr/2021 08:04:39] "GET /search/search HTTP/1.1" 200 4164 [01/Apr/2021 08:04:57] "POST /search/search HTTP/1.1" 200 4164 The problem comes when i try to render the function with .post method to the html template nothing appear on the html page. def wind_search(request): if request.method == 'post': city = request.post['city'] weather_city_url = urllib.request.urlopen('api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=1a7c2a40a0734d1dc18141fc6b6241bb').read() list_of_data = json.loads(waether_city_url) # main wind information wind_speed = list_of_data['wind']['speed'] # wind_gust = wea['current']['wind_gust'] wind_deg = list_of_data['wind']['deg'] # wind conversiont m/s to knots def wind_converter(w): knots = 2 kt = (float(w)) * knots return kt wind_response = wind_converter(wind_speed) #convert wind degree in cardinal direction. def degrees_to_cardinal(d): dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] ix = round(d / (360. / len(dirs))) return dirs[ix % len(dirs)] direction = degrees_to_cardinal(wind_deg) wind_data = { "wind_response":wind_response, "wind_direction":direction, } else: wind_data={} context = {"wind_data":wind_data} return render(request, 'API/wind_search.html',context) This is the html template: {% extends "API/base.html" %} {% block content %} <!--Jumbotron --> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Wind … -
'AnonymousUser' object is not iterable error when using custom context processors
I am using a custom context processor in Django. But when the user is logged in it works file but when I try to login the user it throws 'AnonymousUser' object is not iterable Here is the error: TypeError at / 'AnonymousUser' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: TypeError Exception Value: 'AnonymousUser' object is not iterable And the context_processers file looks like def noti_count(request): count1 = Notification.objects.filter(user=request.user, seen=False) count2 = Notification_general.objects.filter(seen=False) return {"count1": count1, 'count2':count2,} And the Context Processors Looks like TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'home.context_processors.noti_count', 'django.contrib.messages.context_processors.messages', ], }, }, ] Please help me out the code works fine for logged in user but when they they try to go to login page after the logout It throws me 'AnonymousUser' object is not iterable -
Nested Bootstrap modal creates an unwanted scrollbar in the middle of the page
I'm working with a Modal and its body consists of another Modal. The body of the inner modal is a Django / Crispy form. When the inner modal opens the form, it displays an unnecessary scrollbar in the middle of the page. I was unable to find a way to disable the scrollbar. Outer modal trigger button: When "New Transaction" is pressed: When "Add Debit" is pressed: The reason for a nested modal is that there will be multiple transaction options added, for example, Add Debit (Currently displayed), Add Credit, Fund Transfer, Standing Order, Recurring Income etc. Code: <!-- New Transaction Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-transaction-modal-lg">New Transaction</button> <div class="modal fade bd-transaction-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">New Transaction</h5> </div> <div class="modal-body"> <!-- NESTED MODALS --> <!-- Debit Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-debit-modal-lg">Add Debit</button> <div class="modal fade bd-debit-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Debit Transaction</h5> </div> <div class="modal-body"> <!-- Form START --> <form action="" method="POST"> {% csrf_token %} <div class="form-row"> <div class="col"> {{ debit_form.debit_name|as_crispy_field }} </div> <div class="col"> {{ debit_form.debit_value|as_crispy_field }} </div> </div> </div> <div class="modal-footer"> <button … -
Django ModelForm form.is_valid is false but with no form.errors
I have problems with Django ModelForm, I have the situation where form.is_valid() = false but with no form.errors. That's why I'm getting no updates in the database. This is what I have: #views.py def blog_update(request, slug): obj = get_object_or_404(BlogPost, slug=slug) form = BlogModelForm(request.POST or None, instance=obj) print(obj.content, obj.title) print(request.POST) print (len(form.errors)) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() form = BlogModelForm() template_name = 'form.html' context = {"form": form, "title": f"Update {obj.title}"} return render(request, template_name, context) # forms.py class BlogModelForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'slug', 'content'] # form.html {% extends 'base.html' %} {% block content %} <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> {% endblock %} I hope you can help me to find where the problem is. Thanks in advance -
How to write raw query and display result in listView in DRF
How can I write the raw query in DRF to get the list of the result? I have tried by my way but the problem is I don't this its returning what the query result. My code is: serlializers.py class MQTTFeedDataSerializer(serializers.ModelSerializer): class Meta: model = models.FeedDataValues fields = ('id','sensor','hardware_id','field1','field2','received_at',) views.py class MQTTGetAvgValue(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser, permissions.IsAuthenticated,) def get(self, request): queryset = models.FeedDataValues.objects.raw(' select id, hardware_id, Avg(CAST(field1 as DECIMAL(4,2))) as field1, strftime(\'%m\', received_at) as month, strftime(\'%Y\', received_at) as year from mqtt_FeedDataValues where hardware_id = \'XXXXXXXXX\' group by month, year;') serializer = serializers.MQTTFeedDataSerializer(queryset, many=True) return Response(serializer.data) Any suggestions will be of great help. -
Error when passing Javascript Variable to Django URL
I am trying to redirect to a URL using Django and a Value that I get after a user clicks a radio button. The code is rendered in overview.html and i get the following error when rendering it: Reverse for 'overview-office' with keyword arguments '{'year': 2021, 'month': 3, 'day': 20, 'office_id_from_filter': ''}' not found. 1 pattern(s) tried: ['overview/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/office/(?P<office_id_from_filter>[0-9]+)$'] Please see code below: $('input[type="radio"][id=office-radio]').change(function () { var redirect_value = this.value; var new_url = "{% url 'overview-office' year=day1.year month=day1.month day=day1.day office_id_from_filter=office_id %}".replace(/office_id/, redirect_value.toString()); window.location.replace(new_url) }); Can someone help me to debug? I think the reason is that the string replacement does not work properly... Thanks a lot! -
Disable collectstatic command when deploying Django App to Azure via Github
This is an error that has been giving me countless problems and unfortunately, there is no documented way around it. I have a Django APP that is running on Azure. I push local changes to Github and through Github actions, the changes are synced to Azure. This has been going on well without any trouble with the build/Deploy processing succeeding. Trouble came when I created a storage account for the media files and static files on Azure using django-storages[Azure]. So, everytime I pushed changes from localhost to Github, the build/deploy process from Github to Azure will run and manage to run the collectstatic command which unfortunately fails due to unknown error. Running collectstatic from SSH terminal on my Azure portal succeeds albeit after taking like forever, So, I am assuming that it is because of the process taking long that ends up failing. I do not need this process to run every time I make changes to the site because I can do so from the SSH terminal when there is a need. I have read from the documentation and most of them recommend setting the value DISABLE_COLLECTSTATIC = 1 to disable the process. However, I don't know how to … -
Why do I get 403 forbidden when using axios and django with CORS
I try to perform login + another POST request with axios and it seems that it works well if i use the same host ( i.e. localhost to localhost, or 127.0.0.1 to 127.0.0.1) but not when going from localhost -> 127.0.0.1 or vice versa. Please assist me finding what am I missing in my configuration, server settings: ALLOWED_HOSTS = [] REMOVE_SLASH = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:19006", "http://127.0.0.1:19006" ] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] client usage: let APIKit = axios.create({ withCredentials: true, baseURL: 'http://127.0.0.1:8000', timeout: 10000, }); APIKit.post("/user?action=login", {...}) APIKit.get('/requests/') Login succeeds but server sends new csrf token, which is ignored in axios as you can see in the following pictures, and thus receiving 403 Forbidden Login request headers : true Access-Control-Allow-Origin: http://localhost:19006 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Set-Cookie: csrftoken=Huur0KQgFMtokszTOUa1gGaWJNODn8blYvjfEO2UGnuyN75hWy1cZLVTaND2ypZ9; expires=Thu, 31 Mar 2022 08:03:39 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=r6alaupw0484mreqt8r4vlqe17hxdjsc; expires=Thu, 15 Apr 2021 08:03:39 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax POST /user?action=login HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Content-Length: 49 sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99" Accept: application/json, text/plain, */* sec-ch-ua-mobile: ?0 User-Agent: Mozilla/5.0 (Macintosh; Intel … -
Django inserting a user_id (ForeignKey) while submitting a form
Im struggling to figure out how can I update a model that has a ForeignKey. I have a User model called Companies and a CompaniesProfile model that has a user field set as a ForeignKey of the Companies model: class Companies(User, PermissionsMixin): company = models.TextField(max_length=100, unique=True) tel = models.TextField(max_length=20) reg_nr = models.TextField(max_length=50, unique=True) vat = models.TextField(max_length=50) class CompanyProfile(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) logo = models.ImageField(blank=True) street = models.TextField(max_length=256) city = models.TextField(max_length=36) postal_code = models.TextField(max_length=16) country = models.TextField(max_length=36) When the Company is register it can create a profile CompanyProfile. I have a form for that: class CompaniesProfileForm(forms.ModelForm): class Meta: model = CompanyProfile fields = ('street', 'city', 'postal_code', 'country', 'logo') and a view: class CreateProfile(CreateView, LoginRequiredMixin): template_name = 'companies/profile.html' form_class = CompaniesProfileForm success_url = reverse_lazy('home') Whenever the form in the view is submitted I get an error "integrityError at /companies/profile/ NOT NULL constraint failed: companies_companyprofile.user_id" I'ts probably because the user field is empty. My question is how to fill the user automatically based on which user currently is logged in. urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(template_name='companies/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('create/', views.CreateAds.as_view(), name='ads_create'), path('profile/', views.CreateProfile.as_view(), name='profile_create'), ] -
How to sorted the list of model instance by number of an other related model in django REST?
I have 2 models is Product and Watch. A Product may have multiple Wacht. When I call the API to get the list of products. I want to provide a feature for ordering the products by a number of watches that each product has like below. domainname/products/?ordering=numberOfWatch Here is my model class Product(models.Model): # product model fields and Wacht model class Watch(models.Model): product = models.ForeignKey( Product, related_name='watches', on_delete=models.CASCADE, ) # other fields and the ProductList View class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() permission_classes = (IsAuthenticated, IsAdmin,) name = 'product-list' filter_fields = ('category', 'brand', 'seller') search_fields = ('name',) ordering_fields = ('-updated_at', 'price', 'discount_rate', 'discount') ordering = ('-updated_at',) I'm thinking of add watch_count field in Product model and ordering for that field. But is that a good way to get what I need? -
Django forms vs HTML forms
when i use the Django {{ forms }} the forms i rendered with the build in functionalities, if user submits and fields are invalid the invalid fields are cleaned but rest of the information in the form is not cleaned, this provides the user to change only the fileds where error is raised. When i use HTML forms on submit if there is a error all the fields are cleaned and the user has to write all the information over again from scratch. How can i accomplish the same fuctionality in a html form as in Django {{ forms }}