Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PyCharm launching Django console for Flask app
For whatever reason, PyCharm thinks my Flask project is a Django project, and thus launches a Django console instead of a Python console in the toolbar: The project interpreter is configured properly: Here is my project hierarchy, if it's relevant: . ├── LICENSE ├── README.md ├── app │ ├── __init__.py │ ├── email.py │ ├── main │ │ ├── __init__.py │ │ ├── errors.py │ │ ├── forms.py │ │ └── views.py │ ├── models.py │ ├── static │ │ └── favicon.ico │ └── templates │ ├── 404.html │ ├── 500.html │ ├── base.html │ ├── index.html │ └── mail │ ├── new_user.html │ └── new_user.txt ├── config.py ├── data-dev.sqlite ├── data-test.sqlite ├── manage.py ├── migrations │ ├── README │ ├── alembic.ini │ ├── env.py │ ├── script.py.mako │ └── versions │ ├── 38c4e85512a9_initial_migration.py ├── requirements.txt └── tests ├── __init__.py └── test_basics.py Just because there is a module called manage.py doesn't mean I'm working on a Django project! How can I fix this? -
Nginx not serve media files
I develop an application with Django and Angular 4, before I can see media files without problems in my localhost, but in my LightSailServer I delete my sock file created with gunicorn and deploy my app again, but I don't understand why I don't see my media files in this moment, this is my nginx file, but I don't touch this in all moment, I think my problem is in other way, any ideas? server { listen 80; server_name 54.12.12.142; location = /favicon.ico { alias /home/ubuntu/tracker-web/trackerServer/favicon.ico; } include /etc/nginx/mime.types; location /static/ { root /home/ubuntu/tracker-web/trackerServer; } location /media/ { autoindex on; alias /home/ubuntu/tracker-web/trackerServer/media/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/tracker-web/trackerServer/trackerServer.sock; } } I don't see problems in this file, but I can't see my media files and these exists! PD: I obtain correct path to media files from my web server, only I can't see these. Thanks -
Django CORS Access-Control-Allow-Origin missing
I'm trying to implement google oauth2 authentication in my django app. I have followed all the steps as per the docs. On the browser address bar,if I browser this https://foo.bar.net/api/v1/auth/login/google-oauth2/ this url, it properly authenticated by google and it returns a google-auth-token to the mentioned redirect-url and it fetches the auth-token and converts it to a normal token which then sends to the user or frontend in json format. But if I tried to make a GET request to the above mentioned url from my js code, it shows Reason: CORS header 'Access-Control-Allow-Origin' missing Full traceback on the frontend looks like, GET https://foo.bar.net/api/v1/auth/login/google-oauth2/ 302 Found 718ms polyfil...ndle.js (line 7507) GET https://accounts.google.com/o/oauth2/auth?client_...DW&response_type=code&scope=openid+email+profile 200 OK Login Failed Response { _body=Event error, status=0, ok=false, more...} main.bundle.js (line 367) Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/auth?client_id=kguygvh868697-khgkhvkgvkgkgv.apps.googleusercontent.com&redirect_uri=https://foo.bar.net/api/v1/auth/complete/google-oauth2/&state=Cbms1QhSQVzjO3xkjhkyuu&response_type=code&scope=openid+email+profile. (Reason: CORS header 'Access-Control-Allow-Origin' missing). I have searched google which prompts me to install djang-CORS-headers. I have installed and configured the above package. But the same error appears. A part of my settings.py looks like, MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'oauth2_provider', 'corsheaders', 'rest_framework_swagger', … -
How do I use a form to update a model?
So what I'm trying to do is display a model on a page and then use a form to update said model on the page. I've managed to create a form and display it on the page, and I have managed to create to create a model--though I haven't gotten to display it on the page. This is what I have so far for the form: from django import forms class IndexForm(forms.Form): post = forms.CharField() This is my models: from django.db import models class Post(models.Model): post = models.CharField(max_length=141) And of course, my views. from django.shortcuts import render from firstapp.forms import IndexForm from django.views.generic import TemplateView from firstapp.models import Post class HomePage(TemplateView): template_name = 'home/home.html' def get(self, request): form = IndexForm() posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) Now how would I go about changing this so the home page would display a form and a model with something like "Name:" and when you input your name in the form, the model would update itself to be "Name: [Your Name]"? -
Django REST group foreign key models
I have models like below. Menu Model class Menu(models.Model): name = models.CharField(max_length=40, unique=True, verbose_name='menu name') Item Model class Item(models.Model): class Meta: unique_together = ('shop', 'menu',) shop = models.ForeignKey(Shop) menu = models.ForeignKey(Menu) name = models.CharField(max_length=500) price = models.IntegerField(default=0) I want to get the menus for the shop id. Item.objects.filter(shop_id = 1) How can I group my results by menu name for the shop id 1. ? Sample. { menu: menuname1 items: [ {item1}, {item2}] }, { menu: menuname2 items: [ {item1}, {item2}] } Thanks.. -
Django: serving user uploaded files
I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py: MEDIA_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = "/media/" When I access these files through my admin I get the following url displayed in my browser: http://127.0.0.1:8000/media/filename.pdf Hence what I tried is to give a link to the file in my HTML code : <a href="/{{instance.docFile.url}}/">File</a> But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error. Adding localhost:8000/ before {{instance.docFile.url}} also didn't work. Why isn't this working?What is the correct way to display link to my files? Let me know if anything else is required.Thank you. -
Reverse for 'user_review_list' not found. 'user_review_list' is not a valid view function or pattern name
Even after going through similar STACKOVERFLOW solutions this doubt was not solved. I have also been through other resources. Been engaged in django since 2 days only !! :) project -> winerama app ->reviews my views.py > def review_list(request): latest_review_list =Review.objects.order_by('-pub_date')[:9] context ={'latest_review_list': latest_review_list} return render(request, 'reviews/review_list.html',context) def wine_list(request): wine_list =Wine.objects.order_by('-name') context ={'wine_list':wine_list} return render(request, 'reviews/wine_list.html',context) def review_detail(request , review_id): review = get_object_or_404(Review , pk = review_id) context = {'review':review} return render(request,'reviews/review_detail.html',context) def wine_detail(request , review_id): wine = get_object_or_404(Wine, pk = wine_id) context = {'wine':wine} return render(request,'reviews/wine_detail.html',context) def add_review(request,wine_id): wine = get_object_or_404(Wine , pk = wine_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name=form.cleaned_data['user_name'] review =Review() review.wine = wine review.user_name = user_name review.user_name = user_name review.rating =rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() return HttpRespponseRedirect(reverse('reviews:wine_detail',args = (wine.id,))) return render(request,'reviews/wine_detail.html',{'wine':wine,'form':form})` reviews/urls.py urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /wine/ url(r'^wine$', views.wine_list, name='wine_list'), # ex: /wine/5/ url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), url(r'^wine/(?P<wine_id>[0-9]+)/add_review/$', views.add_review, name='add_review'), ] reviews/templates/reviews/base.html {% block bootstrap3_content %} <div class="container"> <nav class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'review_list' %}">Winerama</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'wine_list' %}">Wine list</a></li> <li><a href="{% … -
Django - Admin forms data generation with fields which are not in model
I have a specific scenario and I am unable to figure out how to approach this problem, some direction will be great help: I have a model: class RollNumber(models.Model): r_no_prefix = models.CharField(max_length=10, verbose_name='Roll number suffix') r_no= models.IntegerField(verbose_name='Number') r_no_suffix = models.CharField(max_length=10, verbose_name='Roll number prefix') def __unicode__(self): return '%s -%s-%s' % (self.r_no_prefix,self.r_no,self.r_no_suffix) No, I want to generate these Roll numbers in bulk by asking the user to input the following in a form which is not having any of the above model fields. Number of roll numbers you want to generate: ____________ Roll number prefix: ________________ Roll number suffix: ________________ [SUBMIT][CANCEL] The submission of above form should be able to generate the number of rollnumbers and create records in RollNumber table in bulk. If I try to use this form again, if should get the last number and then start the sequence from there. Considering the that user may have deleted some of the roll number records. -
Django rating system
I am trying to implement a rating system on a Django website. I have done my rating with just one star (booleanfield) false/true : <!-- Favorite Album --> <a href="{% url 'music:favorite_album' album.id %}" class="btn btn-default btn-sm btn-favorite" role="button"> <span class="glyphicon glyphicon-star {% if album.is_favorite %}active{% endif %}"></span> </a> and this these are my album model : class Album(models.Model): user = models.ForeignKey(User, default=1) artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() is_favorite = models.BooleanField(default=False) So, I want to know how to change this rating, so I will be able to select from 1 to 5 (in numbers) to rate the album. And by that, the album model should look like this I think : .......... is_favorite = models.IntegerField() .......... -
Django & Heroku | How to log 400 error in detail?
I have created an app on Heroku and I push my Django app to it. I monitor the logs using heroku logs --tail to see them in real time. How to display 400 error log in detail at such a production environment (when DEBUG=false)? I know debug.technical_500_response(request, *exc_info)method and use it for logging 400 errors, but it seems there is no technical_400_response method. I'm using Django 1.11.5 Python 3.6.1 whitenoise 3.3.0 Procfile web: gunicorn --env DJANGO_SETTINGS_MODULE=myapp.settings myapp.wsgi --log-file - settings.py LOGGING = { 'version': 1, 'formatters': { 'all': { 'format': '\t'.join([ "[%(levelname)s]", "asctime:%(asctime)s", "module:%(module)s", "message:%(message)s", "process:%(process)d", "thread:%(thread)d", ]) }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'django.log'), 'formatter': 'all', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'all' }, }, 'loggers': { 'command': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, }, } Thanks in advance. -
django rest create api to show count of distict field in a model
i'm amateur in Django Rest! i have a model named 'person' with some field 'name,family,tel,....' i want to create an api to show count of distict family my serializer: class PersonCountSerializer(ModelSerializer): class Meta: model = Person fields = 'family' my view: class PersonCountView(ModelViewSet): queryset = Person.objects.all().distinct('family').count serializer_class = PersonCountSerializer url: router.register(r'personcount', views.PersonCount) and it doesnt work,please help to fix it thanks -
Disadvantages of using ASGI instead of WSGI
What is the explicit and clear disadvantages of using ASGI instead of WSGI for HTTP request handling in Django in general? I know ASGI is for asynchronous tasks, but it can also handle synchronous HTTP requests via http.* channels. Is it slowly than normal WSGI or is there any unsupported features comparing to WSGI? One more, for providing both REST API and websocket handling in same project, which way do you prefer and why? WSGI for REST + ASGI for websocket in different server instances WSGI for REST + ASGI for websocket in same machine ASGI for both -
Django sitemaps while using Jinja2 templating
I am trying to set up a sitemap.xml on my Django project. However, I am currently experiencing this error: TemplateDoesNotExist at /sitemap.xml I have added sitemaps to my installed apps: INSTALLED_APPS = [ # Django base. 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.staticfiles', # Own modules. ... ] This is my TEMPLATES configuration: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': TEMPLATE_DIRS_, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], }, }, ] I thought it could be because I am missing the loader. I have tried adding it: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': TEMPLATE_DIRS_, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.app_directories.Loader' ], }, }, ] When doing this, however, the error evolves into: ?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option. I need APP_DIRS for Jinja2. Even if I tried to set it to False, then the homepage (nor any page for that matter) would not load. Anyway to import sitemaps.xml from Django while keeping Jinja2? Thank you! -
Accessing ValidationError in PyCharm
I'm having issues with accessing ValidationError in the models.py file of my django app (running in PyCharm 2017.2.3): from django.core.exceptions import ValidationError ValidationError is underlined red, and hovering over it, it says "Unresolved reference to 'ValidationError'" Further, when looking up that file in 'External Libraries', that file (django.core.exceptions) has a different icon to the other python files, and no syntax highlighting. I've also tried to create my own 'exceptions.py' file in my app so I can define some commonly-used exceptions, and that file has the same issue (different icon, no syntax highlighting). Both issues are with files called 'exceptions.py', so I can't help but think they're connected somehow. While typing this, have also realised that if I start typing "from django.core.ex..", 'exceptions' isn't picked up/offered by the autocomplete feature. Running: PyCharm professional 2017.2.3 Python 3.6.2 in virtualenv Django 1.11.5 Have also tried a fresh install of everything, issue still exists. -
Why is create_or_update generating manager attribute error?
I receiving an error AttributeError: 'Manager' object has no attribute 'create_or_update' in my views.py upon using create_or_update below. My code is shown below: SlotFilling.objects.create_or_update( originator=textobject.originator, defaults = {empty_slot: True, relevant_intent: intent_rank1, ner_entities_list: ner_entities,} ) I'm not sure how to resolve this error. I'm using Django 1.11.2, so create_or_update should be supported. The only thing I can think of is that I must have missed something in my model.py. I've included that below. Any insights into what might be happening? My models.py: from django.db import models class SlotFilling(models.Model): originator = models.CharField(max_length=20, primary_key=True) empty_slot = models.BooleanField(default=False) relevant_intent = models.CharField(max_length=20) slotted_entity = models.CharField(max_length=20) ner_entities_list = models.CharField(max_length=40) -
model design for considering multiple work schedule with number
I am trying to create convincing job hiring model. However I got stuck to show the conditions like 3 Full Time, 2 Part Time in a single job. For example, a company may post job for senior backend developer with job description and all where he may select both Full Time and Part Time work schedule. Probably he want to state how many Full Time and Part Time employer for that job. That is why I am using ManyToManyField for work schedule but I am not sure for the numbers of employeer for certain workschedule in an efficient manner. Here is the model design that I have designed for now class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=50, unique=True) description = models.CharField(max_length=400, blank=True, null=True) class WorkSchedule(models.Model): name = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=50, unique=True) class Position(models.Model): name = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=50, unique=True) class Job(models.Model): company = models.ForeignKey( Company, related_name='jobs', on_delete=models.CASCADE) job_title = models.CharField(max_length=200, blank=True, null=True) category = models.ForeignKey(Category, related_name='jobs') description = models.TextField(blank=False, null=False) city = models.CharField(max_length=100, blank=False, null=False) position = models.ManyToManyField( Position, related_name='jobs', blank=False, null=False) work_schedule = models.ManyToManyField( WorkSchedule, related_name='jobs', blank=False, null=False) -
Django + HTML Template cannot display the right way
I'like to represent the list of news_list, the result should be like following style using 2 loops: category1 -- info_record 1 -- info_record 2 category2 -- info_record 3 The problem is, inside loop {% for m in p_list.p.name %} always nothing happen, meanwhile outside loop {% for p in p_category %} could be retrieved properly. html template file is shown as below, {% block content %} <div class = "container"> {% for p in p_category %} <div class = "row" > ......... {{p}} </br> </div> {% for m in p_list.p.name %} <div calss ="row"> .. <a href = "/pubinfo/{{m.slug}}" > {{m.title}} - [ {{m.created}}] </a> </div> {% endfor %} {% endfor %} </div> {% endblock %} the view file is shown as below, from django.shortcuts import render from datetime import datetime from .models import Category from .models import PostInfo def list_all(request): post_categories = Category.objects.all() post_lists ={} for cate in post_categories: post_lists[cate.name] = PostInfo.objects.all().filter(category = cate) import pdb; pdb.set_trace() return render(request, 'pub_post.html', {'p_category': post_lists.keys(), "p_list": post_lists}) model file is shown as below, from django.db import models from django.contrib.auth.models import User # Create your models here. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) … -
How do I pass primary key from url to function based view in django?
I have a function based view as: @api_view(['GET', 'PUT', 'DELETE']) def hotel_detail(request, pk): # Lots of code and I'm using this URL pattern: url(r'^hotel/(?P<pk>[0-9]+)/$', api.hotel_detail) but it's not working -
How do you conditionally modify/update an object in django?
I'm looking to create/update an object in Django. My current code shown below: SlotFilling.objects.create( originator=textobject.originator, empty_slot=True, ) Where originator is set as my primary key. This works fine for creating new objects for the first time the originator is seen. However, I'm wondering how do I update the object if the originator has already exists in the DB. Basically if primary key already exists update functionality, but if it doesn't then create functionality. I'm looking for an alternative to .create here. I couldn't find how to do this in the models documentation. Is it possible? I know I could use try/except but I am wondering if django has an alternative. -
SQL query radius based on latitude and longitude of a linked model
I am having issues executing one query as I can't link properly two models together. ModelA contains a OneToOne relationship with a Location(latitude, longitude) table. The database is Postgres. The query is failing on: ( SELECT * FROM "myapp_location" WHERE id=location_id ) as location, The message it's giving me is: subquery must return only one column Here is the Query: ''' SELECT * FROM ( SELECT id, location_id, ( SELECT * FROM "myapp_location" WHERE id=location_id ) as location, ( 3956 * 2 * ASIN( SQRT( POWER( SIN(({latitude}- location.latitude) * pi()/180 / 2), 2) + COS({latitude} * pi() / 180) * COS(location.latitude * pi() / 180) * POWER(SIN(({longitude} - location.longitude) * pi() / 180 / 2), 2) ) ) ) AS distance FROM {model} ORDER BY distance ) items WHERE distance <= {miles} '''.format(latitude=latitude, longitude=longitude, miles=miles, model=model) Does anyone have any good suggestions? Much appreciated. -
ImportError: No module named captchia.fields
I am using python 2.7 django 1.11 and django simple captcha 0.56, when I using python manage.py test captcha, error popup as below, appreciated if any assistance. -
Highlight search terms on a django search results page
How can I create a search results page in Django 1.11, using PostgreSQL full text search, where the terms searched for are highlighted? -
required=false for BooleanField generates TypeError
It is my understanding from documentation and other SO posts that BooleanField needs required=. When I left it out there was a syntax error in my view.py, where I was saving to the model. However, now that I've added required=False I'm getting a TypeError. My code: class SlotFilling(models.Model): originator = models.CharField(max_length=20, primary_key=True) empty_slot = models.BooleanField(default=False, required=False) My error: File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 996, in __init__ super(BooleanField, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'required' Any insights into what might be happening here? -
How to get description of object from python django backend to AJAX in front end?
So for each of my models in my apps I have the object description def unicode(self): ............................... And I want to see this description in my dynamic drop boxes generated with Ajax. My data flows in following way: 1-I have sterilizer in my api class LeaseTermSerializer(serializers.ModelSerializer): class Meta: model=LeaseTerm fields = '__all__' 2-I have api method in view @api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid): leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True) leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True) response = Response(leaseterm_serializer.data) return Response(response.data,status=status.HTTP_200_OK) 3-In my template I build it like this function getleaseterm() { //get a reference to the select element $select = $('#leaseterm'); //request the JSON data and parse into the select element var l_id = ($("select[name='lease'] option:selected").attr('value')); l_url = "/api/get_leaseterm/"+l_id+"/"; $.ajax({ url: l_url, dataType:'JSON', success:function(data1){ //clear the current content of the select $select.empty(); $select.append('<option value="-1">Select term </option>'); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('<option value="' + val.id + '">' + val + '</option>'); }) }, }); } Problem is that the "val" value I display in dropdown if I I don't specify what field I want to show will display [object Object] for all the values in dropdown when I want it to display description of object I … -
How to cache element position Django
Issue description: At my Django project user can change element position using JQuery UI selectable() function. What I want implement: I want to cached HTML divs after replace position. For example: User change element position. After refresh website elements position should be like user preferences. I read about template cache: https://docs.djangoproject.com/en/1.10/ref/templates/api/#django.template.loaders.cached.Loader Thanks in advance!