Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx doesn't proxy websocket
I'm trying to install django_channels. I pass the tutorial, and everything works except of essential - websocket doesn't work when I try it by external browser. Daphne is working, checked with wscat --connect ws://localhost:8000/ws/chat/room/ so local works. The only difference between tutorial and my is in asgi.py: tutorial asgi.py: import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) my asgi.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') import django django.setup() from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ "http" : get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) I have to move from channels.auth import AuthMiddleWareStack lower and have to add import django; django.setup() because of errors - (NO INSTALLED_APPS and no Apps). I know that nginx got connection because /var/log/asgi.log reacts: django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <module 'chat.urls' from './chat/urls.py'> (None:None) 'chat/'> 2021-01-27 00:44:20,491 WARNING Not Found: /ws/chat/room/ nginx/sites-enabled/mysite.conf # map $http_upgrade $connection_upgrade { default upgrade; '' close; } # the upstream component nginx needs to connect to upstream django-mysite { server unix:///home/mysite/mysite.sock; # for a file … -
Django default values depend on selected value
I am working on a small Transport planner app. I have a Model as follows. I have four widgets to select, but I want to select only the store_name field and with this selection I want to set default values for the other three fields. It would be practical to set the default value for all with only one selection, because most of the cases I use this default value. The default values are in the Store Model. Do you have any idea how can I do it? Thank you in advance! class StoreNumber(models.Model): number = models.CharField(max_length=10, default=None) def __str__(self): return str(self.number) class TransportCompany(models.Model): name = models.CharField(max_length=100, default=None) def __str__(self): return self.name class Store(models.Model): name = models.CharField(max_length=100, default=None) default_store_number = models.CharField(max_length=100, default=None) default_company = models.ForeignKey(TransportCompany, null=True, on_delete=models.SET_NULL) default_expedition_time = models.TimeField(default=None) def __str__(self): return str(self.name) class Transport(models.Model): store_name = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) store_number = models.ForeignKey(StoreNumber, null=True, on_delete=models.SET_NULL) transport_company = models.ForeignKey(TransportCompany, null=True, on_delete=models.SET_NULL) expedition_time = models.TimeField(default=None) def __str__(self): return str(self.expedition_time) + ' | ' + str(self.store_name) + ' | ' + str(self.store_number) def get_absolute_url(self): return reverse('transportplanner') The form.py: store_choices = Store.objects.all().values_list('name','name') store_choice_list = [] for item in store_choices: store_choice_list.append(item) store_number_choices = StoreNumber.objects.all().values_list('number','number') store_number_choice_list = [] for item in store_number_choices: store_number_choice_list.append(item) company_choices = … -
Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardOneToOneDescriptor object
Anyone knows what the most likely cause? Exception Type: TypeError Exception Value: Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardOneToOneDescriptor object at 0x000002972F06E6D0>. The above exception (int() argument must be a string, a bytes-like object or a number, not 'ForwardOneToOneDescriptor') was the direct cause of the following exception: ''' posts = Post.objects.filter(authPost=user)''' -
Django Channels setup with Django 2.2 and channels 3.03
I know there are other questions like this but none of those solutions seem to be working. I added the version numbers of each framework as that might be a factor. I have the tutorial on channels site (https://channels.readthedocs.io/en/stable/tutorial/part_2.html) working locally but when I move over to the production server (Apache) it fails with the following error on daphne: 2021-01-26 23:26:15,994 ERROR Exception inside application: No route found for path 'ws/chat/lobby/'. Traceback (most recent call last): File "/opt/venv/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/opt/venv/lib/python3.6/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/opt/venv/lib/python3.6/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/opt/venv/lib/python3.6/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/opt/venv/lib/python3.6/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/opt/venv/lib/python3.6/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat/lobby/'. my asgi.py file: import os import django from channels.routing import get_default_application # Fetch Django ASGI application early to ensure AppRegistry is populated # before importing consumers and AuthMiddlewareStack that may import ORM # models. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") django.setup() application = get_default_application() my settings.py: ASGI_APPLICATION = "myapp.routing.application" my … -
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f5b25bc24e0>: Failed to establish a new connection: [Errno 111] ',))
I have created a django project on my windows computer and uploaded that on github and then i clone my project on my linux computer , everything is working fine. I mean user is creating, sending emails verifications , all is fine expect the kyc form, When i fill all fields and click on submit button then i see the following traceback. Traceback (most recent call last): File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connection.py", line 170, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/util/connection.py", line 96, in create_connection raise err File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/util/connection.py", line 86, in create_connection sock.connect(sa) During handling of the above exception ([Errno 111] Connection refused), another exception occurred: File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 706, in urlopen chunked=chunked, File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.6/http/client.py", line 1281, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1327, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1276, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1042, in _send_output self.send(msg) File "/usr/lib/python3.6/http/client.py", line 980, in send self.connect() File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connection.py", line 200, in connect conn = self._new_conn() File "/home/hamza/Mydjangoproject/dotescrow/dotescrow_main/dotescrowenv/lib/python3.6/site-packages/urllib3/connection.py", line 182, in _new_conn self, "Failed to establish a new connection: %s" % e During handling … -
GeoDjango - DataSource Feature Type Error
I'm trying to import geoJSON into a geodjango database. In the below example, the layer.field_types method returns the correct datatypes. However, when looping through the features the elevation field is converted from a float to a int. >>> from django.contrib.gis.gdal import DataSource >>> a = '{"type": "FeatureCollection","name": "minContours","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::6527" } },"features": [{ "type": "Feature", "properties": { "ID": 2, "Elevation": 41.5 }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 589193.655952385859564, 768634.955786595470272, 41.5 ], [ 589193.4616099999985, 768634.944451080053113, 41.5 ], [ 589192.966033526696265, 768635.120235103997402, 41.5 ] ] ] } }]}' >>> ds = DataSource(a) >>> lyr = ds[0] >>> print(lyr.field_types) >>> features = [f for f in lyr] >>> print([type(features[0]['ID']),type(features[0]['Elevation'])]) [<class 'django.contrib.gis.gdal.field.OFTInteger'>, <class 'django.contrib.gis.gdal.field.OFTReal'>] [<class 'django.contrib.gis.gdal.field.OFTInteger'>, <class 'django.contrib.gis.gdal.field.OFTInteger'>] Is it fair to assume this is some sort of geojson driver issue that cannot be fixed in python? Other file types like .shp work as expected. -
Access Twitter API within Celery Task
I have a long function that I am passing on to Celery but it requires access to the Twitter API through Oauth. I have user auth process all sorted just can't add it to the function as request is not defined in Celery. This is what I have at the moment... views.py def like(request): liker.delay() return render(request, "home.html") Celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoTweetLiker.settings') app = Celery('AutoTweetLiker') app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='redis://:pf133827b9d431528f1158e82e1b04a8bda7b3555544882d8f0e3b963bd0f85a1@ec2-18-207-19-49.compute-1.amazonaws.com:13609', CELERY_RESULT_BACKEND='******') app.autodiscover_tasks() @app.task(bind=True) def liker(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) ....The rest of my function using Twitter API... Now the function works if I put in my own access_key and access_secret manually as a variable but this doesn't help other users authorise my app and then use the function. Any ideas how I can get this to work? -
Connecting Django to PostgreSQL - Error loading psycopg2 module despite install
Very aware there are similar questions out there. I have had a sift through answers but nothing seems to be working... I'll explain from the beginning so hopefully someone can help. I am using python 3.8 on mac. As title says, trying to connect a new django project to a postgresql database. I have installed the postgresql app (as well as pgadmin 4 for monitoring). I've updated my settings.py file as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'psql1', 'USER': 'Pete', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } I've then gone into terminal to run python manage.py migrate to make the initial migrations, but receive the following: Error loading psycopg2 module: No module named 'psycopg2'. Obviously, I then followed the instructions online and used pip install psycopg2-binary, successfully installing psycopg2-binary in: /Users/Pete/Library/Python/2.7/lib/python/site-packages (2.8.6) and also pip3 install psycopg2-binary, successfully installing psycopg2-binary in: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (2.8.6) But I still receive the SAME error above. Really quite stuck and would greatly appreciate any help! Thanks. -
Has anyone successfully used Reverse with namespaces, rest_framework and host patterns?
I have literally been trying to solve/ignore this issue for months now but I cannot test properly nor move on until I do. I've tried using namespaces and hard-coding but I still get the same error. 'django.urls.exceptions.NoReverseMatch: 'users' is not a registered namespace' If you can see a solution that I cannot, please assist me. I have attached the url files and test that is giving me the error. I have tried changing the app_name, namespace, url name; adding and removing said variables...same issue no matter what. I'm stumped 😩. Thank you in advance! Test: from rest_framework.test import APITestCase from django.urls import reverse from users.models import Feedback class TestFeedbackAPI(APITestCase): def test_post_request_can_create_new_entity(self): data = { 'subject': 'Test', 'message': 'Testing on these hoes', } self.client.post(reverse('users:post_user_feedback'), data=data) self.assertEqual(Feedback.objects.count(), 1) App named Users urls: from django.urls import path from .views import ProfileDetail, SettingsDetail, FeedbackDetail app_name = 'users' urlpatterns = [ # path("create/", views.UserCreate.as_view()), # Sign up view, POST path('profile/', ProfileDetail.as_view(), name='get_user_profile'), path('settings/', SettingsDetail.as_view(), name='get_user_settings'), path('support/', FeedbackDetail.as_view(), name='post_user_feedback'), ] Api urls: """busTracker API URL Configuration""" from django.urls import include, path urlpatterns = [ path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.authtoken")), path('', include('core.urls', namespace='core')), path('', include('users.urls', namespace='users')), ] Host file: from django.conf import settings from django_hosts import patterns, host … -
TemplateDoesNotExist: polls/question_detail.html Django tutorial
Studied the tutorial up to the seventh part. Everything was fine until I decided to launch my application. After launch, I added a multiple choice question. The error occurs after I click on a question to answer it. Long searches for an answer did not bring any results. Please help. I get this error: TemplateDoesNotExist at /polls/1/ polls/question_detail.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 4.0.dev20210118085850 Exception Type: TemplateDoesNotExist Exception Value: polls/question_detail.html Exception Location: c:\users\mrand\django\django\template\loader.py, line 47, in select_template Python Executable: C:\Users\mrand\Anaconda3\envs\mysite\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\mrand\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages', 'c:\\users\\mrand\\django', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\Pythonwin'] Server time: Wed, 27 Jan 2021 01:15:15 +0300 Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 4.0.dev20210118085850 Python Version: 3.8.6 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\mrand\mysite\templates\polls\question_detail.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\mrand\mysite\polls\templates\polls\question_detail.html (Source does not exist) * django.template.loaders.app_directories.Loader: c:\users\mrand\django\django\contrib\admin\templates\polls\question_detail.html (Source does not exist) * django.template.loaders.app_directories.Loader: c:\users\mrand\django\django\contrib\auth\templates\polls\question_detail.html (Source does not exist) Traceback (most recent call last): File "c:\users\mrand\django\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\users\mrand\django\django\core\handlers\base.py", line 204, in _get_response … -
Store JSON data in Django model
I am trying to send data from sensor to Django server using ESP8266. I sent the data in JSON format and used this code to convert it to python Dict but I can't store the sensors' values in the database, so any idea how to do that ? @csrf_exempt def index(request): print("\n") data = json.loads(request.body) type = data.get("SensorType", None) reading = data.get("Reading", None) print(type) print(reading) return HttpResponse("Hello") I made a sensortype row with charfield input and reading with integarfield input -
Django template cannot see model object
models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=256) author = models.CharField(max_length=256) coverphoto_link = models.CharField(max_length=1000, blank=True) text = models.TextField() photo_link = models.CharField(max_length=1000,blank=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("basic_app:article", kwargs = {'pk':self.pk}) class Comment(models.Model): post = models.ForeignKey(Post,related_name='comments', on_delete = models.CASCADE) name = models.CharField(max_length=300) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name article.html {% include 'base1.html' %} {% load static %} <br> <div class="container" id='container_article'> <div class="container2"> <h1>{{ article_detail.title }}</h1> <p class="author_detail" style="color: rgb(0, 4, 255);">{{ article_detail.author }} | {{article_detail.date }}</p> <br> <img id="photo" src="{{ article_detail.photo_link }}"> </div> <p id="articletext">{{ article_detail.text }}</p> <br> <br> <hr> <!--- HERE ---> <h2>Comments...</h2> {% if not post.comments.all %} No comments yet...<a href="#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} - {{ comment.date_added }}</strong> <br> {{ comment.body }} <br> {% endfor %} <hr> {% endif %} </div> {% include 'footer.html' %} THe main problem is that I created comments at the admin secction, all good, but the page is still displaying "No comments yet...".See the <!--- HERE ---> part, there is the problem.I also registered the app and the model at admin.py. -
How to get Postgres (.sql) file generated by Django>
I am developing a website with Django and I connected Django to Postgres. Now I want to view the Postgres SQL generated by Django but I don't seem to find it. I know an SQL developer who wants to have a look at how the database is and I replied that I can absolutely get him the SQL file and I don't know how to, I've searched a lot and ended up asking here. -
Unable to register in a self hosted taiga.io docker instance; redis ConnectionError 99
I'm trying to spin up a taiga.io instance from https://github.com/taigaio/docker-taiga-5 but whenever I try to register, I have this error on my server: server_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/task.py", line 570, in apply_async server_1 | **options server_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/base.py", line 755, in send_task server_1 | self.backend.on_task_call(P, task_id) server_1 | File "/usr/local/lib/python3.7/site-packages/celery/backends/redis.py", line 294, in on_task_call server_1 | self.result_consumer.consume_from(task_id) server_1 | File "/usr/local/lib/python3.7/site-packages/celery/backends/redis.py", line 135, in consume_from server_1 | return self.start(task_id) server_1 | File "/usr/local/lib/python3.7/site-packages/celery/backends/redis.py", line 114, in start server_1 | self._consume_from(initial_task_id) server_1 | File "/usr/local/lib/python3.7/site-packages/celery/backends/redis.py", line 142, in _consume_from server_1 | self._pubsub.subscribe(key) server_1 | File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 2229, in subscribe server_1 | ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels)) server_1 | File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 2161, in execute_command server_1 | self._execute(connection, connection.send_command, *args) server_1 | File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 2172, in _execute server_1 | connection.connect() server_1 | File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 442, in connect server_1 | raise ConnectionError(self._error_message(e)) server_1 | redis.exceptions.ConnectionError: Error 99 connecting to localhost:6379. Address not available. There is only this line regarding celery in the settings.py file: CELERY_ENABLED = True And there is strangely no redis service in the compose file. I don't really know in what direction to search... the README regarding a Docker setup doesn't seem to fully match the docker setup … -
Django OSError dont know how to resolve this error
File "C:\Users\Newto\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "C:\Users\Newto\AppData\Local\Programs\Python\Python39\lib\pathlib.py", line 1204, in resolve s = self._flavour.resolve(self, strict=strict) File "C:\Users\Newto\AppData\Local\Programs\Python\Python39\lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' -
Django-summernote How can I make it work based on model form?
If you want to fix your relationship this is what you should be views What I did is based on this : https://github.com/summernote/django-summernote But it doesn't work. from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from blog.models import Category, Comment, Post from .forms import PostForm # Create your views here. class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm fields = ['category','title', 'content','image','status','excerpt','slug'] template_name = 'crud/new_post.html' # form_class = PostCreateForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) crud/new_post.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form layout="horizontal" size="small" label_class="form-label col-md-3" %} <div class="row"> <div class="col-12 text-center"> {% buttons %} <button type="submit" class="form-button btn btn-success"> Submit </button> {% endbuttons %} </div> </div> </form> -
How to create a model with a field that contains the unique values from a field in another model?
Using django 3.1.3 I have a model (Item) that holds all items submitted by users. All of these items are grouped into user-defined categories. Each record contains the item name and the category name. What I want to do is create a second model (Category) that will have two fields: category: populated with the unique values from the category field in (Item include: A boolean that indicates if 'category' should be included So lets say that model (Item) has the following unique categories: 'Clothes', 'Groceries', 'Chairs'. I want (Category) > category to contain one record for each of those unique values. How can I structure model (Category) to accomplish this? Here's the relevant portion of model (Item): class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) include = models.BooleanField(default=False) quantity = models.PositiveIntegerField(default=0) category = models.CharField(max_length=20) item = models.CharField(max_length=50) And here's what I have for (Category): class Category(models.Model): include = models.BooleanField(default=True) category = ???? -
How to pass form_class data into model objects create in Django?
I want to create article form in Django. The code below getting Error FileModel.post" must be a "Article" instance. because i want to create multiple file related article instances which is coming from forgnekey. i need to pass example post=form.instances when i submit form data but i don't understand how can i pass FileModel.objects.create(post=self.form_class, file=f)? I would be grateful for any help. views.py class CreateView(CreateView): form_class = FileForm template_name = 'create.html' success_url = '/' success_message = "New story has been created successfully" def form_valid(self, form): form.instance.author = self.request.user for f in self.request.FILES.getlist('file'): FileModel.objects.create(post=self.form_class, file=f) # Error is here! return super().form_valid(form) -
Is it possible to fetch data and plot it to graph from REST API using only Django?
Because I have a chart on my django app. I also have django-filter on my rest_framework. where I can filter dates. start_date=$start_date&end_date=$end_date from a typical get data. def view_info(request): objs = test.objects.all() return render(request, 'test.html', {'objs': test}) I want to fetch the data directly to the REST API URL localhost:8000/api/test/?start_date=$start&end_date=$end Is it possible? this is how I fetch data from my chart. <script> $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for i in objs %}'{{i.timestamp}}',{% endfor %}], datasets: [{ label: 'Rainfall Graph', data: [{% for i in objs %}'{{i.amount}}',{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> -
Displaying Foreign Key Options in django restframework view
I'm having trouble displaying all the jobs as options in the apply url view see image below. I am getting the error which says Lists are not currently supported in HTML input The main function I am looking for is for a list of jobs that were posted to be available for selection when applying for the job. models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() job_type = models.CharField(max_length=12, choices=JOB_TYPE_CHOICES, default='Full-Time') city = models.CharField(max_length=255) def __str__(self): return self.description[:50] class Applicant(models.Model): """A applicant that can apply to a job""" job = models.ForeignKey(Job, related_name='applicants', on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=254) phone_number = PhoneNumberField() resume = models.FileField(upload_to=resume_file_path, validators=[validate_file_extension]) def __str__(self): return self.first_name I've removed some of the attributes in Job so that the code is not so long. serializers.py from rest_framework import serializers from django.utils.translation import ugettext_lazy as _ from core.models import Job, Applicant class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" applicants = serializers.StringRelatedField(many=True) class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active', 'applicants') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" return … -
How to fix manytomany field in django
How to make a one to many relationship in Django/Mysql? I have an identical situation to this post, yet, my django returns errors on the admin page: get() returned more than one order2pizza-- it returned 5! order2pizza with that pizza already exists. My mysql database have composite keys on a tertiary table to order and pizza to link multiple pizzas to an order. models.py: class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_name = models.CharField(max_length=100, blank=True, null=True) class Pizza(models.Model): Pizza= models.AutoField(primary_key=True) Pizza_name= models.CharField(max_length=50, blank=True, null=True) class order2pizza(models.Model): order = models.ManyToManyField(Orders, models.DO_NOTHING, ) pizza_id= models.IntegerField() class Meta: unique_together = (('order ', 'pizza_id'),) -
Error in hosting Django app with AWS Elastic Beanstalk
I was trying to host my Django app with AWS Elastic Beanstalk. I took help from their very own documentation here Upon doing whatever written there, I faced an error saying: "Internal Server Error" I tried finding out the solution. I found an answer in StackOverflow itself that removing the following part from my settings.py does the job. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Well, it did for the very basic trial. I tried to host my eCommerce website on AWS using the same thing I learned. It showed the same internal server error. So I removed the DATABASE part from my settings.py. Now it shows the very obvious error: ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'my-secret-key' DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # installed apps 'ckeditor', 'ckeditor_uploader', 'eshop', 'product', 'order', 'user', 'mptt', 'paywix', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ebdjango.urls' TEMPLATES = [ … -
Why doesn't href from HTML to CSS work correctly with Django?
I have the next problem: Im ceating a basic django webpage using HTML and CSS. The issue is that when I try to make the href from the HTML file to the CSS one: <link rel="stylesheet" type="text/css" href="modelado.css"> It doesn't work correctly. my HTML file called "inicio.html" and "modelado.css" are in the same folder, but once I make the href, the console says this: Not Found: /inicio/modelado.css I think that the console is trying to find a folder called "inicio", but that's impossible since inicio is the HTML file from where I am running the program. What I want to know is if there is another way to write the direction, because that directory doesn't exist. I also think that this is a django related problem, because when I only use HTML, that line of code actually works when the files are in the same folder. Thanks! -
Do i need to manipulate DRF if only im using the built-in template django system?
I have some troubles understanding Django and DRF, if for instance I want to integrate a frontend framework along with Django, do I really need to use Django itself or will I touch DRF; and in the other hand, if I use the built in template django system, do I need to use DRF? please someone help me since I don't know the answer yet since I want to integrate a frontend framework such as Angular to developer my web page but I think I don't need Django, instead I need to use DRF! -
Issue with passing a file object as an argument of Django command
I'm trying to test a Django command by passing a file object as an argument: a_file = open('Sample.xml', 'rb') call_command("process_xml", a_file, self.valdate) and parse the xml file in the command: from lxml import etree, objectify from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command class Command(BaseCommand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( 'a_file', ) def __init__(self, **kwargs): super(BaseCommand, self).__init__(**kwargs) def handle(self, *args, **options): xml_file = options["a_file"] print(str(xml_file)) result = objectify.parse(xml_file) I got the error: File "/mnt/ccl/management/commands/process_xml.py", line 20, in handle result = objectify.parse(xml_file) File "src/lxml/objectify.pyx", line 1842, in lxml.objectify.parse File "src/lxml/etree.pyx", line 3521, in lxml.etree.parse File "src/lxml/parser.pxi", line 1859, in lxml.etree._parseDocument File "src/lxml/parser.pxi", line 1885, in lxml.etree._parseDocumentFromURL File "src/lxml/parser.pxi", line 1789, in lxml.etree._parseDocFromFile File "src/lxml/parser.pxi", line 1177, in lxml.etree._BaseParser._parseDocFromFile File "src/lxml/parser.pxi", line 615, in lxml.etree._ParserContext._handleParseResultDoc File "src/lxml/parser.pxi", line 725, in lxml.etree._handleParseResult File "src/lxml/parser.pxi", line 652, in lxml.etree._raiseParseError OSError: Error reading file '<_io.BufferedReader name='/mnt/ccl/Sample.xml'>': failed to load external entity "<_io.BufferedReader name='/mnt/ccl/Sample.xml'>" However, if I open the file within the command module, with open('/mnt/ccl/Sample.xml', 'rb') as xml_file: result = objectify.parse(xml_file) There was no issue. Would appreciate if anyone can shed some light on this.