Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django server not displaying and not stopping
I have just started to use django and have followed a tutorial to simply create a project called 'mysite' and then created an app 'hello', which displays a hello world message. The web application works fine and is working as expected. However, I have been encountering a problem where the terminal does not display the url and other things that should be displayed the server does not shut down. The terminal should display: 'Performing system checks...starting development server at http://127.0.0.1:8080/ Quit the server with CONTROL-C.' but instead, it displays nothing. (I have found the $ sign does not exist anymore so assumed the server was working, and thankfully the server was running since the application was working on http://127.0.0.1:8080 as expected. Also, if I refresh the page, I get a response of '[02/Sep/2018 12:13:28] "GET/HTTP/1.1" 200 13' in my terminal which also indicates that the server is running) Although I think it isn't a problem in my working process, I just don't understand why the terminal is not displaying anything. Is this a problem with my terminal or shell (I used zsh on a cygwin terminal on windows) or a problem with the setting with django (am I missing an … -
AttributeError: module 'django.http.request' has no attribute 'session'
I want to logout the user but I am getting this error : AttributeError: module 'django.http.request' has no attribute 'session' Here's my code: class logout_view(request): logout(request) print("-------------User Logging Out---------------") redirect('essay:index') Url: url(r'^logout/$', views.logout_view.as_view(), name='user_logout') Don't know why it is giving error about session.I am using Django 2.0 -
NoReverseMatch at / list
I tried get dynamic link Error: NoReverseMatch at / Reverse for 'new_single' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['single/'] Code: view: {% for new in news %} {{ new.id }} <h2><a href="{% url 'new_single' pk=new.id %}">{{ new.title }}</a></h2> {% endfor %} urls: urlpatterns = [ url(r'^$', views.news_list, name='news_list'), url(r'single/<int:pk>', views.new_single, name="new_single"), ] views: def new_single(request,pk): new=get_object_or_404(News,id=pk) return render(request,"news/news_single.html",{"new":new}) -
build_attrs() got an unexpected keyword argument 'type'
I am using django framework and trying to integrate a paypal payment gateway. But I am getting this error build_attrs() got an unexpected keyword argument 'type' Django Version: 1.11.11 Python Version: 3.6.3 Exception Value: build_attrs() got an unexpected keyword argument 'type' Exception Location: /home/iuser/anaconda3/lib/python3.6/site-packages/paypal/standard/widgets.py in render, line 35 from django import forms try: from django.forms.utils import flatatt # Django 1.7 and later except ImportError: from django.forms.util import flatatt # earlier from django.utils.safestring import mark_safe from django.utils.encoding import force_text class ValueHiddenInput(forms.HiddenInput): """ Widget that renders only if it has a value. Used to remove unused fields from PayPal buttons. """ def render(self, name, value, attrs=None): if value is None: return u'' else: return super(ValueHiddenInput, self).render(name, value, attrs) class ReservedValueHiddenInput(ValueHiddenInput): """ Overrides the default name attribute of the form. Used for the PayPal `return` field. """ def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type) if value != '': final_attrs['value'] = force_text(value) return mark_safe(u'<input%s />' % flatatt(final_attrs)) -
Django : Problem with updating object from the model "already exist"?
I am new to web developing and to Django. I have difficulties to find the right way to update a record (object) of my model in my Django project.Can you have a look on my code and help me to fix it ? After running the code below I got the errors that the object already exist. ( yes , and should be , I want to update it !!!) My guess is the is_valid() is the problem. I have the following model: class QA_machine_DB(models.Model): QAmachine = models.CharField( max_length = 64, unique=True) status = models.CharField(max_length=32,null=True, blank=True) def __str__(self): return "%s" % (self.id) I have the following view: def formreport(request): Booking= BookingForm(request.POST) if request.method == 'POST': if Booking.is_valid(): print('############## VALIDATION GOOD ######################### ') machine_name= Booking['QAmachine'] print('Name',Booking.cleaned_data['QAmachine']) print("Status: ",Booking.cleaned_data['status']) to_book =QA_machine_DB.objects.get(QAmachine= machine_name) # if I hard code the machine_name it works . !? I guess is_valid is the problem .... #to_book =QA_machine_DB.objects.get(QAmachine= 'ali' ) to_book.status='free' to_book.save() return index(request) else: print('Form not valid', Booking.errors) return render(request,'QA_interface_app/form_page.html', { 'Booking': Booking}) I really don't see it , if you can help me I would be fantastic . Thanks in advance -
Django 1.11 , ho to fix it?
when i try to fix the url in my urlpatterns it shows me this error : The error: Your URL pattern "url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view')," is invalid. Ensure that urlpatterns is a list of url() instance. try removing the string 'url(r'^player/[?P[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'),'. The list of urlpatterns should not have a prefix string as the first element. My Code : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', HomePageView.as_view(), name='home-page'), url(r'^teams/$', TeamsListView.as_view(), name='teams-list-view'), url(r'^scores/$', ScoresListView.as_view(), name='scores-list-view'), url(r'^player/[?P<slug>[-\w\x20]+]/$', PlayerDetailView.as_view(), name='player-detail-view'), ] Can anyone help me?? -
Selenium cleaning database in Django Application
I have a Django Application and I'm trying to create some selenium tests for it. The problem is that every time I run the test my database gets cleaned. This is my test: import time from django.contrib.auth.models import User from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys class CrewTest(StaticLiveServerTestCase): def setUp(self): self.selenium = webdriver.Chrome('chromedriver') super(CrewTest, self).setUp() self.user = User.objects.create_user(username='user', email=None, password='password') def test_register(self): selenium = self.selenium selenium.get('http://127.0.0.1:8000/static/myapp.html') name = selenium.find_element_by_id('username') password = selenium.find_element_by_id('password') submit = selenium.find_element_by_id('submit') name.send_keys('user') password.send_keys('password') submit.send_keys(Keys.RETURN) selenium.page_source time.sleep(1) assert 'Welcome user' in selenium.page_source The test is successful, but my database is empty after I run it. Should I have a separate database for selenium tests? Or can I just disable cleaning the database after the test. -
Django - dealing with multiple CSRF tokens in the same template (ajax and form) Forbidden (CSRF token missing or incorrect.)
I have this template where I have a form for submitting an email address, and I'm trying to make a checkbox so that users can choose whether to receive email notifications or not. {% extends "base_generic.html" %} {% block content %} <h1>{{ user.username }}</h1> <p> Email comfirmed? {{ user.profile.email_confirmed }}</p> {% if user.profile.email_confirmed %} <p>Email confimed as {{ user.email }}</p> {% else %} <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Authentificate</button> </form> {% endif %} {% if posts %} <p>Your posts: </p> <ul> <li> {{ posts.author }} {{ posts.pub_date }} {% if post.last_edited != null %} Last edited: {{ post.last_edited }} {% endif %} <br> <a href="{% url 'fortykwords:detail' posts.id %}">{{ posts.title }}</a></li> {% for tag in posts.tags.all %} <a href="{% url 'fortykwords:tag' tag.name %}">{{ tag.name }}</a> {% endfor %} {% endif %} </ul> {% else %} <p>No posts are available.</p> {% endif %} <input type="checkbox" name="checkbox" id="{{request.user.id}}">Send me an email notifications when I receive a message.<br> <script … -
how can i make ~[0] plus to ~[1] in django?
codes: >>> from test2.models import Member_info >>> member = Member_info.objects.all() >>> member <QuerySet [<Member_info: John2>, <Member_info: John1>, <Member_info: John3>]> >>> member = Member_info.objects.all()[0] >>> member <Member_info: gun2> >>> member += Member_info.obejcts.all()[1] Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'Member_info' has no attribute 'obejcts' >>> member += Member_info.objects.all()[1] Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: unsupported operand type(s) for +=: 'Member_info' and 'Member_info' >>> member.append(Member_info.objects.all()[1]) Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Member_info' object has no attribute 'append' 2.How can i append,,,,? -
Serve media files with S3 backend and user permissions
I'm surprised, but I couldn't find anybody with the exact same requirements in Google, so here I go. I'm designing a Django project, and I know that sensitive documents will be uploaded by the users, so I need to introduce some kind of permission control mechanism (thinking about using JWT at the moment). To make my project stateless from an operational point of view (planning to run it in containers), I'd like to store my user-uploaded files in a distributed object storage system (S3/minio). This is where I'm getting lost. I know that in a "regular" Django production environment, the user-uploaded media files tend to go to the ./media folder, and the webserver serves it directly from there, without any kind of authentication. To me, this is risky and unacceptable, because shared direct links can be sniffed/leaked, and unauthorized people can get access to sensitive documents. Wrapping it up: What's the accepted practice to store/serve user-uploaded contents in/from S3/minio? How do I control access to these files? Thanks! -
django-channels: authentication over channel connection
What is the reason to avoid an authentication schema where an anonymous user send credentials over a django-channels connection to authenticate him, the connection and eventually its current session ? -
Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django
I was able to install django once in a virtual enviroment. Now whenever i try to install it with pip install django==2.07 it returns: Cache entry deserialization failed, entry ignored Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))': /simple/django/ Could not find a version that satisfies the requirement django==2.0.7 (from versions: ) No matching distribution found for django==2.0.7 Also I have: pip- 10.0.1 virtualenv- 16.0.0 This is killing me. I believe it has something to do with pip. I … -
Getting 'env' is not recognized as an external or internal command while pushing local database to heroku
What I am trying to do ? I am trying to migrate my local database to heroku. What Is the problem ? While migrating my local database to heroku with this command heroku pg:push mylocaldb DATABASE_URL --app myappname. The pushing of the database crashes suddenly with the message 'env' is not recognized as an internal or external command, operable program or batch file. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mylocaldb', 'USER': 'postgres', 'PASSWORD': 'ahtisham', 'HOST': 'localhost', 'PORT': '5432', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) -
Is it possible to perform an operation before routing to views in django
I have the main urls.py that includes other apps urls.py, then calling the corresponding view. However, I have an operation that needs to be performed everytime before doing anything, whatever the app. Is it possible to perform an operation before routing to the view ? -
rendering a form with css in django
I know how to render static content basically. But, when we use form.as_p to let django build out the form from the models for us, then, there are no tags exposed, so, how do we format the form with CSS? -
Send errors in Django to Sentry asynchronously with Celery to avoid Sentry's error droping
I'm using Sentry for error capturing and reporting in Django (with logging config in settings.py). However, Sentry doesn't capture errors when I send lots of errors in a short time (the free version phenomena). One solution is putting them in a queue and send them async with brokers like Celery. My questions are: 1- Is there any other solution to capture all errors. 2- How can I send the errors to Celery and then to Sentry. I want to handle it in settings.py to avoid cascading to all files. -
I got an error while executing django-admin startproject newDjango as invalide syntax
(newDjango) C:\Python34\Scripts\newDjango>C:\Python34\Scripts\newDjango\Scripts\django-admin.exe startproject newDjango . Traceback (most recent call last): File "C:\Python34\lib\runpy.py", line 170, in _run_module_as_main "main", mod_spec) File "C:\Python34\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Python34\Scripts\newDjango\Scripts\django-admin.exe__main__.py", line 5, in File "c:\python34\scripts\newdjango\lib\site-packages\django\core\management__init__.py", line 11, in from django.conf import settings File "c:\python34\scripts\newdjango\lib\site-packages\django\conf__init__.py", line 18, in from django.utils.functional import LazyObject, empty File "c:\python34\scripts\newdjango\lib\site-packages\django\utils\functional.py", line 12 return _curried_func(*args, *moreargs, **{**kwargs, **morekwargs}) ^ SyntaxError: invalid syntax -
Django database table without writing query
Is there any database for django where table can be created without writing queries and just like we can write all the details for that table without query -
truncate word in django display text only
enter image description here[when I truncateword:30 the image along with the text is displayed. What I need is to just display text and not image.][2] -
What do I do with the frontend of a containerized Django/Angular application?
I have a Django/Angular application I want to containerize for easy deployment to the cloud. I've created a container for the database, now I have the backend and frontend to take care of. I can create another container for the backend, which will include all the Django code and uwsgi as a server. My question is about the frontend - what do I do with it? I need to package all my frontend files (the result of the angular build, as well as the static files of Django, as I'm using the Admin interface), but what do I do with them? I can store all the static files on S3 (or similar if I go with another cloud provider), but something will need to redirect all URLs starting with /admin or /api to the Django container. Do I create a third container with nginx and those files, and connect it to the backend? -
Is there any possibilities of performing bootstrap modals with django messages?
I am creating a accounting app, I was wondering if there is any possibilities of creating a bootstrap modal in django forms...I am using class based views for my app. Actually I need something like when the user submits any form they should not be redirected to any details view they should get a modal pop-up with success messages... Is there any possibilities of performing this in django with class based views...Actually I am new to django thats why facing some basic difficulties, It will be real help for me if some one can help me out in this...' Thank you. -
Python3 Manage.py Runserver Hangs when Running Through Git Bash
I am a total python/git bash noob and new to this. Whenever I run command $ python3 manage.py runserver it seems to run it but hangs. I don't' get any output. How can I fix it or troubleshoot it? My directory in which manage.py is located: /c/python34/pythonprograms/superlists Steps I have done: django-admin.py startproject superlists get into the superlists directory python3 manage.py runserver it runs however then it hangs and blinks. I get not output. If anybody has some suggestions, can you please help me out with some simply-explained steps? Not sure how to get output on this one or how to make it work...all my environment variables seem to be good. I have environment variables setup in my settings for python, python (scripts folder), python (geckodriver). Thank you, Roman -
heroku connect to mysql database
I have push a python-django project to heroku and it works well. In my view.py file of django model, I added function that could connect to the local mysql database to retrieve data from the mysql. The function is the view.py is as followed: @login_required def results(request): data=[] data1 = [] owner = request.user owner = str(owner) db = MySQLdb.connect(user='root', db='aaa', passwd='xxxxx', host='localhost') cursor = db.cursor() cursor.execute("SELECT search_content, id, title, author, institute, FROM result_split where username = '%s'" % (owner)) data = cursor.fetchall() db.close() return render(request, "webdevelop/results.html", {"datas": data}) But when I try to open the page that show the data from mysql database in the deployed heroku website, it show the error:"OperationalError at /results/ (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")". How could I have this heroku project to connect to my local mysql database? Or I should choose alternative? -
502 error running Django in a Docker container with nginx and uwsgi
I'm having trouble running my django app in a Docker container using nginx and uwsgi. I have been following the tutorial from the chapter 5 of the book Building Django 2.0 Web Applications by Tom Aratyn. (code is here : https://github.com/tomaratyn/MyMDB/tree/chapter-5) After a couple days of adapting the script I've manage to : get a mysql (instead of postgres) database running, I can connect with a client and I see that migrations have run according to the script access the Django shell, I can create objects and see them appear in the database Everything seems to be running ok on the bd/app side but I keep getting 502 Bad Gateway errors when I try to connect to localhost or 127.0.0.1:80. (venv) root@3a29f7e17ef5:/sacado/django# curl http://127.0.0.1:3031 curl: (7) Failed to connect to 127.0.0.1 port 3031: Connection refused After Nginx configuration : upstream django { server 127.0.0.1:3031; } server { server_name 0.0.0.0; listen 80; charset utf-8; client_max_body_size 2M; location /static { alias /sacado/django/gathered_static_files; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } } uwsgi : [uwsgi] socket = 127.0.0.1:3031 chdir = /sacado/django/ virtualenv = /sacado/venv wsgi-file = /sacado/wsgi.py env = DJANGO_SECRET_KEY=$(DJANGO_SECRET_KEY) env = DJANGO_LOG_LEVEL=$(DJANGO_LOG_LEVEL) env = DJANGO_ALLOWED_HOSTS=$(DJANGO_ALLOWED_HOSTS) env = DJANGO_DB_NAME=$(DJANGO_DB_NAME) env = DJANGO_DB_USER=$(DJANGO_DB_USER) … -
Using linkify option on Django_tables2 columns to create links
I want to add a link to my listview using linkify in the Columns of the API Reference. I am using Django 2 with Django_tables2 v 2.0.0b3 I have a URL with two context variables name, which is passed from the ListView and the slug field species: URL.py app_name = 'main' urlpatterns = [ #The list view path('genus/<slug:name>/species/', views.SpeciesListView.as_view(), name='species_list'), # The Detail view path('genus/<name>/species/<slug:species>', views.SpeciesDetailView.as_view(), name='species'), ] The DetailView is currently accessible if I manually type the URL. I want to use the option where I can enter a tuple with (viewname, args/kwargs). For the tables.py I tried: class SpeciesTable(tables.Table): species =tables.Column(linkify=('main:species', {'name': name,'slug':species})) This gave a NameError: name 'species' is not defined. species =tables.Column(linkify=('main:species', {'name': kwargs['name'],'slug':kwargs['species']})) This gave a NameError: name 'kwargs' is not defined. I also tried changing the following variables to strings: species =tables.Column(linkify=('main:species', {'name': 'name','slug':'species'})) species =tables.Column(linkify=('main:species', {'name': 'name','slug':'object.species'})) These attempts gave a NoReverseMatch Reverse for 'species' with keyword arguments '{'name': 'name', 'slug': 'species'}' not found. 1 pattern(s) tried: ['genus\\/(?P<name>[^/]+)\\/species\\/(?P<species>[-a-zA-Z0-9_]+)$'] Formatting it as any of the following will give a SyntaxError: species =tables.Column(kwargs={'main:species','name': name,'slug':species}) species =tables.Column(args={'main:species','name': name,'slug':species}) species =tables.Column(kwargs:{'main:species','name': name,'slug':species}) species =tables.Column(args:{'main:species','name': name,'slug':species}) How would I add a link similar to {% url "main:species" name=name …