Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't call custom django commands extwith call_command
This is probably a really basic question but I can't find the answer anywhere for some reason. I created a custom command which I can call from the command line with python manage.py custom_command. I want to run it from elsewhere but don't know how to do so. I have added pages to my INSTALLED_APPS in settings.py. This question: Django custom command works on command line, but not call_command is very similar but I'm not sure what the answer means and I think it's unrelated. My file structure is : ├── custom_script │ ├── script.py │ ├── __init__.py ├── project │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── pages │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── management │ │ ├── commands │ │ │ ├── __init__.py │ │ │ └── custom_command.py │ │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py content of script.py from django.core.management import call_command call_command('custom_command', 'hi') content of custom_command.py from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('message', type=str) def handle(self, *args, **options): print('it works') I want … -
APIClient vs RequestFactory (with coding example)
I am new to django, and i tried something this: from rest_framework.test import APITestCase, APIClient, APIRequestFactory from django.contrib.auth import get_user_model client = APIClient() User = get_user_model() factory = APIRequestFactory() class UserLoginTestCase(APITestCase): def SetUp(self): user = User.objects.create(email="test@gmail.com", password=utils.make_password("test@12345"), full_name="The User") user.save() def test_user_login(self): valid_data = {"email": "test@gmail.com", "password": "test@12345"} url = reverse('api:login') response = self.client.post(url, data=valid_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) Is this possible that can i use "APIRequestFactory" for above code? Please also tell how to use "APIClient" in more good way. -
How do I solve psycopg2 error when trying to run in local server?
So I have deployed my project using AWS EC2. I was trying to run the application in my local server as well, for testing. But then I got the error below. Traceback (most recent call last): File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\user\Envs\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError I have this in settings.py import os from .local_settings import PG_HOST DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME' : 'myDB', 'USER' : 'Manager', 'PASSWORD' : '###password###', 'HOST' : PG_HOST, 'PORT' : '', } } And this in local_settings.py. (NOT used in the AWS server) PG_HOST = '' What do you think is wrong? Thank you very much in advance. -
django valueError/ at /login/
The view XXX.views.loginPage didn't return an HttpResponse object. It returned None instead. i am having a value error on my redirect function below. i already refer some answer that other user ask on same error. but it still not working. I really need your help. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login def loginPage(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): user = form.get_user() login(request, user) if 'next' in request.POST: return redirect(request.POST.get('next')) else: return redirect('index.html') else: form = AuthenticationForm() return render(request, 'loginPage', {'form': form}) urls.py from django.urls import path from . import views from .views import redirect_view urlpatterns = [ path('', views.Index, name='index.html'), path('index/', views.Index), path('register/', views.register), path('login/', views.loginPage), path('/redirect/', redirect_view) ] -
I don't know how to which relationship to use between these 6 models Order, Item , OrderItem, SihippingAddress ,Payment and Coupon in django models.py
So these are the elements i want to store in these models. In Item: title, price , discount_price , label , category , slug, description In OrderItem : user , ordered , quantity , item In Order : user, items, create_date , order_date , ordered, shipping_address, payment, coupon In ShippingAddress : street_address , country , zip , user In Payment : stripe_charge_id , amount , timestamps In Coupon : code, amount As you have seen I want to create relationship between Order, OrderItem and Item, also in Order I want to refer to 3 models Payment, ShippingAddress and Coupon but I don't know which relationship to use between these models. -
python manage.py run server is not working
need help please "...can't open file 'manage.py': [Errno 2] No such file or directory" Im working on windows. I am trying to run the server but I keep getting this error. I tried every solution that is posted but no luck. what's the solution please ? thank you -
attributes field is not resolved and always returns null
I am practicing through saleor's product models and schema to be familiar on ariadne where I could get the list of products but I could not fetch the attributes associated with the product. Their schema is as follow schema.graphql type Product implements Node { id: ID!, productType: ProductType! name: String! slug: String! description: String! category: Category! price: Money attributes: [SelectedAttribute] variants: [ProductVariant] images: [ProductImage] collections: [Collection] } type SelectedAttribute { attribute: Attribute values: [AttributeValue] } type Attribute implements Node { id: ID! productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection! productVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection! inputType: AttributeInputTypeEnum name: String slug: String values: [AttributeValue] valueRequired: Boolean! } type AttributeValue implements Node { id: ID! name: String slug: String inputType: AttributeInputTypeEnum } resolvers.py query = QueryType() @query.field('products') @convert_kwargs_to_snake_case def resolve_products(obj, info, **args): products = models.Product.objects.all() if 'sort_by' not in args: args['sort_by'] = { 'field': category_sorting_field.values['NAME'], 'direction': category_direction.values['DESC'] } return connection_from_queryset_slice(products, args) product = ObjectType('Product') @product.field('productType') def resolve_product_type(obj, info): return models.ProductType.objects.get(products__id=obj.id) @product.field('attributes') def resolve_attributes(obj, info): print('obj', obj.product_type.product_attributes.all()) return obj.product_type.product_attributes.all() Here, the product type is resolved using @product.field('productType') but not for attributes. I keep getting "attributes": [ { "attribute": null }, { "attribute": null } ] This is what … -
how can i POST data from ant design form into Django Backed?
i trying to post data from ant design React.js into Python Django rest frame work. so I am using method OnFinish to send data, but its not working. MY big problem is , i don't know how can i Introduction Data i want to send them data from Form , by using React-redux or something else way , so please Help me . #react.js Form: import React, { Component } from "react"; import { Form, Input, Button, PageHeader, Select, DatePicker, message, } from "antd"; import "antd/dist/antd.css"; import { connect } from "react-redux"; import axios from "axios"; // defualt setting for django axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; // from layout setting const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 8, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; // end fform layout setting // const onFinish = (values) => { // console.log(values); // axios.post("http://127.0.0.1:8000/api/create/", { // title: values.title, // manager: values.manager, // }); // }; // const title = event.target.elements.title.value; // const manager = … -
Can anyone show me some example project with details for the live chat on the website in Python, Flask?
I am going to add a live chat section for my website using flask or Django can someone show me some links or instruction which can direct me to the target? -
I'm calling another page on click button in Django Framework but it is not working
I'm trying to navigate to the result.htm from index.html on click button on "RUN" but the below code is not working to navigate to result.htm. index.html <ol> <li> <form method="POST"> {% csrf_token %} <input class="bg-yellow text-white" id="RUN" href={% url 'result' %} value="RUN" name="runModel" type="submit" onclick="sendValuesToBack()"> </form> </li> <input type="image" onclick="openSettingForm()" alt="submit" data-modal-target="#modal" class="img" style="width:80px;height:70px;" src="{% static 'AutoGenerateML/assets/img/Setting.jpg'%}"> </ol> result.html <!DOCTYPE html> <html> <head> </head> <body> <h1>Hello Result Page</h1> </body> </html> urls.py path('result/',views.result,name="result"), View.py def result(request): return render(request,"result.htm") -
Why is python-dotenv not working properly in Django project
I'm trying to send django form data via email using emails module and python-dotenv for environment variables. The .env file is along settings.py and it's loading the envs in settings.py accordingly, but I try this in views.py where I'm trying to set the aws ses credentials as environment variables, and everything seems to work, but the email is not sent, but then I re-enter the aws ses creds in plain back into views.py and everything works great again. Any ideas why with envs the email is not sent? Code in views.py import os import emails from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv(), verbose=True) ... part of code with creds: ... try: # Send the email r = message.send( to= os.environ.get("RECEIPIENT"), smtp={ "host": os.environ.get("HOST"), "port": 587, "timeout": 5, "user": os.environ.get("USER"), "password": os.environ.get("PASSWORD"), "tls": True, }, ) except BadHeaderError: return HttpResponse(f"response{r.status_code == 250}") I also tried this following the example in the official python-dotenv site using os.getenv(): ... try: # Send the email r = message.send( to=os.getenv("RECEIPIENT"), smtp={ "host": os.getenv("HOST"), "port": 587, "timeout": 5, "user": os.getenv("USER"), "password": os.environ.get("PASSWORD"), "tls": True, }, ) except BadHeaderError: return HttpResponse(f"response{r.status_code == 250}") -
Moving a Django Foreign Key to another model while preserving data?
I have a Django application where I have a basic user model and user profile model. class Office(models.Model): name = models.CharField() class User(models.Model): email = models.EmailField() offices = models.ManyToManyField(Office) class Profile(models.Model): user = models.OneToOneField(User) Each user has a profile and can be assigned to many different offices. What I am looking to do is have it so that a User can have many profiles, but the profiles can be assigned to different offices. At the moment, this isn't possible as the Office field is assigned at the User level and not the Profile level. I envision 2 ways to solve this: Find some way to move the offices field over to the Profile field. Create a new model something along the lines of ProfileNoUser that has a foreign key to the user model as well as have an offices foreign key within it. Which option do you think is best? If #1, how can I do that? -
Django - How to declare variable in template depending on condition
I'm looking to do something really basic but against all odds it seems like it's not as easy as it should be. I need to transcribe the following into django template syntax : p = '&' if '?' in request.path else '?' All I found so far to create variable is the with statement but I can't get what I need : {% if '?' in request.path %} {% with p='&' %}{% endwith %} {% else %} {% with p='?' %}{% endwith %} {% endif %} p needs to be available in all the template, and since I use a condition here, I can't afford to duplicate the html structure twice to put it inside the with statement. It has to be an easy way to do this that I'm missing... -
How to deploy a Django and React web application
Hi I've never deployed a full stack application, how can I deploy a django application with react in it onto the web? Do I need to seperate the frontend from backend? Do I need a cloud and virtual machine or just a hosting plan from popular hosting companies? -
Django can i reverse a parameterized url without passing any arguments?
app_name = 'app_name' path('url/<uuid:uuid>',someview.as_view(),name='somename') def get_url(): return reverse('app_name:somename',args=None) I want get_url to return 'url/' Is it possible? -
PasswordResetView in Django Allauth throwing invalid lookup error
I'm trying to override the PasswordResetView template. I've done so successfully by just creating a directory called account and placing password_reset.html My url looks liek this: url(r'^recover/$', PasswordResetView.as_view(), name='account_reset_password') Everything works fine, however, when I submit an email to have the password reset, I get the following error: Related Field got invalid lookup: is_active I'm not sure why this is happening. I'm using allauth and also Django's auth but for this particular instance i'm using the allauth views. -
Looking for help to make npm/pdfjs-dist work with Webpack and Django
I've been trying for a few hours replacing a link-based pdf.js with an npm install of pdfjs-dist, since I noticed that my links were not meant to be used as cdns and could become unstable as described here. I could not find much documentation on how to make that work other than a few examples, and when Webpack is involved they are mostly with React, while I am simply using ES6 in a Django framework (static compiling on the desired django directory, without using the webpack-plugin.) After exchanging several messages with one of the guys that work on pdf.js it seemed that my compiling errors were probably due to how Webpack handles internally the library. Here's what I am seeing: WARNING in ./node_modules/worker-loader/dist/index.js Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileAsyncWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist' @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js WARNING in ./node_modules/worker-loader/dist/index.js Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist' @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js ERROR in (webpack)/lib/node/NodeTargetPlugin.js Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node' @ (webpack)/lib/node/NodeTargetPlugin.js 11:1-18 @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js Child HtmlWebpackCompiler: 1 asset Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0 [./node_modules/html-webpack-plugin/lib/loader.js!./src/src-select.html] 4.57 KiB … -
Django Admin - How to embed View from Foreign Key
I have a simple relationship with a Question that contains a Label. class Label(models.Model): text = models.CharField(max_length=200) subtext = models.CharField(max_length=50) class Question(models.Model): title = models.ForeignKey(Label, on_delete=models.CASCADE) question = models.CharField(max_length=200) If I open up the admin panel to edit a Label, it shows 2 text fields to update the text and subtext. However, if I attempt to edit the Question, it'll be a dropdown list of all Labels. What is the best way to make it straightforward to edit the Question and it's child Label? In the example above, I would want all 3 text fields ( text, subtext and question ) in the same view and editing them will update the correct tables in the database. -
Django order_by('-id') is extremely slow
I have a model Line with a group Foreign key. I want to get the last 30 Lines under a certain id, within in a single group. To do that, I use this query: Line.objects.filter(group_id=8460, id__lt=10333449).order_by("-id")[:30] My problem is that this query takes 1.5s to get executed, whereas these two are done almost instantly (<30ms): Without the ordering: Line.objects.filter(group_id=8460, id__lt=10333449)[:30] Without the id__lt: Line.objects.filter(group_id=8460).order_by("-id")[:30] For info, I have 10M+ lines in total and about 13k lines in this group alone. How can I make the query faster when both using id__lt and order_by('-id')? -
How to joins multiple tables in Django
** I just need one more table join in my query ** I want to get sales of logged-in users with order detail and shipping address. I tried this queries but not getting desired results. orderitems = OrderItem.objects.filter( product__user=request.user, order__complete=1).order_by('-date_orderd') Now i want to get also address, city and state from the Shippingaddress model. I attached the models below. this is my current result. My models: Order Model: class Order(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) date_orderd = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) # product = models.ManyToManyField(OrderItem) def __str__(self): return str(self.id) Order items Model: class OrderItem(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_orderd = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) price = models.FloatField(blank=True, null=True) def __str__(self): return str(self.product) Shipping Address Model: class ShippingAddress(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=150) address = models.CharField(max_length=150) city = models.CharField(max_length=150) state = models.CharField(max_length=150) zipcode = models.CharField(max_length=150) date_orderd = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address -
Django Display multipe categories on page
I have this model.py file: class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title class Video(models.Model): title = models.CharField(max_length=128) description = models.TextField(default='') thumbnail = models.ImageField(default='default_thumbnail.png', upload_to='thumbnails') date_posted = models.DateTimeField(default=timezone.now) category = models.ForeignKey( Category, on_delete=models.SET_DEFAULT, #null=True, default=1, verbose_name="Category" ) def __str__(self): return self.title Each video has its own category and I want to display on one page a given number of films in each category. Currently, I'm only showing the last 5 videos on the page: def home(request): latest_videos = Video.objects.all().order_by('-date_posted')[:5] categories = Category.objects.all() context = { 'latest_videos': latest_videos, #'categories': categories, } return render(request, 'videos/home.html', context) I have no idea how to display a given number of movies in each category. I tried to send all the videos and query them on the template, but this is probably impossible. Any ideas? I'm still learning Django, but this time I found a problem I can't solve all day. Thanks -
Что надо знать Backend разработчику?
Я начал изучать языка программирования Python и двинулсч глубже и изучал фреймворков и наткнулся на Django и изучаю его и он мне понравился . Суть вопроса в том что , можно ли с помощью Django произвести или работать с Backend ? У меня просто путаница знаком с SQL . -
How to run Django and Node Server at the same time
I'll try to be as concise as possible. Here's what I've done so far: I processed some NLP data using textblob, tweepy, etc. I serialized the data using Django REST API. I'm using axios to do a GET request from my Django server and display on my express app (not using a fancy JS framework) Things seems to be going ok, except I'm trying to figure out if running two servers (Django and Express) is the most efficient way of running this app. Is there a way to simplify this? eventually I intend to put this on Github and allow people to view the application on their own machine. Any tips or links would be greatly appreciated!!! Kind regards. -
Django REST Framework Testing and Token Authentication
I have a REST API working and accessible via Postman with token authentication. I'm trying now to write tests for the API. This test case set up will work fine, though it returns a 401 status (as expected): class ModelCRUDTests(TestCase): def setUp(self): self.thing = TestThingFactory.create() self.client = APIClient() self.response = self.client.get( reverse('appname:things-detail', kwargs={'pk': self.thing.pk}), ) When I add credentials, I get an error from the GET request (debugging shows that the authentication is stored in the client correctly). Modified code: class ModelCRUDTests(TestCase): def setUp(self): self.thing = TestThingFactory.create() self.admin_user = TestUserFactory(is_staff=True) self.token = Token.objects.get_or_create(user=self.admin_user) self.client = APIClient() self.client.credentials(HTTP_AUTHORIZATION='Token '+self.token[0].key) self.response = self.client.get( reverse('appname:things-detail', kwargs={'pk': self.thing.pk}), ) Stack trace: Traceback (most recent call last): File ".../venv2/lib/python3.8/site-packages/rest_framework/relations.py", line 393, in to_representation url = self.get_url(value, self.view_name, request, format) File ".../venv2/lib/python3.8/site-packages/rest_framework/relations.py", line 331, in get_url return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File ".../venv2/lib/python3.8/site-packages/rest_framework/reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File ".../venv2/lib/python3.8/site-packages/rest_framework/reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File ".../venv2/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File ".../venv2/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'thing-detail' not found. 'thing-detail' is not a valid view function or pattern name. During handling of the … -
My form doesn't add data to database - Django
I've just started my journey with django. Form is displayed on page, data typing works well, but data doesnt go to database. Form is about registation system on page. models.py: from django.db import models from datetime import date class Users(models.Model): login = models.CharField(max_length=30) password = models.CharField(max_length=30) mail = models.CharField(max_length=40) create_date = models.DateTimeField(default = date.today(), blank=True) forms.py: from django import forms from .models import Users class Register(forms.ModelForm): password = forms.CharField(max_length=32, min_length = 8, widget=forms.PasswordInput) login = forms.CharField(min_length=4, max_length=30) mail = forms.EmailField() class Meta: model = Users fields = ['login','password','mail'] register.html: {% extends 'base.html' %} {% block content %} <div id="form-user"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SAVE" /> </form> </div> {% endblock %} views.py: from django.shortcuts import render from .forms import Register from .models import Users def register(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save(commit = True) form = Register() form = Register() return render(request, "register.html", {'form': form})