Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form has defualt HTML required
My sign up page has the HTML required attribute for the form fields, 'instrument1, 'instrument2, 'level1' and 'level2'. I never used required in the form or html so I'm wondering why it's popping up and how to disable it. Thanks. forms.py class TeacherSignUpForm(RegisterForm): instrument1 = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control'})) instrument2 = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control'})) level1 = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control'})) level2 = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control'})) def save(self, commit=True): user = super(TeacherSignUpForm, self).save(commit=False) user.instrument1 = self.cleaned_data['instrument1'] user.instrument2 = self.cleaned_data['instrument2'] user.level1 = self.cleaned_data['level1'] user.level2 = self.cleaned_data['level2'] user.teacher = True if commit: user.save() return user HTML <div class="items"> <div class="form-inline justify-content-center"> <!-- Instrument 1 --> <div> {{ form.instrument1 }} </div> <!-- Level 1 --> <div> {{ form.level1 }} </div> </div> </div> <div class="items"> <div class="form-inline justify-content-center"> <!-- Instrument 2 --> <div> {{ form.instrument2 }} </div> <!-- Level 1 --> <div> {{ form.level2 }} </div> </div> </div> -
Recommended way to setup Django REST framework with Firebase
Investigating this topic, I found plenty of potential ways to implement firebase with django rest framwework: TokenAuthentication Custom authentication (and some packages have been built this way: django-firebase-auth, django-rest-framework-firebase) djangorestframework-jwt django-rest-knox I tried using django-rest-framework-firebase, but it's broken. I tried manually adding a custom FirebaseAuthentication class, but querying the api somehow never enters the authenticate() method. There's somehow very few mentions of Firebase on 3rd-part tools like djangorestframework-jwt. All I'm trying to do right now is filtering model fields on ModelViewSet per request (anonymous users can see public basic information, authenticated users can see their own private information). I understand that once I log my user from the frontend, I can query firebase for the user token id and use it to query my server's api. From the server, I need to query firebase with that token id to get another token (jwt?) used to retrieve the django user in my postgresql db. In the case of user creation, my view should create the custom token and save it in both postgresql and firebase for that user. Can the Django REST framework core team suggest a recommended way to setup firebase when using viewsets ? -
TypeError in Python 3 with Django 2.0
I have an issue where I am trying to fix my urls.py file. I have read the documentation and the error that I am receiving the fix should be to use import . from views but I have that and I'm still receiving the error. Here is my urls.py file `from django.urls import path from . import views urlpatterns = [ path(r'^user/(?P<username>[-\w]+)/$', 'bookmarks.views.bookmark_user', name='bookmarks_user'), path(r'^$', 'bookmarks.views.bookmarks_list', name='bookmarks_list'), ]` This is the error: raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
Django - Gunicorn/Nginx Deployment Testing Error
Need Help on Gateway 502 Bad Gateway ngnix/1.10.3 I have configured my Django application using Nginx/Gunicorn. It was running fine until I made some changes to the code and reloaded the server. FYI: My settings.py has ALLOWED_HOSTS = ['*'] Error Logs : 2018/06/27 08:36:38 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:36:40 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:36:41 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:39:06 [crit] 7444#7444: *41 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" -
Django - No add button for TabularInline
I'm using Django 2.0.9 and I'm creating a simple TabularInline ModelAdmin, as follows: class AnswerInline(admin.TabularInline): model = Answer This is then used in a ModelAdmin object, like so: inlines = [AnswerInline]. The ModelAdmin is registered with the admin site. Everything works as expected, except that I do not see the ability to add further inline models. Here's what I mean: I've seen other inlines where there is such a button, which would dynamically add more fields that I can populate. I've tried overriding things on the TabularInline, like setting has_add_permission to return true and setting max_num to 1000, but I still cannot get the button to show up. Would appreciate some outside input here. Thanks! -
ImportError: No module named urls on Django REST framework Tutorial 1
In the "Working with Serializers" section of the Django REST framework Tutorial 1 (Link Here), when I go to import SnippetSerializer with the command: >>> from snippets.serializers import SnippetSerializer I get the error: ImportError: No module named urls I copy and pasted the code for /snippets/serializers.py file from the tutorial to make sure I hadn't made a typo. What could be the problem? If I need to include any other details, please let me know in a comment. -
How can I require admin login on a Django site only if a certain environment variable is set?
I have two AWS Elastic Beanstalk environments serving content using the same Django web server. One of them is a staging site (i.e. for development/testing purposes) and one of them is the production website. On the staging site, features that normally require payment are free to use in order to simplify testing and development. I want to avoid having users stumble upon this staging site and gaining free access to features that normally require payment. To prevent this, I would like to require staff login for all of the views, but only on the staging site. I have an environment variable that gets checked in settings.py which determines whether or not the server is running in the staging or production environment. Is there some elegant/clean way of accomplishing this by checking that environment variable? -
How to filter django-taggit top tags
Suppose you have a database with User objects running behind a Djano app and you want to use django-taggit to tag User objects so you can retrieve subgroups using some convenient filtering. Additionally you have a Dashboard where you want to display interesting statistics about used tags to glean some information about the subgroups that exists within your Users. How would you access and display information about the top X tags used within the Django app? How would you access only the top X tags of an already filtered subgroup of the User object? -
Django choosen user permission is not showing in admin
I tried to extend default Django user in my project by using AbstracUser. In Django admin i couldn't see choosen user permissions. Here is my work from django.db import models from django.contrib.auth.models import AbstractUser class ExtendedUser(AbstractUser): bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) After that i add my extended user in admin.py class ExtendedUserAdmin(admin.ModelAdmin): pass admin.site.register(ExtendedUser, ExtendedUserAdmin) Also add AUTH_USER_MODEL in settings.py AUTH_USER_MODEL = '_aaron_user.ExtendedUser' -
Dynamically update models
I have a signup form that works great. One feature of it is users can press "Add more +" and have more identical "instrument" and "level" select fields created. The model only saves the first "instrument" and "level" field and not the further ones created from the javascript function. How can I adjust my model to create further fields when the javascript function is called? I appreciate any help I get. models.py class User(AbstractBaseUser): instrument = models.CharField(max_length=255, choices=instrument_list) level = models.CharField(max_length=255, choices=level_list) HTML <div> <div class="items"> <div id="ins"> <div> {{ form.instrument }} </div> <div> {{ form.level }} </div> </div> </div> <div id="add_more"> <button type="button" class="no_link" onclick="add_instrument()">Add more +</button> </div> </div> Javascript var i = 0; var original = document.getElementById('ins'); function add_instrument() { var clone = original.cloneNode(true); clone.id = "ins" + ++i; original.parentNode.appendChild(clone); } -
"Uncaught SyntaxError: Unexpected token <" in Django/React app for prod env
Tons of questions regarding this. I've probably gone through all of them, which hasn't resolved my issue. The accepted answers vary widely, which is to say I am confident that despite the similarity in title, this is not a duplicate. Anyway, at first I was pretty convinced it was a web server issue. The setup is Apache with a Gunicorn proxy. However, I just made a new Django app and it is loading "the install worked successfully!" page. So I am pretty sure the issue is with Webpack or python manage.py collectstatic. What is the issue? When I try to load them app in browser, I get these errors: Viewing them shows the following, and actually clicking on any of the static files in Chrome's Dev Tools > Sources, produces the following which is basically my index.html. However, if you look at the same files on the server, they have the correct JS and CSS. So the server is responding with my index.html for assets when it receives a request via browser. This is what the actual Django template looks like: {% load render_bundle from webpack_loader %} {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> … -
Django; Bootstrap doesn't work for pages that have number
I'm new to Django. Basically the problem is bootstrap doesn't work for pages that have number like path('edit_entry/<int:entry_id>'). It does work for pages that don't have number like path('') or path('add_entry/') I'm using bootstrap stuff from https://startbootstrap.com/. And the error message from the console on browser is like this. HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). GET - http://127.0.0.1:8000/edit_entry/static/blog/js/scrolling-nav.js urls.py is like this. path('edit_entry/<int:entry_id>', views.edit_entry, name='edit_entry'), It does work for pages that don't have number so I guess there's a specific way to solve this and it's a problem people often face. How can I fix this? -
django rest api - adding users to keyword model
i want to implement a feature in my rest api that users can add specific keywords for a news feed. so if the users make a post request with a keyword within, the user object will be added on the predefined keyword (predefined in the database). I have tried it with this code, but always if i try to simulate the post request with postman and i have this problem: the keyword will be added but not the provided json data, its just a empty string and the post request returns also an empty keyword... I hope you are able to help me and maybe you could give me an advice how to just allow the static keywords which are already defined and allow user only have a keyword once (no double keywords with same value) Made with this headers: [{"key":"Content-Type","value":"application/json","description":""}] [{"key":"Authorization","value":"Token xxxxxxx","description":""}] Body: { "name": "keyword1" } Authorization works, so the user added to the empty keyword I am very new to django and i am doing this project to improve my skills, so please be lenient to me :) So it could be that its completly wrong, please give me some advices to solve my problem These are … -
Unable to install mysqlclient on macos High Sierra
I am building a project using Django and I am setting up my system. I am using macos High Sierra. Python: 3.6.5 In my attempt to execute the following script: python manage.py dbshell I am getting this error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/db/models/base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/db/models/base.py", … -
Python lxml and xslt issue
I have some problem with lxml and python. I have this code: import lxml.etree as ET xml_dom = ET.parse(xml_path) xslt_dom = ET.parse(xslt_path) print('transforming...') transform = ET.XSLT(xslt_dom) print('transformed: ', transform) parsed_xml = transform(xml_dom) print('all good!') On my local environment, all works good (python 3.6.5 on a virtualenv with lxml 3.6.0). The problem is, i have this code on a Centos 7 server, with the exact same specs (Python 3.6.5 and lxml 3.6.0), if i execute it from command line, all is good, when i put this code inside a Django (2.0) project, it "freeze" on this part: transform = ET.XSLT(xslt_dom) No exceptions, no errors, nothing. The print below that line never executes. I changed permissions of the files, to apache group, set read permissions, and nothig works. The weird thing is, from console works nice, from "apache + Django", don't. Any suggestion? Thanks. -
Which technology is best for my needs
I'm a new developer tasked with creating an app for my new job. I need to create an application that checks an email inbox for new messages every hour, extracts data from a message, stores it to a DB, and uses that data to create a pdf report. I wanted to use python because that's the language I'm most familiar with, and my partner already started writing a python script for creating a pdf. This app will potentially have to utilize the shopify API sometime in the future. My initial impression was to use django because of its email and shopify packages, but I don't think the app needs any kind of front end. Does anyone have any suggestions for frameworks or technologies I should use? I hope this question is not too open ended, but I wanted some input before I started developing so that I don't waste time with an improper technology or framework. Thanks -
AttributeError: in django
enter image description here Here i use index as function and mapped it but attribute error occurs -
Django how to create session variables to pass information from one web page to another
I'm new to django session. If I have pieces of information extracted in one page view such as this if 'editEntry' in request.POST: values = request.POST['editEntry'] values = values.split(',') id_num = values[0] first_name = values[1] last_name = values[2] country = values[3] city = values[4] salary = values[5] return redirect('/edit') Is there a way to send those variable information to another webpage? Also what would the template language be to call on a variable like id_num in the html file. -
Are Django global variables shared across all users or individual users?
Hey this is a more general question. The first part is just knowing exactly how Global variables work. If multiple users are accessing the server at the same time is a global variable going to be shared across all of the users? or will each user have their own instance of that global variable? I am aware of sessions and how this is probably the best answer to solve my issue, however, I am currently working with the Django FormWizard and it doesnt seem to have access to request so I am unable to use the sessions. I am not entirely sure how to access request so if anyone knows how to do that I appreciate the help. Thanks! -
django -Which is faster, reverse lookups in filter or forward lookups to pks?
I have a django model structure that looks like this: # Pre-defined User model class A(models.Model): pass class B(models.Model): relevant_users = models.ManyToManyField(User) related_A = models.ForeignKey(A) And given a User, I want to quickly generate a queryset of all A's attached to B's where the user is in the relevant_users many-to-many. I expect lots of A's, but only one or two B's per A, with indexing on pk's only. I have two methods for generating this queryset, and both work: Method 1: Filter A objects with reverse lookup. queryset = A.objects.filter(B__relevant_users__exact=user) Method 2: Get a list of the A pks with forward lookup, then find those pks in the A table. (select_related is used, but omitted here for clarity) a_pks = [b.related_A.pk for b in user.b_set.all()] queryset = A.objects.filter(pk__in=a_pks) Are these equivalent? Do they have the same time complexity, for large numbers of A? -
Pointing STATIC_URL to CDN Not Working
I would like to use a CDN to serve my static and media files. Setting MEDIA_URL to my cdn works like a charm as so, MEDIA_URL = 'https://cdnid.cloudfront.net/media/' But completely fails when trying to do the same for STATIC_URL. STATIC_URL = 'https://cdnid.cloudfront.net/static/' I am also keeping my MEDIA_ROOT and STATIC_ROOT as their defaults. STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') From everything I have read this should work great. We have a custom way of deploying these static assets and so I have opted to using this simple approach as opposed to some of the more complicated but automated setups where boto3 will take your collectstatic assets, post them to cloudfront, and let django know where they are. I dont really understand what else I am missing. The django docs make it seem that this is exactly how it is done, Example: "/static/" or "http://static.example.com/" This is not working in development or production environments. -
Django access entry from ManyToMany Through model in a template
I would like to access the list of users subscribed to a given training and I managed to get the list with correct number of subscribers but all subscribes have the name of the user currently logged in. Thanks in advance! models.py class Training(Base): subscribers = ManyToManyField(User, through = 'Subscription') class Subscription(Base): user = ForeignKey(User, on_delete = CASCADE) training = ForeignKey(Training, on_delete = CASCADE) views.py class ShowSubscribers(Subscription): def get(self): self.subscribers = models.Subscription.objects.filter(training = self.get_training()) in my template I call the list in the following way: {% for s in subscribers %} {{subscription.user.first_name}} {% endfor %} -
Repeating HTML blocks in Django
Not sure what technical term it is I'm looking for, but I have a set of HTML elements that are repeated and wondering if there is an easy way to do this. Very simplified HTML, if I have the following: <div class='container'> {{ django.dataFromORM }} </div> I need to add to base.html in a certain section <div id='main-container'> all elements go here </div> So on run, I want to add the generated HTML the main-container. I've done this before by building in JS, but wondering if there is a way to smoothly do this in Django? I looked at templates and partials, but not sure that's the proper way or not? -
Django extracting values and making them placeholders in another page
so on my first webpage I have a submit button that contains an array of information I need in the value tag. <button type="submit" name="editEntry" value="[{{ entry.id }}, {{ entry.first_name }}, {{ entry.last_name }}, {{ entry.country }}, {{ entry.city }}, {{ entry.salary }}]">Edit</button> In my view.py, I set variables for each extracted information in the value tag. def post(self, request): form = AddUser(request.POST or None) context = { 'form': form } if 'editEntry' in request.POST: values = request.POST['editEntry'] id_num = values[0] first_name = values[1] last_name = values[2] country = values[3] city = values[4] salary = values[5] return redirect('/edit') Now in my edit page I have a some input tags <input type="hidden" name="id_num" value=""> <input type="text" name="first_name" placeholder="First Name" value=""> <input type="text" name="last_name" placeholder="Last Name" value=""> <input type="text" name="city" placeholder="City" value=""> <input type="text" name="country" placeholder="Country" value=""> <input type="text" name="salary" placeholder="salary" value=""> How can I take the variables, I gained from my first webpage, and put them as the values in my input tags for the edit page? -
Hotel Booking Website with Django - How can you change the price of a room every night?
I am coding a hotel booking website. The hotel and the date are two separate models. class Hotel_Database(models.Model): hotel_name = models.CharField(max_length=20) description = models.TextField() location = models.CharField(max_length=20) def __str__(self): return self.hotel_name class Hotel_Date_Price(models.Model): hotel = models.ForeignKey(Hotel_Database, on_delete=models.CASCADE , related_name='hotel') departure = models.DateField(default= datetime.date.today()) departure1 = models.DateField(default=datetime.date.today() + datetime.timedelta(1)) price1 = models.IntegerField() def __str__(self): return self.hotel.hotel_name + ' ' + str(self.departure) + ' ' +str(self.departure1) HOWEVER, I need a separate price for every night. In models, I have tried creating another class just for the price but it is not filtering through the available dates. Creating another object with DjangoAdmin is also not working because it will not recognize the available dates. #views.py if form.is_valid(): location = form.cleaned_data['location'].capitalize() departure1 = form.cleaned_data['departure1'] departure2 = form.cleaned_data['departure2'] num_of_people = form.cleaned_data['num_of_people'] list_of_hotels = Hotel_Database.objects.filter(location__icontains=location, hotel__departure__lte=departure1, hotel__departure1__gte=departure2)