Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 error on new pages with wordpress blog ( on mysql) with django (postgres) using nginx on the same server
Condition : I have set up my server as follows : my wordpress blog ( on mysql) with django (postgres) using nginx on the same server. Error I am getting 404 error for new pages I create on the blog. ( it works when permalink settings is like this : https://www.example.com/blog/?p=1 It does not work when permalink setting contains post name New pages I create also behave in similar fashion - do not work with name slug My analysis is that it has something to do with ssl conf or nginx conf. Basically routing issue. I am a newbie. Here is the Nginx Conf: upstream app_server { server unix:/home/user/opt/env/run/gunicorn.sock fail_timeout=0; } #wordpress php handler upstream wordpress-prod-php-handler { server unix:/var/run/php/php7.0-fpm.sock; # serve wordpress from subdirectory location /blog { alias /home/user/opt/blog; index index.php; try_files $uri $uri/ /blog/index.php?$args; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass wordpress-prod-php-handler; } } Please help.. As specified, I was trying to get my blog and app on the same domain. www.example.com -> opens django app www.example.com/blog -> opens wordpress blog Now it works fine, but if anything comes after /blog -- such as example.com/blog/test will result in a 404 error. Nginx error log shows this … -
custom django form field (django-recaptcha) is not added to AuthenticationForm class
objective: adding a new field from (captcha field) within Django Admin Login Form. enabling below method (google captcha v2 - I'm not robot checkbox): https://github.com/torchbox/django-recaptcha Django: Tested on 4.0.X, 4.1.X, 3.2.X versions. project name: ea_games app name: ea_app ea_games\ea_app\froms.py: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import get_user_model from django import forms from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox class CustomLoginForm (AuthenticationForm): #class Meta: # model = get_user_model() # fields = ('required_checkbox',) ## comment/un-comment didn't work. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) required_checkbox = forms.BooleanField(required=True) ## added to test but it's not showed in django admin login form. username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Username or Email'}), label="Username or Email") password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'}), label="Password") captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox()) ea_games\ea_app\views.py: class CustomLoginView (LoginView): form_class = CustomLoginForm template_name = "ea_app/login.html" def form_invalid (self, form): print ("form_invalid:::::", form) ## it's not called to print :/ return self.render_to_response (self.get_context_data(form=form)) def form_valid (self, form): print ("form_valid::::::", form) ## it's not called to print :/ checkbox = form.cleaned_data['required_checkbox'] return super().form_valid(form) ea_games\ea_app\templates\ea_app\login.html: {% extends "admin/login.html" %} Also for project's urls.py file, i checked many solutions and they didn't work: ea_games\urls.py: from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings … -
How to get id from another table in django?
I am writing a script to populate database tables. I need to get foreign key from city table. There are 3 fields in the City table: id, name, reference. I need a foreign key for the Warehouses table with fields id, name,reference, city_id (foreign key). I take all the data from the API. def refresh_warehouses(): api_domain = 'https://api.novaposhta.ua' api_path = '/v2.0/json/Address/getWarehouses' api_data = { "modelName": "Address", "calledMethod": "getWarehouses", "methodProperties": { "Limit": "5" }, 'apiKey': settings.NOVA_POSHTA_API_KEY } response = requests.post(api_domain + api_path, json=api_data).json() if not response.get('success'): raise Exception(','.join(response.get('errors'))) Warehouse.objects.all().delete() warehouses = [] for item in response.get('data'): params = { 'name': item.get('Description'), 'reference': item.get('Ref'), 'city_id': City.objects.get(name=item.get("CityDescription")).id, 'delivery_method_id': 1 } warehouses.append(Warehouse(**params)) Warehouse.objects.bulk_create(warehouses) After executing the script, django throws a FOREIGN KEY constraint failed error. Tell me how best to take the id from the City table? -
How to get all items related to a Foreign Key in django?
My aim is to get all the items with a particular category from the model I created. For example, if I should get a category with an ID, I want to get all the products that is in that category. Below is my model class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name class Category(models.Model): #product = models.ForeignKey('Product', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name Below is my view def getCategory(request, pk): category = Category.objects.get(id=pk) # product = Product.objects.all() products = Product.category_set.all() # Product.category_set.all() context = {'category': category, 'products':products} return render(request, '*.html', context) I tried using Product.category_set.all() and I have tried to flip it over, getting the products relaed to the category that I got the ID but I dont know how I can do that. I used this loop below in my template and it worked but I wonder if there is a better way to do it. Template {% for product in products %} {% if product.category.id == category.id %} View def getCategory(request, pk): category = Category.objects.get(id=pk) products = Product.objects.all() context = {'category': category, 'products':products} return render(request, … -
User can't login because of "Invalid password format or unknown hashing algorithm."-Django
I'm learning Django and tried to write my own custom user model. I'm not using DRF and serializers and stuffs I have no idea about :) I am using createView to create users but I can't login because "Invalid password." I checked the user's password in admin and the user's password is "Invalid password format or unknown hashing algorithm." . here are the codes: Custome User and User Manager in models class UserManager(UserManager): def create_user(self, username, email, password, **extra_fields): if not email: raise ValueError('User must have email') if not username: raise ValueError('User must have username') user = User.objects.create_user( username=username, email=self.normalize_email(email), ) user.set_password(password) user.save() return user def create_superuser(self, username, email, password, **extra_fields) : user = self.create_user(username, email, password) user.is_staff = True user.is_superuser = True user.is_admin = True user.is_active = True user.save() return user class User(AbstractBaseUser): username = models.CharField(unique=True, max_length=200) email = models.EmailField(unique=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(auto_now=True) objects = UserManager() REQUIRED_FIELDS = ["username","email", "password"] USERNAME_FIELD = "username" def __str__(self): return self.email def has_perm(self, perm, object=None): "Does the user have a specific permission?" return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # … -
django: modelChoiceField form not working in template
I am confronted for the first time to a situation where I want the user to select model column values based on some constraint. The goal is to have the user select something and then output the result below the form on the same page. I am not sure what I am doing wrong but submiting the form output: Select a valid choice. That choice is not one of the available choices. Here is what I have been able to do: forms.py class SelectBuildingForm(forms.Form): filename = forms.ModelChoiceField(queryset=Building.objects.none()) def __init__(self, *args, **kwargs): us = args[1] or None forms.Form.__init__(self, *args, **kwargs) self.fields['filename'].queryset = Building.objects.filter(project=us).values_list('filename',flat=True) views.py @login_required @owner_required def FileSelectionView(request,pk): form = SelectBuildingForm(request.POST or None, pk) # if form.is_valid(): # filename = form.cleaned_data('filename') # print(filename) # return redirect('comparator_test') return render(request,'files_selection.html', {'form':form}) and template <div class="mt-5 md:col-span-2 md:mt-0"> <form method="POST" id="my-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="Select">GOOOO</button> </form> {% if form.is_valid %} {% for choice in form.cleaned_data.choices %} <p>{{ choice }}</p> {% endfor %} {% endif %} </div> I have tried a couple options to validate the selection but none of them work. Can a pair of fresh eyes see where I am messing up? -
How can I call an asynchronous function inside my synchronous Consumer?
In my django quiz project I work with Channels. My consumer QuizConsumer is synchronous but now I need it to start a timer that runs in parallel to its other functions and sends a message after the timer is over. class QuizConsumer(WebsocketConsumer): def configure_round(self, lobby_id): # Call function to send message to begin the round to all players async_to_sync(self.channel_layer.group_send)( self.lobby_group_name, { 'type':'start_round', 'lobby_id':lobby_id, } ) self.show_results(lobby_id, numberVideos, playlength) def start_round(self, event): self.send(text_data=json.dumps({ 'type':'start_round', 'lobby_id': event['lobby_id'] })) def show_results(self, lobby_id, numberVideos, playlength): async_to_sync(self.channel_layer.group_send)( self.lobby_group_name, { 'type':'show_results_delay', 'lobby_id':lobby_id, 'numberVideos':numberVideos, 'playlength':playlength, } ) def show_results_delay(self, event): time.sleep(event['numberVideos']*event['playlength']+5) self.send(text_data=json.dumps({ 'type':'show_solution', 'lobby_id': event['lobby_id'] })) I tried to work with async functions and await, but I did not get it to work as I expected yet. I tried to work with async functions but so far it disconnected from the websocket or it did not send the "start_round" until the timer was finished. -
Postgresql : Global replace all foreign key references to a row with another
I am using postgres with Django. I have a table of users. The rows are referenced in other tables as foreign keys. Some times, we want to merge two user rows into one. We want to replace all references to a particular row with another. Is this possible? -
How to save 1 information to 2 tables on Django
How can I save 1 information to 2 tables on Django, when user register he entres his username, and I need to save this username in table "users" and in table "authors", how can i realize it? views.py def register(request): if request.method == 'POST': nick = request.POST.get('nick') email = request.POST.get('email') password = request.POST.get('password') ppassword = request.POST.get('ppassword') if password == ppassword: new_user = User.objects.create_user(nick, email, password) new_user.nick = nick new_user.email = email new_user.save() return redirect('../login/') else: return HttpResponse("Пароль и повтор пароля не совподают") return render(request, 'main/register.html') models.py class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) username = models.CharField(max_length=40, blank=True) slug = slug = models.SlugField(max_length=400, unique=True, blank=True) bio = HTMLField() profile_pic = ResizedImageField(size=[50, 80], quality=100, upload_to="authors", default=None, null=True, blank=True) def __str__(self): return self.username @property def num_posts(self): return Post.objects.filter(user=self).count() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) super(Author, self).save(*args, **kwargs) Regards, Idris. -
Reverse for 'login' not found. 'login' is not a valid view function or pattern name
[Reverse for 'login' not found. 'login' is not a valid view function or pattern name.[Main.urls[Views.pyUrls.py](https://i.stack.imgur.com/Q88iG.png)](https://i.stack.imgur.com/MPxwl.png)](https://i.stack.imgur.com/9KYhw.png) NoReverseMatch at /user/signup/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method:POSTRequest URL:http://127.0.0.1:8000/user/signup/Django Version:4.1.4Exception Type:NoReverseMatchException Value:Reverse for 'login' not found. 'login' is not a valid view function or pattern name.Exception Location:C:\Users\JOSHI\OneDrive\Desktop\Watch Store\Venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefixRaised during:User.views.signupPython Executable:C:\Users\JOSHI\OneDrive\Desktop\Watch Store\Venv\scripts\python.exePython Version:3.9.0Python Path:['C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Online_Shop', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Venv', 'C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Venv\\lib\\site-packages']Server time:Sat, 31 Dec 2022 06:39:18 +0000 -
How to upload multiple images to Django?
I am trying to send some data from the client side (react native) that includes a few images so I append them to formdata and successfully send it through a post request but I am having trouble figuring out how to handle it on the server side. My react code: const post = async () => { const token = await getToken(); const [description, setDescription] = useState(''); const formData = new FormData(); images.forEach((image) => { formData.append(`images`, { uri: image, type: 'image/jpeg', name: image, }); }); formData.append('description', description); console.log('formdata:', formData); try { await axios.post(URL, formData, { headers: { 'Content-Type': 'multipart/form-data', Authorization: token, }, }); } catch (e) { console.log(e); } }; when i console log formdata on client side i get: formdata: [["images", {"name": "/Library/Developer/CoreSimulator/Devices/123.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/123.jpg"}], ["images", {"name": "/Library/Developer/CoreSimulator/Devices/456.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/456.jpg"}], ["description", "Test"]] on my server side (django/drf): models.py: class Post(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE, default=None ) images = models.FileField( max_length=3000, default=None, null=True, blank=True, upload_to='media/post_images') description = models.TextField(null=False, default=None) date = models.DateTimeField(editable=False, auto_now_add=True) serializers.py: class PostSerializer(serializers.ModelSerializer): images = serializers.FileField() class Meta: model = Post fields = "__all__" views.py class PostView(APIView): serializer_class = PostSerializer parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): form_data = request.data images … -
RollupError: "default" is not exported by "node_modules/react-infinite-scroller/index.js"
Using v1.2.6 of react-infinite-scroller in a reactjs .tsx bumps into the following build error: [!] RollupError: "default" is not exported by "node_modules/react-infinite-scroller/index.js", imported by "src/core/DataTable.tsx". https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module src/core/DataTable.tsx (6:7) 6: import InfiniteScroll from 'react-infinite-scroller'; What do I miss? -
Django Application CPanel Internal Server Error 500
I am getting a Internal Server Error in my Django Application hosted in Cpanel . I have tables with Links and sublinks associated with those links . so the url is like https://[domain]/links/ and https://[domain]/links// . Everything works fine on local host but whenever i go to the Sublink in the live website I get 500 Error. I am really lost as I dont know how to debug this . I dont know how to start to look at the error . I looked at the log file and this is the ouput . Can anyone tell me how to start debug this error since its running properly on the localhost so I cant find anything . -
Django: mysterious slow request before timing middleware kicks in
I'm using Django with Sentry to monitor errors and performance. There's one specific endpoint (this doesn't happen with other endpoints) that seems to stall for a few seconds before actually processing the request. It's a very simple endpoint, but it does get called a lot. It seems to do nothing for a few seconds and is waiting on the time before Django middleware is even called. The actual logic that goes into rendering only takes a few hundred milliseconds: something is happening before the Django middleware that causes this to only happen for this view. What could this mean? I don't often see the Django.db.close_old_connections call and I'm hoping someone might have a clue for what might be causing it when the stall is after that, with another stall in the same place towards the end right before close_old_connections is called again. -
can't authenticate username and pasword of another table
my project is a online store, My admin side and store side just use username and password at table User with Superuser permission to login, If login at store admin side login too and vice versa. data User data Customer this is my code views.py def register(request): registered= False last_visit = request.session.get('last_visit',False) if request.method == 'POST': form_user = FormCustumer(data=request.POST) form_por = UserProfileInfoForm(data=request.POST) if (form_user.is_valid() and form_por.is_valid() and form_user.cleaned_data['password'] == form_user.cleaned_data['confirm']): user = form_user.save() #user.set_password(user.password) user.password = make_password('password') user.is_active = True user.save() #profile = form_por.save(commit=False) #profile.user = user if 'image' in request.FILES: user.image = request.FILES['image'] user.save() registered=True email_address = form_user.cleaned_data['email'] subject = 'Chào mừng bạn đến với chúng tôi' message = 'Hi vọng bạn có những giây phút thư giãn và có những lựa chọn mua sắm đúng đắn!' recepient = str(email_address) html_content = '<h2 style="color:blue"><i>Dear Reader,</i></h2>'\ + '<p>Chào mừng bạn đến với <strong>EShop</strong> website.</p>'\ + '<h4 style="color:red">' +message + '</h4>' msg = EmailMultiAlternatives(subject, EMAIL_HOST_USER, [recepient]) msg.attach_alternative(html_content, 'text/html') msg.send() #send_mail(subject,message, EMAIL_HOST_USER,[recepient],fail_silently=False) if form_user.cleaned_data['password'] != form_user.cleaned_data['confirm']: form_user.add_error('confirm', 'Mật khẩu xác nhận không chính xác') print(form_user.errors,form_por.errors) else: form_user = FormCustumer() form_por = UserProfileInfoForm() username = request.session.get('username',0) cart = Cart(request) return render(request, 'store/signin.html',{ 'subcategories': subcategory_list, 'form_user':form_user, 'form_por':form_por, 'registered':registered, 'username':username, 'cart': cart, 'today':now, 'latest':latest, 'last_visit':last_visit, … -
How to accept a file upload in django and send it to a flask api as a file upload?
I have a Flask API running on my localhost that accepts a file as a form data and returns an output. I also have another application that is created using Django that actually faces the user. I'm trying to have it so that a user can upload a file to the Django app and the Django app then forwards the file to the API. So far I've got this code: In Django views.py: url = 'http://127.0.0.1:5000/uploadFile' files = {'file': request.FILES['file']} response = requests.post(url, files=files) In Flask: @app.route("/uploadFile", methods=["GET", "POST"]) def uploadFile(): if request.method == "POST": file = request.files.get("file") I've tested the Flask api using Postman and it works as expected. Running the above code, I get the following output (error): I get a long series of this output repeated several times: Object 5 0 not defined. Overwriting cache for 0 5 And this at the end of it: RecursionError: maximum recursion depth exceeded while calling a Python object -
Django Advice - model_to_dict - User returning ID instead of username
I'm calling the model_to_dict function and it is working, but i want to be able to modify the results before returning. The Author area is currently returning an id number and I want it to return the Username instead. Does anybody know how to make that happen? .model class Comment(models.Model): poopfact = models.ForeignKey(PoopFact, related_name="comments", on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(unique=True, blank=True, null=True) datetime = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="comment_likes") .views def comment(request, poopfact_id): ... new_entry = Comment() ... data = model_to_dict(new_entry) return JsonResponse(data, safe=False) -
Need jQuery AJAX response Advice - Passing multiple response['Variables'] in multiple HTML createElements - Django
I'm trying to asynchronously update a comment section on my page which has multiple elements that need to be created and multiple variables that need to be updated. I know how to create multiple elements, but not sure how to update place multiple response variables. I've pretty much replaced all the django templates {{variable}} with a ${response['var']} but it doesn't work. Any advice on this? current html structure with django templates {% for comment in poopfacts %} <div class="row"> <p class="col text-muted fw-light d-inline" style="font-size:10px;"> {{comment.author}} </p> <p class="col text-muted fw-light d-inline" style="font-size:10px;" align="right"> {{comment.datetime}} </p> </div> <p> {{comment.comment}} </p> <p class="d-inline like-count{{comment.id}}"> {{ comment.like_count }} </p> likes <form action="{% url 'like_comment' comment.id %}" class="d-inline like-form" id="{{comment.id}}"> <button type="submit" class="btn btn-link">like</button> </form> {% endfor %} .script success: function(response) { $(`.comment-row${poopfact.id}`).append(` <div class="row"> <p class="col text-muted fw-light d-inline" style="font-size:10px;"> ${response['author']} </p> <p class="col text-muted fw-light d-inline" style="font-size:10px;" align="right"> ${response['datetime']} </p> </div> <p> ${response['comment']} </p> <p class="d-inline like-count${response['id']}"> ${response['datetime']} </p> likes <form action="{% url 'like_comment' ${response['id']} %}" class="d-inline like-form" id="${response['id']}"> <button type="submit" class="btn btn-link">like</button> </form> `) -
Why the checkboxes are not sent though request?
I am doing a form with checkboxes, but I can't make it send to the view. The request only send the csrf token. What I am doing wrong? <form action="select" method="POST"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ subject.id }}" id="flexCheckDefault{{ subject.grouper }}{{ subject.id }}" > <label class="form-check-label" for="flexCheckDefault-{{ subject.name }}"> {{ subject.name }} </label> </div> <button type="submit" class="btn btn-sm btn-primary pull-left"><i class="fa fa-check"></i> Save</button> Request: csrfmiddlewaretoken=VQRxpROz9G9b1ObLSqBX7AP6JaIneD2sW1lxRFNjypEuuKCPOM2GEtoMD383u53S -
Only accept values based on another table ? (MySQL, PostgreSQL, Django)
I'm developing a School/University software and I got stucked in this situation: Table Professor id name 1 Mr. Ward 2 Mr. Smith Table Subject id name 1 Math 2 Physics 3 English Table ProfessorsSubject p_id s_id 1 1 1 2 2 3 (Mr. Ward, Math), (Mr. Ward, Physics) and (Mr. Smith, English) Table StudentClass: id name Building 10 Tenth Grade A 11 Eleventh Grade A Table A: sclass_id subj_id prof_id foo bar 10 1 1 foo1 bar1 10 2 1 foo2 bar2 10 3 NULL foo3 bar3 11 1 1 foo4 bar4 11 2 1 foo5 bar5 11 3 2 foo6 bar6 The pair(sclass_id, subj_id) must be UNIQUE. prof_id might be NULL. CREATE TABLE Professor ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL ); CREATE TABLE Subject ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL ); CREATE TABLE ProfessorsSubject ( prof_id int, subj_id int, PRIMARY KEY (prof_id, subj_id), FOREIGN KEY (prof_id) REFERENCES Professor(id), FOREIGN KEY (subj_id) REFERENCES Subject(id) ); CREATE TABLE StudentClass ( id int PRIMARY KEY AUTO_INCREMENT, name varchar(100) NOT NULL, building varchar(100) ); CREATE TABLE A ( sclass_id int, subj_id int, prof_id int, foo varchar(10), bar varchar(10), PRIMARY KEY (sclass_id, subj_id), FOREIGN KEY (sclass_id) … -
How to trigger a python script on the server through user action in react (Django+React)?
I'm trying to launch a python script on the backend when a user enters some numbers into a form using react. I have Django as the main "shell" for my app handling the backend and is pointing to React properly for the frontend. The idea is to run all complex mathematical models, big data processing, and calculations on Python in the backend while node.js is used to run only front-end UI related scripts. Django for substance, React for the aesthetics. I am able to use SpawnSync child_process in Node.jus to successfully execute when I type "node run_python.js" in the command line ("run_python.js" is the name of my function). But when I run "npm run dev", that's when node is saying it can't find child_process. I checked node_modules and the childprocess library is there with keywords "child_process" included in the pacakge.json. I also tried referencing "child_process" in the main package.json file as a dependency. Is there a better way to trigger a python script on the server through action in react? -
Accessing session data from websocket consumer in Django
I save task_ids as a session variable in a view: request.session['task_ids'] = task_ids and I want to access that data in the websocket consumer: import requests class ProcessConsumer(WebsocketConsumer): def connect(self): self.accept() session = requests.Session() task_ids = session.get('task_ids') // I guess I'm doing this wrong self.send(text_data = json.dumps({ 'task_ids': task_ids })) I get the following error: requests.exceptions.MissingSchema: Invalid URL 'task_ids': No scheme supplied. Perhaps you meant http://task_ids? How can I access session data from websocket consumer in a proper way? Thanks. -
How to get the value from a template in Django to pass it to another template?
I have a template which only lists records, and I have another template to show each record's details. I use function views. My list template's some parts are as shown below; ` {% if list.item_name == 'A' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_01' %}">View</a> {% elif list.item_name == 'B' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_02' %}">View</a> {% elif list.item_name == 'C' %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_03' %}">View</a> {% else %} <a type="button" class="btn btn-info" role="button" target="_blank" href="{% url 'app_name:template_04' %}">View</a> {% endif %} ` What I am trying to achieve is that when one of the above options is selected, I want to display the item_name in the detail template like this; <h1>{{ list.item_name }}</h1> So, if it worked, it would be A, B, C, or the item name which comes from the else option. I tried using function views for this purpose. My function views are like the ones shown below; ` def List_FunctionView(request): context = {} context["list"] = some_model.objects.all() Detail_FunctionView(request, context) template_name = "app_name/list.html" return render(request, template_name, context) ` def Detail_FunctionView(request, context): selected_item = request.GET.get('list.item_name') context2 = context template_name = "app_name/template_04.html" return render(request, template_name, context2) … -
How to make little search in Django
I want to make search function in my project, with Model Agreements from django.db import models class Agreements(models.Model): username = models.CharField(max_length=128) # this i want to use to search email = models.CharField(max_length=128, unique=True) phone_number = models.CharField(max_length=128, unique=True) creation_date = models.DateField() conclusion_date = models.DateField() def __str__(self): return str(self.username) views.py from django.shortcuts import render from django.views.generic import ListView from django.db.models import Q from connections.models import Agreements, Connections def index(request): context = { 'index': Agreements.objects.all(), 'HM': Connections.objects.all(), } return render(request, 'list_agreements.html', context) class Search(ListView): template_name = 'list_agreements.html' context_object_name = 'Agreements' def get_queryset(self): return Agreements.objects.filter(username__icontains=self.request.GET.get('q')) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['q'] = self.request.GET.get('q') return context my urls.py from django.contrib import admin from django.urls import path from connections.views import index, Search urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('search/', Search.as_view(), name='search'), ] [enter image descrienter image description hereption here](https://i.stack.imgur.com/gClVN.png) my list_agreements.html (only important parts) <form class="d-flex" role="search" action="{% url 'search' %} " method="get"> <input class="form-control me-2" type="search" type="text" placeholder="Search" aria-label="Search" name="q"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> <div class="limiter"> <div class="container-table100"> <div class="wrap-table100"> <div class="table100 ver1"> <div class="table100-firstcol"> </tbody> </table> </div> <div class="wrap-table100-nextcols js-pscroll"> <div class="table100-nextcols"> <table> <thead> <tr class="row100 head"> <th class="cell100 column2">ФИО</th> <th class="cell100 column3">Почта</th> <th class="cell100 … -
Does chaining prefetch_related fetch all sub-queries?
Take this for example: user = User.objects.prefetch_related("foo__bar__baz").get(id=id) In this scenario, do I not need to do: user = User.objects.prefetch_related("foo__bar").get(id=id) if I want to access values on bar, or if they are mixed between select_related and prefetch_related due to some being OneToOne and others being FK like this below? user = User.objects.prefetch_related("foo__bar__baz").select_related("foo_bar_baz_qux").get(id=id) Or would skipping the prefetch and only using select be sufficient? user = User.objects.select_related("foo_bar_baz_qux").get(id=id)