Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send email from view when testing in Django
So I have a view that sends an emails when it store some data on the database, currently I'm testing but the test returns The email can't be sent that happens when there is an error sending the email, I have checked some answers here but so far no positive results. My code: views.py def update_inventory(self): # code store the data is success context = { 'time': timezone.now() } # render email text email_html_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.html', context) email_plaintext_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.txt', context) msg = EmailMultiAlternatives( # title: "{title}".format(title="Inventory updated"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: "email@email.com" ) msg.attach_alternative(email_html_message, "text/html") try: msg.send() except Exception as e: raise serializers.ValidationError({'error':"The email can't be sent"}) return Response({'info':'Inventory successfully updated'}, status=status.HTTP_200_OK) tests.py def test_successfully_update_inventory(self): data = {'product1': 500, 'product2': 200} response = self.client.post(reverse('inventory:update-inventory'), data, format='json') stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.getLogger().info(response) # Prints The email can't be sent Any thoughts about this? Thanks in advance -
Categories and Subcategories showing products for the parent and children
Im doing a ecommerce website with django and I have a problem with categories and subcategories. This are my models: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True) title = models.CharField(max_length= 200, null = True) slug = models.SlugField(max_length=200, null = True) ordering = models.IntegerField(default = 0) class Product(models.Model): name = models.CharField(max_length = 255, null = True) slug = models.SlugField(max_length=200) category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE) parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True) brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE) description = models.TextField(blank = True, null = True) price = models.FloatField(null = True) disccount = models.BooleanField(default = False) disccount_price = models.FloatField(blank = True, null = True) And this is my view: def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.filter(parent = None) context = { 'category': category, 'products' : products } return render(request, 'category_detail.html', context) Okay so what I want to do is if I click the parent category I want to show all the products that their children have and If I click a Children I want to show only the products that he has. So i don't know how to do … -
Pass parameter to cursor.execute in Django
I have the following view definition Django def getEiNumberByFeatures(request): # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the nick name from the client side. id = request.GET.get("id", None) sqlQuery = """SELECT names FROM Costumer WHERE id = %s """ cursor.execute(sqlQuery, (id)) eiNumbers = cursor.fetchall() context = {"EiNumber": eiNumbers} return JsonResponse(context, status=200) I am getting the following error pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000') Have somebody any idea why this can happens? Even when I am sending the parameter -
Помогите написать Permission django rest framework для бана пользователя
Если пользователь забанен тогда он не сможет смотреть PostDetailAPIView. Нужно написать Permission - IsBanned Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') name = models.CharField(max_length=50) bio = models.TextField(max_length=2000, blank=True, default='') avatar = models.ImageField(upload_to='media', null=True, blank=True) is_moderator = models.BooleanField(default=False, verbose_name=("moderator")) is_ban = models.BooleanField(default=False) is_mute = models.BooleanField(default=False) Views.py class PostDetailAPIView(generics.RetrieveAPIView): queryset = Topic.objects.all() serializer_class = PostDetailSerializer permission_classes = [IsBanned] -
Utilise AJAX & javascript to create a toast with Djangos messaging framework
I have followed a tutorial to utilise AJAX to validate an input field before attempting to submit. I have it working on my django built site; however, I have been using toasts to alert the user to other actions and did not want to get way from this. $("#id_hub_name").focusout(function (e) { e.preventDefault(); // get the hubname var hub_name = $(this).val(); // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'validate_hubname' %}", data: {"hub_name": hub_name}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("You cannot create a hub with same hub name"); var hubName = $("#id_hub_name"); hubName.val("") hubName.focus() } }, error: function (response) { console.log(response) } }) }) This is my current JS, I want to change the alert function to use toasts instead. In my base.html I use the following to listen for toasts and create them. {% if messages %} <div class="message-container"> {% for message in messages %} {% with message.level as level %} {% if level == 40 %} {% include 'includes/toasts/toast_error.html' %} {% elif level == 30 %} {% include 'includes/toasts/toast_warning.html' %} {% elif level == 25 %} {% include 'includes/toasts/toast_success.html' %} {% else %} {% include 'includes/toasts/toast_info.html' %} {% endif … -
Dependent drop down box in form for every submit render chart, how to update new value in chartjs dataset?
I am working on Django project I write the code for dependent drop down box that can be get values and passed to the backend to call the API/JSON to fetch that data in chartjs, but here if I click submit the chart will appear, for the next time I will select zero value or any other value so the chart is disappeared or new values comes but if I overlay the mouse its showing old data also and new data also, how to update only new values. here is my code HTML: <form id ="new_form" name="new_form" method="POST"> {% csrf_token %} <label for="Question_type">Question Types:</label> <select id="qt_it" name = "select_question_type"> <option value="{{question}}">ALL</option> {% for qt in question %} <option value="{{qt.id}}">{{qt.question_type}}</option> {% endfor %} </select> <label for="Certificate">Certificate:</label> <select id="Certificate" name = "select_certificate"> <option disabled selected = "true"> -- Select certificate -- </option> {% for certificate in certifi %} <option value="{{certificate.id}}">{{certificate.certification_name}} {{certificate.certification_year}}</option> {% endfor %} </select> <label for="state">State:</label> <select id="state_id" data-district-url="{% url 'Dashboard:load_district' %}" name = "select_state"> <option disabled selected = "true"> -- Select State -- </option> {% for state in states %} <option value="{{state.id}}" >{{state.state_name}}</option> {% endfor %} </select> <label for="district">District:</label> <select id="district_id" data-taluk-url="{% url 'Dashboard:load_taluk' %}" name = "select_district"> <option disabled … -
How can I write more columns than defined in header?
I am using Datatables jQuery plugin and I have the following columns in html: <tbody> <td class="test1">elem1</td> <td class="test2" style="display: none;">elem2</td> </tbody> I activate one or the other column from jQuery ( always one ). Problem is that 'datatables' plugin yells error because num of columns from tbody is not equal with num of columns from thead (1 in my case 'cause I only want one to display). Is there a workaround for defining more columns than specified in the header and pass validation ? I am writing the html thought Django's template language. For showing columns I use somthing like this: <select onchange="selectChange(this.value)"> <option>test1</option> <option>test2</option> </select> function selectChange(val) { $(`[class*="test"]`).hide(); $(`[class="${val}"]`).show(); } -
Using CheckBox in Django FilterSet
I can't seem to find any solutions to this issue.. In my models.py I have a class called Course like this: class Course(models.Model): seats_occupied = models.IntegerField(null=True, default=0) seats_available = models.IntegerField(null=True, default=25) # etc... In my filters.py I have this filter for it: class CourseFilter(django_filters.FilterSet): seats_occupied = django_filters.NumberFilter(field_name='seats_occupied', lookup_expr='lt') At this point, I need to enter a number to see if seats_occupied is less than that number. But I would like to just have a CheckBox or Possibly a multiple choice with "open/full" courses, that will only give me the courses that are not full. Is there a good way to accomplish this? -
Docker Set Up mysql db
I was setting up mysql with docker and I observe that without defining environment in docker-compose.xml, file I am able to run mysql . Is this good or I am going wrong ? my docker-compose.xml is db: image: mysql:5.7 restart: always ports: - "3302:3306" and my settings.py file is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': myproj, 'USER': root, 'PASSWORD': 123123123, 'HOST': 'db', 'PORT': 3306, } } I didn't enter any environment in xml file . If even I do its working same . -
How to serve local CSS files in my Django-Dash-Plotly app
I need to add CSS to my project to enable it to stop conflicting with Bootstrap CSS. I have the exact problem this person is having with fixed columns. The solution is to add this CSS snippet somewhere in my directory: .dash-spreadsheet .row { flex-wrap: nowrap; } My only problem is, I'm an extreme novice when it comes to styling files and I feel completely lost on where to add this snippet into my Django-Dash project. I've read the documentation from Django-Dash for local files Also looked at Dash-Plotly official documentation for adding CSS ... and I'm still confused on where to add the code snippet. For anyone wondering I've tuned my django settings.py to fit the Django-Dash requirements, according to documentation. Here is how my Django project is set-up: app.py is my Dash app that is within my home Django app. stockbuckets folder is the main project folder that holds my settings.py file. I see I am also meant to add serve_locally = True as an in app argument or global variable for DASH_PLOTLY in settings.py. Either method I use just gets my project stuck in HTTP GET... trying to find the local files I'm assuming? Would greatly appreciate … -
Getting data from Shopify to Django
I have an Inventory App that was built in django and I want to extract the data from Shopify to my web app. Basically I want to get the customers info from shopify and show it to my Django app table. How to do this ? Any tips? -
how to use json data in django orm filter
I use in query filter in **kwargs but output query set is None. My code is below: kwargs={"category":["v1","v2","v3"],"tags":["t1","t2"]} obj.filter(**kwargs ) -
Django, Docker and traefik shows 404 on deploy but no error logs - using django-cookiecutter
I recently decided to move my website to use docker along with the template that django-cookiecutter with the goal in mind of easy deployment and easy to setup environments. Localy the project runs fine and I can access the website through the ip address of the virtualmachine on port 8000. But when deploying it to DO with the production.yml file it does not fail, the build and up both run successfull. But when I try access the ip of my droplet I get a 404. The only error that I get is from traefik, SSL related and I don't think this is causing the 404. traefik_1 | time="2020-10-07T16:47:26Z" level=error msg="Unable to obtain ACME certificate for domains \"bgan.be,www.bgan.be\": unable to generate a certificate for the domains [bgan.be www.bgan.be]: error: one or more domains had a problem:\n[bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://bgan.be/.well-known/acme-challenge/4AvrIU9r8F3PwtyrK_6yq8fwHc4CgiHeT_4Vk5Yo0G4 [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n[www.bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://www.bgan.be/.well-known/acme-challenge/gToGrbtaQN5SBFyArzNz8r1SQx8QSB2Wax3_CqzYXCk [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n" providerName=letsencrypt.acme routerName=web-secure-router@file rule="Host(`bgan.be`) || Host(`www.bgan.be`)" Would anyone have any suggestions on why this is happening? been stuck on this for 3 days now and have tried to … -
Why my django server is not running after changing BASE_DIR?
I am getting the following error in Git bash. $ python manage.py run Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\website\website\website\settings.py", line 72, in <module> 'NAME': BASE_DIR / 'db.sqlite3', TypeError: unsupported operand type(s) for /: 'str' and 'str' When I am trying to run the server it shows this. Can anyone please explain it? -
Django: Save forms cleaned_data with foreign key as session items
I've got a ModelForm with a number of attributes - in the CreateView form_valid method I'm trying to save a users form inputs as session data (which I check for in the get_initial method if they visit the form again) ModelForm: class OrgForm(forms.ModelForm): """Form definition for a Org.""" class Meta: """Meta definition for OrgForm.""" model = Org fields = ( "full_name", "short_name", "feature", "state", "email", ) View: class OrgCreateView(CreateView): "CreateView for OrgForm" model = Org form_class = OrgForm success_url = "/home/" def form_valid(self, form): response = super().form_valid(form) # Set the form data to session variables responses = {} for k, v in form.cleaned_data.items(): responses[k] = v self.request.session["org_form_data"] = responses return super().form_valid(form) def get_initial(self): initial = super(OrgCreateView, self).get_initial() # Check for any existing session data # This is present if they had filled this out # and then came back again later to fill out again if "org_form_data" in self.request.session: # They have data - loop through and fill it out for key, value in self.request.session["org_form_data"]: initial[key] = value return initial Model: class Org(models.Model): """Model definition for Org.""" full_name = models.CharField(max_length=150) short_name = models.CharField(max_length=25, blank=True, null=True) state = models.CharField(max_length=50) is_active = models.BooleanField(default=False) feature = models.ForeignKey(Feature, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) last_updated … -
DJANGO: Need help in implementation of price filtering of items through HTML <FORM>
I wanted to add buttons to select between ASC or DSC order of viewing items. I added a radio button to select between ascending order of price and descending order of price of items to be shown. I know how to sort the list of the hat items in descending or ascending order in views.py but I don't know what condition to use and how to change the order through the form in the html code. I'm new to this and this is my first project in DJANGO. I know I have to get some POST input through the form and use that variable in the condition in views.py but I don't know how. Thankyou. relevant part of views.py file: def head_wear(request): if(#whatconditionhere): hat_list=models.Hat.objects.order_by('price') else: hat_list = models.Hat.objects.order_by('-price') stuff_for_frontend = { 'hat_list': hat_list, } return render(request, 'AUM/head_wear.html',stuff_for_frontend) relevant part of head_wear.html <form class="form-inline" action="#"> <div class="col s4 offset-s4"> <p> <label> <input class="with-gap" name="group1" type="radio" checked /> <span style="color:white;">Ascending</span> </label> </p> </div> <div class="col s4 offset-s4"> <p> <label style="padding-left:150%;"> <input class="with-gap" name="group1" type="radio" /> <span style="color:white;">Descending</span> </label> </p> </div> </form> urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('head_wear',views.head_wear,name='head_wear'), path('shirt_wear',views.shirt_wear,name='shirt_wear'), path('pant_wear',views.pant_wear,name='pant_wear'), path('watch_wear',views.watch_wear,name='watch_wear'), path('shoe_wear',views.shoe_wear,name='shoe_wear'), … -
Django Rest Auth - Facebook Login Access Token
I trying to make a django rest authentication system. I use the dj-rest-auth. I successfully made the app to register and login local user ( with email & password). Now i would like to sign up users with Facebook. I follow all the introductions from the dj-rest-auth docs https://dj-rest-auth.readthedocs.io/en/latest/. I follow other introductions to setup the admin page and the Facebook For Developers stuff and finally i got this(picture). Then i found the access token manualy from my facebook profile and successfully I register a user(my profile) on my app. My problem is that i want to Sign Up with facebook directly like all other applications like this "Continue As"(picture) and i couldn't found how to do this. I would like to make an API for this because i would like to make a React-Native frontend. Thank you all for your time :) !! In my settings.py in INSTALLED_APPS : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter', ] My urls.py : from django.contrib import admin from django.urls import path, include from .views import FacebookLogin, FacebookConnect urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/facebook/', FacebookLogin.as_view(), name='fb_login'), path('dj-rest-auth/facebook/connect/', … -
how to make summation between two similar object instead of creating a new object? django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object this is my model this is the Products model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name this is the Collections model class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
How to solve issue corb (cross origin read block) in django python?
In my Django application I get an error Cross Origin Read Blocking, I have searched an internet that says it is the version problem of Chrome, so I have tried Internet Explorer, Microsoft Edge I still get same error I have installed pip install django-cors-headers and add it to settings.py file INSTALLED_APPS = [ ... 'corsheaders', ... ] and also MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', ... but when I reload the page the result is same. I want to add a picture to my website from google pictures. Here is the result chrome console shows **Cross-Origin Read Blocking (CORB)** blocked cross-origin response https://en.wikipedia.org/wiki/The_Terminator with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. Here is the result from Microsoft Edge Cross-Origin Read Blocking (CORB) blocked cross-origin response https://en.wikipedia.org/wiki/The_Terminator with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. I am using Django version 3.1.2, Python 3.7.9 -
Where is the css .fieldWrapper class defined? (Django? Bootstrap?)
I have some HTML code in a Django app (with Bootstrap) that has a .fieldWrapper CSS class. I searched for this class in Google, in the Django docs, and in the Bootstrap docs. In the Django docs, I see it being used in examples, but I don't see it documented anywhere. Where is the .fieldWrapper class defined? (and optionally, where is the documentation for it?) -
How to Send Email from Django
I am taking a tutorial for Django, but stuck at sending email from Django. I am working on Django's built in django.contrib.auth password reset views, it works fine, but doesn;t actually sends any email. For Testing purpose, I am using below code example to send email, but it gives error which I don't know where to resolve. (env1) C:\Users\crm>python manage.py shell Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'email1@gmail.com', ... ['email2@gmail.com'], ... fail_silently=False, ... ) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 51, in send_mail connection = connection or get_connection( File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line … -
NOT NULL constraint failed: users_usermodel.password
I have created a Custom User Model(I am new to this Curtom thing) And I got this error at login. NOT NULL constraint failed: users_usermodel.password. I don't understand what to do. Here is my models.py and views.py I changes the login to mylogin because I thought the function might contrdict the django login funtion. but nothing changed. Please help me solve my problem Models.py # Custom User Model Code from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email,first_name, last_name, password=None): """ Creates and saves a User with the given email, favorite color and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,first_name, last_name, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class UserModel(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=20, default='') last_name = models.CharField(max_length=20, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] def __str__(self): return … -
data in serializer is always empty
I have following serializer: class AdminSerializer(serializers.Serializer): def validate(self, data): user = data.get("user_pk") total_licenses = data.get("total_licenses") #here i do some validation with the vars But my data is always empty. This is part of my view serializer_class = self.get_serializer_class() serializer = serializer_class( data=self.request.data, ) serializer.is_valid(raise_exception=True) This is my unit test request: response = self.client.patch( url, data={"user_pk": self.user.pk, "total_licenses": 3}, ) Why is my 'data' always empty? -
How to route to switch from HTTP to HTTPS
I have a Django website running behind Nginx. I have this issue where Nginx won't switch routes from http://www.example.org/uploads to https://www.example.org.uploads. So I am getting a 404 error. Here is my Nginx configuration: upstream gunicorn{ server unix:/home/ubuntu/website/project.sock fail_timeout=0; } server { listen 443 ssl http2; server_name *.example.org; ssl_certificate /etc/ssl/private/example.org.crt; ssl_certificate_key /etc/ssl/private/domain.key; # path for static files root /home/ubuntu/website/project/project; location /uploads { alias /home/ubuntu/uploads; } location ^~ /dashboard { alias /var/www/name/dashboard_app/build; try_files $uri $uri/ /dashboard/index.html; } location ^~ /shop { alias /var/www/name/user_app/build; try_files $uri $uri/ /user_app/index.html; } location ^~ / { proxy_pass http://gunicorn; proxy_set_header Host $host; } location /static { } } server { if ($host = example.org) { return 301 https://www.$host$request_uri; } if ($host = www.example.org) { return 301 https://$host$request_uri; } listen 80; server_name domain.org; return 404; } 'dashboard' and 'shop' lead to React applications. '/' leads to my Django application. 'http(s)://example.org/uploads' and 'https://www.example.org/uploads' work fine . 'http://www.example.org/uploads' is the only combination I can find that does NOT work. How can I get calls to 'http://www.example.org/uploads' to route correctly? -
Categories and Subcategories Django
Im doing a ecommerce website with django and I have a problem with categories and subcategories. This are my models: Model Category Model Product And this is my view: View Okay so what I want to do is if I click the parent category I want to show all the products that their children have and If I click a Children I want to show only the products that he has. So i don't know how to do that:(