Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using template function to each member of array and get it back to array
I have list in django template {{mylist}} each items of mylist has string. What I want to do is like this. {% for i in mylist %} {set i = (i | truncatechars:20)} {% endif%} {{mylist | join:","}} Using truncatechars for each member and then join. It can be in view.py but I want to this in template. Is it possible?? -
DRF endpoint returns weirdly serialized object although it is fetch correctly in the view
So I'm using Django REST authand dj-rest-auth as authentication backend for my React app. In the view it seems that it grabs the correct instance of the logged in user, but it doesn't reflect that in the response. Also if I print fields of that instance it returns the wrong data, the serializer instance however looks like it holds the correct object to serialize...hm # views.py class UserDetail(APIView): """ Retrieve a User instance """ def get(self, request): print('Header Token: ' + str(request.META['HTTP_AUTHORIZATION'])) print('request.user: ' + str(request.user)) try: user_profile = UserProfile(user=request.user) print('user_profile: ' + str(user_profile)) print('user_profile.company: ' + str(user_profile.company)). # Why is this none? serializer = UserProfileSerializer(user_profile) print('serializer: ' + str(serializer)) # looks like the instance is correct though.. print('serializer.data: ' + str(serializer.data)) return Response(serializer.data) except UserProfile.DoesNotExist: raise Http404 Returns and Postman returns But the data should be: # models.py class UserProfile(models.Model): """ Extends Base User via 1-1 for profile information """ # Relations user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) # Roles is_ta = models.BooleanField(default=False) # indicates if user is part of TA department def __str__(self): return F'{self.user.first_name} {self.user.last_name}' @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() # serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = … -
DRF: convert a list of string into seperate objects and save it into the database(postgres)
My query is that I have a list of string from the post request which were separated by 2 newlines ['hdhsjfhjfsjhj hsjfh skjh jsh shjsfhjs', 'ahfjjfhjdfgdjdkfgajkfgakjgaj', 'jhdsjfhdgjfhdghjdgk'] what i want is that for each of this string a new object is created in the database, so that when i make a get request it shows like ` [{ "id": 11, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjkvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }, { "id": 12, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjkvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskbhjsdgfgudskfhakfgvkfasgkvfugaskubvksjbj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }, { "id": 13, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjmsknvsjbvjk skvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskbhjsddjjkl sgsdlkfhsdljfjslsl dsfsshlghjshlkg skdjgkldjsk gdsklgj klsdjgk sdkgj ksdj gkjsdk skdj gklsjdkggfgudskfhakfgvkfasgkvfugaskubvksjbj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }] my viwes.py @api_view(['GET', 'POST']) def paralist(request): """ List all the paraGraphs added till now to the database or add new paragraphs one by one """ if request.method == 'GET': allpara = para.objects.all() serializer = paraSeriealizer(allpara, many=True) return Response(serializer.data) if request.method == 'POST': todata = request.data['para'].split("\n\n\n") print(todata) serializer = paraSeriealizer(data=todata, many=True) if serializer.is_valid(): print(serializer.data) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my seriealizer.py class paraSeriealizer(serializers.ModelSerializer): class Meta: model = para fields = '__all__' models.py class para(models.Model): para = models.TextField() -
Django ORM equivalent to left exclusive JOIN
Relatively new to Django and I have the following models in my django (3.2) project: class projectsA(models.Model): projectID_A = models.BigIntegerField(primary_key=True) project_name_A = models.TextField(blank=True, null=True) project_desc_A = models.TextField(blank=True, null=True) projektID_B = models.ForeignKey('projectsB', models.DO_NOTHING, db_column='projektID_B', blank=True, null=True, db_constraint=False) class Meta: managed = False db_table = 'projectsA' class projectsB(models.Model): projectID_B = models.BigIntegerField(primary_key=True) project_name_B = models.TextField(blank=True, null=True) project_desc_A = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'projectsB' I want to get all projects from projectsA which are not in projectsB. The SQL equivalent would be SELECT * FROM projectsA a LEFT JOIN projectsB b on a.projektID_B = b.projectID_B WHERE b.projectID_B is null I have tried with .exclude or .select_related() and several other approaches, but cannot find a solution for this scenario. Thanks in advance. -
Get a result and the filter only has an associated field [Django-filter]
I want to create django-filter where when users search for a book by title or content they get a result and the filter only has an associated field. And also in each field there is a number of containing books with numbers. For example,I'm looking for a book about nature, I write "nature" in the search field in the filter, and then I click "Search". I get a result and a filter with the corresponding fields and results (for example, the filter has the following values - language filter: English (54), German (20) ; Publisher: Oxford (100), Seven House(21) etc.) I want to create a django filter where when users search for a book by title or content they get a result and the filter only has an associated field. And also in each field there is a number of containing books with numbers. For example, I'm looking for a book about nature, I write "nature" in the search field in the filter, and then I click "Search". I get a result and a filter with the corresponding fields and results (for example, the filter has the following values - language filter: English (54), German (20) ; Publisher: Oxford (100), … -
Generate graphene types dynamically
I am sure whether this can be achieved or not. It would be very great if someone suggests any alternative to this or any other supporting packages to achieve this. Below is my code. class DynamicTypeInput(graphene.InputObjectType): object_type = graphene.String() object_value = graphene.String(required=False) # Can we make this required=True if object_type == "requesting_value" class WidgetInput(graphene.InputObjectType): title = graphene.String() dynamic_object_type = graphene.Argument(DynamicTypeInput, required=True) I tried using graphene-pydantic for generating graphene models but no use. Its throwing generalized error like TypeError: Input fields cannot be resolved. The input field type must be a GraphQL input type. Is there any way to achieve this with graphene itself? -
How To Parse form-data / multi-part in HTTP Request
How do I get the multipart section and parse it? b'POST /Hello/MyBrother HTTP/1.1\r\nUser-Agent: PostmanRuntime/7.29.0\r\nAccept: */*\r\nCache-Control: no-cache\r\nPostman-Token: e7051ceb-6859-47b6-bc19-82016a8b6316\r\nHost: 127.0.0.1:8 000\r\nAccept-Encoding: gzip, deflate, br\r\nConnection: keep-alive\r\nContent-Type: multipart/form-data; boundary=--------------------------468552134136252037791868\r\nContent-Length: 29 1\r\n\r\n----------------------------468552134136252037791868\r\nContent-Disposition: form-data; name="username"\r\n\r\nMahanBi\r\n----------------------------468552134136252037791868\r\n Content-Disposition: form-data; name="password"\r\n\r\nYayaya12345678\r\n----------------------------468552134136252037791868--\r\n' -
How to generate Token Authentication for for Already existing users table in my private database in Django REST API?
I have table users in my private database with username, password, email, status, creation_date, updated_date,... etc. with some rows of data. I want to generate Tokens for this users ? So i want to use my private database users table instead of Django db auth_users table for generations of tokens for username's present my private database. **idint(11) NOT NULL AUTO_INCREMENT,usernamevarchar(200) DEFAULT NULL,namevarchar(200) DEFAULT NULL,passwordvarchar(200) DEFAULT NULL,emailvarchar(100) DEFAULT NULL,statustinyint(1) DEFAULT 0 COMMENT '0=>active,1=>inactive,2=>delete',creation_datedatetime DEFAULT NULL,updated_datetimestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),last_logindatetime NOT NULL,created_byint(11) NOT NULL,is_sys_admintinyint(1) DEFAULT 0,is_agency_admintinyint(1) DEFAULT 0,is_adv_admintinyint(1) DEFAULT 0,is_pub_admintinyint(1) DEFAULT 0,is_bidder_admintinyint(1) DEFAULT 0,template_idint(11) DEFAULT -1,camp_list_filterstext DEFAULT NULL COMMENT 'Campaign Listing Page Filters',adv_list_filterstext DEFAULT NULL COMMENT 'Advertiser Listing Page Filters',agency_list_filterstext DEFAULT NULL COMMENT 'Agency Listing Page Filters',account_list_filterstext DEFAULT NULL COMMENT 'Account Listing Page Filters',user_list_filterstext DEFAULT NULL COMMENT 'User Listing Page Filters',template_list_filterstext DEFAULT NULL COMMENT 'Template Listing Page Filters',connection_list_filterstext DEFAULT NULL,adgroup_list_filterstext DEFAULT NULL COMMENT 'Adgroup Listing Page Filters',dashboard_list_filterstext DEFAULT NULL,report_list_filterstext DEFAULT NULL,report_timezonevarchar(200) DEFAULT 'UTC' COMMENT 'User Default Timezone',ad_list_filterstext DEFAULT NULL COMMENT 'Ads Listing Page Filters',segment_list_filters text DEFAULT NULL COMMENT 'Audience Segment Listing Page Filters', PRIMARY KEY (id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 ** -
How to create new collection datatabase after each scraping execution?
I have created a scrapping tool to crawl data from aliexpress website using python and selenium. This is my script in python : from selenium.webdriver.edge.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium import webdriver from pymongo import MongoClient from time import sleep from lxml import html import pandas as pd import cssselect import pymongo import time def scrap(subject): start_time = time.time() options = Options() options.headless = True driver = webdriver.Edge(executable_path=r"C:\Users\aicha\Desktop\mycode\aliexpress_scrap\scrap\codes\msedgedriver",options=options) url = 'https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText='+subject+'&ltype=wholesale&SortType=default&page={}' # baseurl = 'https://www.aliexpress.com' for page_nb in range(1, 5): print('---', page_nb, '---') driver.get(url.format(page_nb)) sleep(2) current_offset = 0 while True: driver.execute_script("window.scrollBy(0, window.innerHeight);") sleep(.5) # JavaScript has time to add elements new_offset = driver.execute_script("return window.pageYOffset;") if new_offset <= current_offset: break current_offset = new_offset sleep(3) tree = html.fromstring(driver.page_source) results = [] for product in tree.xpath('//div[@class="JIIxO"]//a'): title = product.xpath('.//h1/text()') if title: title = title[0] price = product.cssselect('div.mGXnE._37W_B span') price = [x.text for x in price] currency = price[0] price = ''.join(price[1:]) stars = product.xpath('.//span[@class="eXPaM"]/text()') if stars : stars = stars [0] else: stars = 'None' nb_sold = product.xpath('.//span[@class="_1kNf9"]/text()') if nb_sold: nb_sold = nb_sold[0] else: nb_sold = 'None' supl = product.xpath('.//a[@class="ox0KZ"]/text()') if supl: supl = supl[0] else: supl = 'None' ship_cost … -
Django : CSS file not loading
Css files not working, I am not sure about the reason, I have done everything as done in the tutorial. settings.py STATIC_DIR = BASE_DIR.joinpath('static') STATIC_URL = '/static/'; STATICFILES_DIR = [STATIC_DIR]; base_html <!DOCTYPE html> <html> {% load static %} <head> <title>BASE</title> </head> <link rel="stylesheet" href="{% static 'style.css' %}"> </link> <body> <ul> <li><a href="{% url 'index' %}">Django</a></li> <li><a href="{% url 'admin:index' %}"> Admin</a></li> <li><a href="{% url 'basic_app:register' %}">Register</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href ="{% url 'basic_app:user_login' %}" >Log in</a></li> {% endif %} </ul> {% block body_block %} {% endblock %} </body> </html> folder structure -
how to install channels redis in django using pip without errors
I am trying to install channels redis module using pip but so far am still getting errors. I installed Microsoft c++ build tools as the error suggested but so far the error still persists when it comes to building wheel for hiredis. Here is the output error. error: subprocess-exited-with-error × Running setup.py install for hiredis did not run successfully. │ exit code: 1 ╰─> [25 lines of output] C:\Users\Teacher-5F84DF\AppData\Local\Temp\pip-install-cs726k2z\hiredis_fa16ee7f0b4e4df28a1a34d9640a827d\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, imp, os, glob, io c:\users\teacher-5f84df\appdata\local\programs\python\python310\lib\site-packages\setuptools\dist.py:697: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\hiredis.pyi -> build\lib.win-amd64-3.10\hiredis copying hiredis\py.typed -> build\lib.win-amd64-3.10\hiredis running build_ext building 'hiredis.hiredis' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src creating build\temp.win-amd64-3.10\Release\vendor creating build\temp.win-amd64-3.10\Release\vendor\hiredis C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -Ic:\users\teacher-5f84df\appdata\local\programs\python\python310\include -Ic:\users\teacher-5f84df\appdata\local\programs\python\python310\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.10\Release\src\hiredis.obj hiredis.c c:\users\teacher-5f84df\appdata\local\programs\python\python310\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': … -
How do I use Django/Python to create rows in a table?
I want to create a html table that has the number of rows and content set, according to what is in Django. I have written the following code: <h5>Model</h5> <a class="btn btn-sm btn-secondary" href="{% url 'create_model' %}?project={{ project.id }}" role="button">Add Model</a> <table class="table"> <thead> <tr> <th scope="col">Entry name</th> <th scope="col">Model</th> <th scope="col">Outcome</th> </tr> </thead> <tbody> <tr> <th scope="row">Entry Name</th> <td>2</td> <td>NaN</td> </tr> <tr> <th scope="row">Entry Name</th> <td>2</td> <td>NaN</td> </tr> <tr> <th scope="row">Entry Name</th> <td>3</td> <td>NaN</td> </tr> </tbody> </table> {% endblock content %} I can access 'Entry name;' through something like this: {% for entry in entries %} <tr> <td>{{entry.name}}</td> How do I set the number of rows I need according to what the database has stored for entry names? For example, if there are two entry names. I want to have double the number of rows, so that the table has the following form: -
Django data migration with contenttype keys
I need to make a Django data migration that creates some predefined initial values in tables. To create the predefined values I am using a fixture file that is called within the migration like so: def run_data_populating_fixtures(apps, schema_editor): call_command('loaddata', 'apps/app/fixtures/test.json') class Migration(migrations.Migration): dependencies = [ ('app', '0012'), ('contenttypes', '0001_initial'), ('core', '0001_initial') ] operations = [ migrations.RunPython(run_data_populating_fixtures, elidable=False) ] The table I am populating has a column content_type_id which is a foreign key to the django_content_type table. This becomes a problem because at the point when the data migration executes, the table doesn't have any of my apps' models registered. Basically in the fixture there is an explicit key specified as "content_type": 11, and it causes a FK violation. How can I run my data migration after django_content_type table has my models registered? I tried using natural keys instead of explicit ones as per migration article, like so "content_type": ["core", "mymodel"] but it doesn't seem to help, as it just produces an error that it couldn't find such content type. -
what is meaning of Django signed cookie?
Is value of signed cookie secure? I supposed that value of signed cookie is encrypting at response and decrypting at request. Here is no detail information about it But when I tried to get value of signed cookie it was visible: from django.http.response import JsonResponse as J j = J({}) j.set_signed_cookie("the_key", "the_value") j.cookies["the_key"].value > 'the_value:1newi4:nTgUngl_0y6YkqJd711GqMkAQFwXORbug6CdcL_Jo2Q' j.cookies["the_key"].coded_value >'the_value:1newi4:nTgUngl_0y6YkqJd711GqMkAQFwXORbug6CdcL_Jo2Q' What is the meaning of coded_value? the_value is clearly visible in both ways. Is it possible to encrypt cookie value? -
using Django template tags in response to ajax
I use Ajax to update a list of objects, let's say each time a button is clicked. But I want to use Django template tags to generate each item of the list. The problem is that I have to send a JsonResponse back to JavaScript, but there, I can't use these tags. I have to send object attributes as json. and I'm stuck with plain html in Ajax: ... success: function (json) { if (json.new_messages.length) { for (let m of json.new_messages) { $('#messages-list').append("<li>"+m.sender_name+" "+m.content+"</li>"); } } }, -
How to Rename your model to another model name in django
I have a model named Customer which is a 3rd table for user. It is related to many other models . Now due to my need I want to create a new model with the name Customer and delete the previous model . How can I do this, without ruining my migratinon . My current Customer model class Customer(models.Model):`enter code here` user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="user_customer") customer_key = models.CharField( max_length=5, null=True, blank=True, unique=True, editable=False, ) -
Error! Unable to find binary python3.8 for runtime python3.8 on Vercel
When i was deploying django app on vercel i got this error Error! Unable to find binary python3.8 for runtime python3.8 Error! Check your logs at https://komputama-qj1unu7v1-ngapa.vercel.app/_logs or run vercel logs komputama-qj1unu7v1-ngapa.vercel.app And the log in the deployment status is [16:26:29.158] Retrieving list of deployment files... [16:26:31.764] Downloading 1726 deployment files... [16:26:38.432] Warning: Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings [16:26:38.619] Installing build runtime... [16:26:42.087] Build runtime installed: 3.467s [16:26:42.423] Looking up build cache... [16:26:42.665] Build Cache not found [16:26:42.856] Starting build [16:26:42.861] Build AMI version: Amazon Linux release 2 (Karoo) [16:26:42.862] Lambda runtime: python3.8 [16:26:42.862] WSGI application: cores.wsgi.application [16:26:42.862] ====> Selecting python version [16:26:42.874] Error: Unable to find binary python3.8 for runtime python3.8 [16:26:42.874] at Object.findPythonBinary (/vercel/7c1ee15da2687191/.build-utils/.builder/node_modules/@ardnt/vercel-python-wsgi/build-utils/python.js:23:9) [16:26:42.874] at Object.exports.build (/vercel/7c1ee15da2687191/.build-utils/.builder/node_modules/@ardnt/vercel-python-wsgi/index.js:34:34) [16:26:42.874] at async mut (/var/task/sandbox.js:197:17526) This is my 'vercel.json' { "build": { "env": { "SECRET_KEY": "django-insecure-ub4*yrbpi+6#v3%(2w^!@u&r%pq6q6le4vi)enqpi6edmou)%#", "DEBUG": "True", "DB_HOST": "ec2-34-197-84-74.compute-1.amazonaws.com", "DB_NAME": "dc3rdsgt6ufbqd", "DB_USER": "xjvzrnscnfbses", "DB_PORT": "5432", "DB_PASSWORD": "cedb50250cec0e8ecc080a361a20e41133b561a3a92ac6038eff49c9219fc9e7" } }, "builds": [{ "src": "cores/wsgi.py", "use": "@ardnt/vercel-python-wsgi", "config": { "maxLambdaSize": "15mb", "runtime": "python3.8" } }], "routes": [ { "src": "/(.*)", "dest": "cores/wsgi.py" } ] } I got stuck with this, so anyone … -
Django doesn't requests the data to login users
<form action="login" method="post" > {% csrf_token %} <div class="form-group mb-3"> <label class="label" for="name">username</label> <input type="text" id="username" class="form-control" required> </div> <div class="form-group mb-3"> <label class="label" for="password">password</label> <input type="password" id="password" class="form-control" required> </div> <div class="form-group"> <input type="submit" action="login"> </div> <div class="form-group d-md-flex"> <div class="w-50 text-left"> <label class="checkbox-wrap checkbox-primary mb-0">Remember Me <input type="checkbox" checked> <span class="checkmark"></span> </label> </div> <div class="w-50 text-md-right"> <a href="#">Forgot Password</a> </div> This is the form. def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("dashboard") else: messages.info(request, "User doesn't exist. Contact the teacher!") return redirect("index") else: return render(request, "login.html") This is the views function. from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth import authenticate, login Those are the imports. But this doesn't redirect user who has already registered, to the page specified. Not a problem of urls or the csrf_token. I think the problem is in the sending data part because the else function triggers and shows the massege user doesn't exist..... Please help. -
Django runserver not woking (it's showing indentation error)
I tried to run my server but it did not work, it ended showing this instead. please help me File "C:\Users\ivbec\Envs\tutorial\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\Users\ivbec\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ivbec\python\djangoprojects\tutorial\myproject\myapp\urls.py", line 2, in <module> from . import views File "C:\Users\ivbec\python\djangoprojects\tutorial\myproject\myapp\views.py", line 5 def index(request): IndentationError: unexpected indent -
How can i route request to specific views according to parameters in Django?
I created an API with Django and i am trying to route requests to different views for optimization purposes. Here is what i'm trying to do: if the GET request is 127.0.0.1:8000/api/sales/?key=<KEY>&some_query=<some_value>&... that query should be handled by a view called sales. If the GET request contains a specific parameter called sale_value the request should be routed to another view called large_sales, for example 127.0.0.1:8000/api/sales/?key=<KEY>&sale_value=<INT>... should be handled from the large_sales view. Here is what i tried: urlpatterns = [ path('sales/', views.sales, name="sales"), path('sales/sale_value<int:num>', views.large_sales, name="large_sales"), ] This will route all the requests to sales. How can i do this? Maybe with regex? -
Djnago ninja | Trying to send file | no validator found for <class 'django.http.response.HttpResponse'>, see `arbitrary_types_allowed` in Config
good people, I'm trying to implement a file download functionality. And the code is pretty straightforward: @api.get("/summary/", response=HttpResponse) def report_summary( request: NinjaRequest, start_date: str, end_date: str ) -> HttpResponse: ... response = HttpResponse( output, # output is the file content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = f"attachment; filename={fname}" # fname is the name of the file return response But it gives me an error saying during bootup: RuntimeError: no validator found for <class 'django.http.response.HttpResponse'>, see `arbitrary_types_allowed` in Config I don't want to set arbitrary_types_allowed. Now how can I resolve this issue? -
Why django ManytoManyFied don't save some models?
Below is my models.py. class Report(models.Model): company_name = models.CharField(max_length = 40, default = "-") favorite = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_reports') def __str__(self): return self.company_name class Fav(models.Model) : report = models.ForeignKey(Report, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='favs_users') class Meta: unique_together = ('report', 'user') def __str__(self) : return '%s likes %s'%(self.user.username, self.report.company_name[:10]) Below is views.py def post(self, request, pk) : t = Report.objects.get(id = pk) fav = Fav(user=request.user, report=t) try: fav.save() # In case of duplicate key print(request.user.favorite_reports) #home.Report.None print('t =', t.favorite) # t = auth.User.None print('fav =',fav.report, fav.user) # fav = untitle hello1 print('uesr =',request.user, request.user.favorite_reports,request.user.favs_users) #uesr = hello1 home.Report.None home.Fav.None except IntegrityError as e: pass return redirect('home:homepage') I want show different button color to user whether user fav some report or not. So I checked request.user.favorite_reports and request.user.favs_users after I save Fav but it return home.Report.None home.Fav.None But When I print fav.report, fav.user It returns well. Why this happened? How can I check user Fav some report in template? like {% if report.company_name in user.favorite_reports %} But It dosen't works. -
Django URLCONF and reverse
I am trying to understand how django links the main urls.py with the url patterns of another application-Here in my case I have 2 apps: loginpage and signup. I defined in the main urls.py this: urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')),] and this in loginpage.urls: app_name='loginpage' urlpatterns = [ path('',views.login_page_fetch,name='login_page_fetch'), path('Verification/',views.check_user,name='check_user') ] I created a function in loginpage/views that get a template and fetch it: def login_page_fetch(request): return render(request,'loginpage/login.html') Now in my signup/views I created a function that created a user etc.. it will have in the end to redirect him to the login page: def create_user(request): user=User() user.first_name=request.POST.get('firstname') user.last_name=request.POST.get('familyname') user.email_address=request.POST.get('email') user.password=request.POST.get('psw') user.save() return HttpResponseRedirect(reverse('loginpage:login_page_fetch')) *//* I cannot understand starting from here // how django finds the login_page_fetch function-does he start looking in the main urls.py file to find a path where its mapped to loginpage.urls? -
NOT NULL constraint failed: forum_question.user_id (django)
I'm trying to save an object using cbv's im new to using it, and I'm trying to save an object using create view but is getting this error: "NOT NULL constraint failed: forum_question.user_id" I would appreciate beginner friendly explanation on how to fix this and maybe tips as well, thank you! models.py: class Question(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=30) detail = models.TextField() tags = models.TextField(default='') add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms.py: class QuestionForm(ModelForm): class Meta: model = Question fields = ['title', 'detail', 'tags'] views.py: class AskForm(CreateView): def post(self): user = self.request.user model = Question form_class = QuestionForm template_name = 'forum/ask-question.html' if form_class.is_valid(): form_class.save() -
python image scrapper become base64
I have scrapper tools, but my code are always scrap base64 instead of real urls,here is my code: import requests from bs4 import BeautifulSoup baseurl = "https://www.google.com/search?q=beli+anjing&sxsrf=APq-WBt4jLZxrfwaRP4YeYUhlfB-EWkTlw:1649653964236&source=lnms&tbm=shop&sa=X&ved=2ahUKEwjEnan0n4v3AhUNRmwGHTIVDlQQ_AUoAnoECAEQBA&biw=1365&bih=937&dpr=1" headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"} r = requests.get(url=baseurl, headers=headers) soup = BeautifulSoup(r.content, 'lxml') for product_images in soup.findAll('div', attrs={'class': 'ArOc1c'}): print (product_images.img['src']) The result is something like: data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== And here is the html element that i wanna to scrap: <img id="10857343619710684967" src="https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcTP0ECipmHbw3MkChu6xHYkHA3AzxaiNoUnqxaW35bfDkFugfhO23iwklpDjhYlUFI-RIyLu95TkcpNCBGxBeKPIarPilIv6a697PoK-RM&amp;usqp=CAE" alt="" role="presentation" data-atf="4" data-frt="0"> I want the src value, but when i scrap, it always get base64 instead of the real urls like above. result that i want: https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcTP0ECipmHbw3MkChu6xHYkHA3AzxaiNoUnqxaW35bfDkFugfhO23iwklpDjhYlUFI-RIyLu95TkcpNCBGxBeKPIarPilIv6a697PoK-RM&amp;usqp=CAE