Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django Channels without views
We want to use Django Channels to use Keras with Tensorflow as model. We've tried Flask but it's not usable for production. Then we tried Javas DeepLearning4J but also got to many problems. We want to solve it with Python. The problem is that Django is fullstack and we just need to use the websockets and execute our python code and send the results back. There is literally no example on Google how to do this. We do this because we got an Angular frontend, Spring Boot backend and another Spring Boot Application as connector between all services. We don't need the most functionalities of Django. It's very hard to find out what do. There is no @socket.route or something like this I think. Websocket using Django Channels this question was maybe a bit helpful but 3 years old and probably outdated. What is the way to achieve what we need? -
Django allauth - Signing up a new user while already logged in
I'm trying to customize allauth's default SignUpView and SignUpForm to allow me to create other users while already logged in. The default behavior prevents me from doing this: in other words, I can only sign up for a new account if I'm not authenticated. How do I override this behavior? I presume I'll have to override the SignupView in views.py but I'm not sure what to look for... Forms.py from allauth.account.forms import SignupForm class SubUserForm(SignupForm): USER_TYPES = [ (2,'customer'), (3,'vendor'), (4,'supplier') ] first_name = forms.CharField(max_length=45) last_name = forms.CharField(max_length=45) user_type = forms.CharField(widget=forms.Select(choices=USER_TYPES)) Views.py from allauth.account.views import SignupView class SubUserSignupView(SignupView): template_name = 'accounts/new_user_signup_form.html' form_class = SubUserForm view_name = 'sub_user_signup' sub_user_signup = SubUserSignupView.as_view() urls.py urlpatterns = [ path('sub_user/',views.sub_user_signup,name='sub_user_signup'), ] Context and extra info: My app allows for a 'parent' user to sign up multiple 'children' users using allauth. In my case, an organization can create several customers, merchants, suppliers, etc. When the the parent user creates a new user, a verification email is sent to the child user, who then activates his account and is prompted to enter a password. I use 2 signup forms; the default allauth signup (for parent accounts), and a customized signup form (for children accounts), which also extends … -
How to open a static file in views.py
I have a little issue with opening a csv file in my views.py Have tried the following 2 things: Open the file while it is in the same directory. Open the file from my static folder. None worked, the framework django is new for me. The code i have right know is a easy one :): from django.shortcuts import render from .models import shopify_orders as sb import csv def csv_converter(request): if request.method == 'POST': f = open(orders_export.csv) csv_f = csv.reader(f) f.close else: return render(request, 'serviceapp/csv.html') There are some tutorials explaining how to import csv data in models, but my csv file is a bit complex. Django directory Your help is apreciated ! -
python Django - lists large array: best way to store and retrieve data when wanted
I am working on a django project. After an operation i get a list of list items. the lenght of the array is 35,000 i have a model and table in django for this. But for me to bulk insert so many data looks time consuming. And i have to do this operation every 1hr. And what to speak of bulk updating so many entries next time. But the advantage of using database is i can filter the records the way i want and show the results. I am thinking instead to store the list in a file and retrieve it when wanted How can i do this effeciently with very little time. I also want to later extract some data based on some filters. Can we use numpy to get data like top50 of a particular column data if i import the list from the file as numpy array. -
How to solve Django python3 handler 'benchmark' error
I get this error of handler 'benchmark' and it seems that Django starts to run in "dev/proj/venv3/lib/python3.8" environment and converts to "/usr/local/Cellar/python@3.8/3.8.6/Frameworks.." not sure if there is a correlation. What can cause to that? Error: Exception ignored in thread started by: <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x10a7d9490> Traceback (most recent call last): File "/Users/username/.vscode/extensions/ms-python.python-2020.11.358366026/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py", line 827, in __call__ ret = self.original_func(*self.args, **self.kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/username/dev/proj/venv3/lib/python3.8/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/config.py", line 808, in dictConfig dictConfigClass(config).configure() File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'benchmark'``` -
Understanding the "args" of HttpResponseRedirect in views.pyfile in Django
I have these two functions in my views.py file: def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def search(request): if request.POST["q"] in util.list_entries(): return HttpResponseRedirect(reverse("entry", args=(request.POST["q"],))) else: return render(request, "encyclopedia/error.html") How we can understand the args of HttpResponseRedirect. Where this args passed in the entry function? I just need the behind the scene action of this "args". -
Failed to save using SelectMultiple in Django
I've got a problem to save in DB data using "Select Multiple Field" My code looks like: Models.py class Author(models.Model): author_name = models.CharField(max_length=100) author_lastname = models.CharField(max_length=100) class Book(models.Model): statement_title = models.CharField(max_length=1000, null=True, blank=True) author = models.ManyToManyField(Author,blank=True) Forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['__all__'] widgets = { 'title': forms.Textarea(attrs={'type': 'text', 'placeholder': 'Book title'} 'author': forms.SelectMultiple() } If I add a new object everything is saving but without the author, but if I save author in admin page I can display authors in book-detail view. Of course, I tried many solutions to solve this problem but nothing solved my problem. I know I'm made a mistake but I don't have an idea where... Maybe I should add something extra in views.py? I'll be very grateful for any tips and clues. -
Django Rest Framework - Filtering fields on serializer form
I have a form called "Contact" that is rendered from a serializer (APIView). That "Contact" model has two ForeignKeys: "City" and "State". All possible "Cities" are on the database already and it has a ForeignKey to determines the "State". What I need to do is to filter the form to show only the cities from that state that I select earlier and not all the cities on the table. Unfortunately I can't show the code because it's not on my computer, but I would be realy grateful if someone could give me any clue on how I can do that. -
Django showing the domaine name as example.com
my Django project doesn't display the correct domain name when i try to reset the password: its showing: "example.com" You're receiving this email because you requested a password reset for your user account at example.com. Please go to the following page and choose a new password: https://example.com/reset/MQ/ad8qye-29c2364e246e74a700774721674d01c1/ Your username, in case you’ve forgotten: ****** Thanks for using our site! -
When I make migrations to Django, all accounts are deleted
When I enter the commands python manage.py makemigrations and python manage.py migrate all accounts are deleted from the database. Perhaps the database is simply re-created -
Proper validation in Rest Api Django
I have this code in my serializers.py: from rest_framework import serializers from .models import OnlineMeeting def valid_name(dob): if dob.isalpha() is False: raise serializers.ValidationError("Name and surname must contain only letters") return dob class MeetingsListSerializer(serializers.ModelSerializer): class Meta: model = OnlineMeeting fields = '__all__' class OnlineMeetingDetailSerializer(serializers.ModelSerializer): start_time = serializers.TimeField() end_time = serializers.TimeField() owner_first_name = serializers.CharField(validators=[valid_name]) owner_last_name = serializers.CharField(validators=[valid_name]) participant_first_name = serializers.CharField(validators=[valid_name]) participant_last_name = serializers.CharField(validators=[valid_name]) def validate(self, data): if data['start_time'] > data['end_time']: raise serializers.ValidationError("finish must occur after start") return data class Meta: model = OnlineMeeting fields = '__all__' I don't inherit OnlineMeetingDetailSerializer from serializers.Serializer which is used for implenting your own validation, is it bad? Can I also write validation in classes which inherit serializers.ModelSerializer? -
Cant filter by category
I am trying to make a filtering system by category.When ever i try to click one of my category it always shows all the products but i want to show filter wise category list if i click Smart Phone it will only show me smartphone category products. Here is my Models.Py: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @staticmethod def get_categories(): return Category.objects.all() class Brand(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name def get_brands(): return Brand.objects.all() class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') price = models.FloatField() @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_products_by_category(category_id): if category_id: return Product.objects.filter(category=category_id) else: return Product.get_all_products() Here Is my Views.py: from django.shortcuts import render from .models import * # Create your views here. def index(request): products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) Please help i am very confused here and also got stucked :( -
Django, how to modify output of a related model serizlizer?
I have a model which has several ForeignKeys: class Employee(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="staff", null=False, blank=False) user = models.ForeignKey(to=User, blank=False, null=False, on_delete=models.CASCADE) roles = models.ManyToManyField(to=Role, blank=False) How do I use a fields from Company and User in Employee model? I need them for __str__. -
How do I view my django site from other devices which are connected to the same network
I wanted to view my django site from another device. I ran this command py manage.py runserver 0.0.0.0:8888 Then I went to my phone web browser and entered this url (Network ip address):8888 It was searching for that url and a little while later the connection timed out. What do I do -
Django dynamically generated serializer
Is there a way how to dynamically generate a django rest framework serializer? Considering this: class BlogSerializer(serializers.ModelSerializer): class Meta: model = models.Blog fields = get_all_model_fields(models.Blog) class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = get_all_model_fields(models.Post) class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = get_all_model_fields(models.User) I am wondering if something like the following example could be possible: from django.apps import apps models = [model for model in apps.get_models()] for model in models: type(model.__name__+'Serializer',(serializers.ModelSerializer,),{ type("Meta",(),{ "model":model, "fields": get_all_model_fields(model) }) }) Or is there any other way how to generate DRF serializers because I have got a huge amount of models to serialize. -
Stripe Webhooks: Invoice.paid vs Checkout.Session.Completed
I use Stripes' webhooks and want to get notified, if the customer successfully "paid the bill". I came across two webhooks, which in my opinion both could do the job: Webhook "invoice.paid" - According to Stripe doc: Occurs whenever an invoice payment attempt succeeds or an invoice is marked as paid out-of-band. Webhook "checkout.session.completed" - According to Stripe doc: Occurs when a Checkout Session has been successfully completed. My questions are: I don't understand the second part of the "invoice.paid" webhook: "invoice is marked as paid out-of-band" -> What does "out-of-band" mean? Is this to be considered a successful payment? Regarding "checkout.session.complete" -> This can also occur, if payment fails - correct? Which webhooks shall I consider (or are there other webhooks) to see the status "customer paid the bill successfully"? What is more, I don't really know if disputes should be considered as successful payments or not: On one hand, I get a invoice.paid webhook, on the other hand, I get a charge.dispute.created webhook. geeezus... I appreciate your help! Thanks. -
How can I work on a django project in my external harddrive
I have an external drive from my old PC and I would like to continue working on some projects there, I have set up python but on my VSCode I keep getting "workspace contains pipfile but pipenv was not found". What's the solution to this? -
Using dictionary from Django view in .html Javascript loop (SyntaxError - unexpected token: ')
I'm working on a Django project, and when I try to load a dictionary using Javascript, I get SyntaxError - unexpected token: &#x27 In my .html file, I am using {{ customer_tabledata }} to import from my views. The problem is it's trying to load &#x27 and not the quotation mark. How can I convert from &#x27 to "? In my .html file: <script> let tableData = {{ customer_tabledata }}; function loadTableData(tableData) { const tableBody = document.getElementById('tableData'); let dataHTML = ''; for(let data of tableData) { dataHTML += `<tr><td>${data}</td></tr>` ; } tableBody.innerHTML = dataHTML; </script> In my views: customer_tabledata = {'site_1' : {'revenue' : 900 }, {'partner_share' : 450}, 'site_2 : {'revenue' : 1500 }, {'partner_share' : 750}} -
Custom navbar for each View
I try to do navbar for each View different. Can I code it better for example using href="{% url 'polls:detail' question.id %} ? Now I create navbar.html {% for name, link in navbar.items%} <li class="nav-item"> <a class="nav-link" href={{link}}>{{name}}</a> </li> {% endfor %} and Views class ArticleListView(generic.ListView): model = Article template_name = 'blog/article_list.html' context_object_name = 'articles' queryset = Article.objects.all() def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data() context['navbar'] = {"Main Page":"/blog/","create":"/blog/create"} return context class ArticleDetailView(generic.DetailView): template_name = 'blog/article_detail.html' context_object_name = 'article' queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data() context['navbar'] = { "Main Page": "/blog/", "create": "/blog/create", "edit": f"/blog/{Article.objects.get(id=self.object.id).id}/update", "delete": f"/blog/{Article.objects.get(id=self.object.id).id}/delete", } return context -
How would one go about making a file-sharing app in Django
How could I make a file sharing app in Django and Django-rest-framework? How would I start and what technologies would I use? -
Django+Apache: [wsgi:error] ModuleNotFoundError: No module named django_project1'
Launching my first Django application through Linode using Apache. Everything was going fine until I had to finalize the launch. When I try to access the IP of the site I am receiving a '500 Internal Server Error'. Based on the error log I am seeing there is an wsgi error. This error states that there is a module not found 'django_project1' (this is the name of my project). I have seen many examples of this error however there doesn't seem to be a comprehensive explanation of why its occurring and not one example has the same solution. Any feedback is appreciated. Below I have included my: Error Log [Tue Nov 10 19:22:25.784084 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 991, in _find_and_load [Tue Nov 10 19:22:25.784090 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked [Tue Nov 10 19:22:25.784094 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [Tue Nov 10 19:22:25.784099 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 1014, in _gcd_import [Tue Nov 10 19:22:25.784104 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 991, in _find_and_load [Tue … -
A way to copy files from one Caprover image to another
I uploaded a website using caprover and django and works well. Everything works fine, but I noticed whenever I updated the project user files get lost, although everything gets updated quite well. I understand caprover is build on top of nginx and docker, but I'm new to them. Every time I update caprover it builds a new image( I guess docker image) and this makes user images to disappear (I guess left in the previous image) is there a way to copy those files? Thanks in advance -
I get AuthFailed after trying to social login in my Django app using linked in
I have a web application that has profiles for alumnus, on each profile there are some information like work I want to let the user be able to connect to his linkedin profile so he can get information like work so I started with social-auth-core library in python to get information from the user but after the linkedin login pop ups and I click on allow I keep receiving this error AuthFailed at /social-auth/complete/linkedin-oauth2/ Authentication failed: HTTPSConnectionPool(host='www.linkedin.com', port=443): Max retries exceeded with url: /oauth/v2/accessToken?grant_type=authorization_code&code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&client_id=77hqh7fm6bhtar&client_secret=wYy0wVVhUIuRQCPF&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fsocial-auth%2Fcomplete%2Flinkedin-oauth2%2F (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05204DA8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) Request Method: GET Request URL: http://127.0.0.1:8000/social-auth/complete/linkedin-oauth2/?code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&state=9oPFIPwkeUI1uzEjmzIq2sLA8y11vf2a Django Version: 2.2.7 Exception Type: AuthFailed Exception Value: Authentication failed: HTTPSConnectionPool(host='www.linkedin.com', port=443): Max retries exceeded with url: /oauth/v2/accessToken?grant_type=authorization_code&code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&client_id=77hqh7fm6bhtar&client_secret=wYy0wVVhUIuRQCPF&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fsocial-auth%2Fcomplete%2Flinkedin-oauth2%2F (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05204DA8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) Exception Location: C:\Users\lebda\.virtualenvs\final-thesis-HeIACWIb\lib\site-packages\social_core\backends\base.py in request, line 236 Python Executable: C:\Users\lebda\.virtualenvs\final-thesis-HeIACWIb\Scripts\python.exe Python Version: 3.8.5 Python Path: ['E:\\final-thesis', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb\\Scripts\\python38.zip', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb\\lib\\site-packages'] Server time: Thu, 12 Nov 2020 17:22:55 +0000 and I don't understand where is the problem my project … -
CSRF token missing or incorrect in django Sign up page
i have a problem with my sign up page, after completing the form and clicking submit button am receiving an error: Access denied (403) CSRF verification failed. The request was aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, … -
Django sites redirect if Site matching query does not exist
I am using the Django "sites" framework and I am having problems handling a DoesNotExist exception it raises when I try to "access" a Site not currently in my database. In my settings.py I am not specifying any SITE_ID. Rather, I am letting Django figure it out automatically by looking at requests. Some of the domains currently in my database are: www.app.com (International version of the app), us.app.com (American version of the app), es.app.com (Spanish version of the app), ... With this being the state of my database, the problem arises when I try to access, say, about.app.com. Since about.app.com is not in my database I get the following DoesNotExist error... Site matching query does not exist. Desired behavior Instead of throwing an exception, I would like Django to redirect all invalid sites to www.app.com. Question Where could I handle that DoesNotExist exception and how could I redirect the user to www.app.com if the exception were thrown?