Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django login olduktan sonra grup seçmek
kullanıcıya atana birden fazla grup için login olduktan sonra grup seçimi yapıp o gruba ait izinler ile panelde dolaşmasını istiyorum. -
Django Model Boolean Field needs to be initially unchecked. initial=False required=False is not working
Forms.py class CheckPostedForm(forms.ModelForm): posted = forms.BooleanField(required=False, initial=False) Views.py postform = CheckPostedForm(request.POST, instance=created_author) if postform.is_valid(): postform.save() else: print 'Cannot save post form.' Models.py posted = models.CharField(max_length=2, blank=True, null=True) I want a checkbox which is initially unchecked and based on th value from DB i check/uncheck it. No matter what i do the form always comes out as checked="checked". <tr><th><label for="id_posted">Posted:</label></th><td><input checked="checked" id="id_posted" name="posted" type="checkbox" value="n" required /></td></tr> I have searched alot every where, the docs say that it should be initially false required=False if we want to apply conditions. -
Python/Django - Generating forms for models.
I have two questions concerning models and forms. 1) What is the best way to create automatically forms for the models? In the example below I have two models - ModelA and ModelB. I need forms for them - ModelAForm and ModelBForm. They should be defined automatically. I do not want to do it manually, because in the future I will add other models, and all the forms will look the same. I am thinking about creating special decorator for models and use modelform_factory. from django.db import models from django.forms import ModelForm class ModelA(models.Model): ... class ModelB(models.Model): ... class ModelAForm(ModelForm): class Meta: abstract = ModelA class ModelBForm(ModelForm): class Meta: abstract = ModelB 2) Assuming I am using only ModelForm forms, it is possible to find the form for the model? Example. I have two models ModelA and ModelB, and two forms ModelAForm and ModelBForm. I have instance of ModelA and I would like to identify proper form for this model which I will pass to template - in this case ModelAForm. -
Python Django Mandrill API response 500
Been asked to look at a server running an app called LibertyMusicStore which uses Python Django. https://github.com/miohtama/LibertyMusicStore The owner tried to update the SSL cert, I updated the cert for them but on the other side the app was not running. Looking at command history it seems that they may have restored an old backup (1 year) of the app over the top of the current one, they've yet to confirm this. The problem can be seen on this page, ignore the fact that SSL is not forced and that the SSL has lots of mixed content warnings if used, it makes no difference to the outcome. http://music.artbyte.me/musician-sign-up/ When signing up the form is replaced with the message "500 Server Error". mandrillapp.com is in ALLOWED_HOSTS and DEFAULT_FROM_EMAIL is set. I've spent hours on this and am not sure where to look next. The server set up is The following is in the log file /srv/django/applebytestore/LibertyMusicStore/logs/django.log. INFO 2017-01-28 09:07:48,278 connectionpool 86.142.174.63 - POST /signup/ HTTP/1.1" Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Starting new HTTP connection (1): mandrillapp.com ERROR 2017-01-28 09:07:48,418 base - - - - -" - Internal Server Error: /signup/ Traceback (most recent call last): … -
Model.objects.get() works, but not when using a ForeignKey attribute
I have a profile model that looks like this: class Profile(models.Model): username = models.ForeignKey(User, blank=True, null=True) age = models.IntegerField(default=0) points = models.IntegerField(default=100) def __str__(self): return str(self.username) Here's my template <h3><a href="{% url 'profile' u=i.user %}" class='username_foreign'>{{ i.user }}</a></h3> which points to this url: url(r'^profile/(?P<u>\w+)/', profile, name='profile') and here's my view function: def profile(request, u): if request.method == 'GET': profile = Profile.objects.get(username=u) return render(request, 'base.html', {}) As you can see here I pass through u which is the username. But when I try to get() the profile via the username passed through, I get this error: ValueError at /profile/zorgan/ invalid literal for int() with base 10: 'zorgan' However when I use get() on any other attribute of my Profile model, it works fine. And it even prints my username. So when I do this: def profile(request, u): if request.method == 'GET': print(u) #prints username profile = Profile.objects.get(points=50) print(profile.username) #successfully prints username (same as 'u') return render(request, 'base.html', {}) As you can see above, getting the Profile object via its attribute doesn't work for username. And the problem isn't related to the u as that successfully prints aswell. Any idea what the problem is? -
Quiz sytem model Field selection
I am creating a model for the Quiz-system in Django.There is Question and 5 options for each question. class Question(models.Model): Question=models.CharField(max_length=1000) option1=models.CharField(max_length=500) option2=models.CharField(max_length=500) option3=models.CharField(max_length=500) option4=models.CharField(max_length=500) option5=models.CharField(max_length=500) Here only one answer is the right answer.Which is the best way to represent the answer here? Is it by adding another field or is it can be done by editing one of the existing field? -
django rest framework - filter list of objects by filtering a list of objects
I have two models ItemCategory and Item, I want to filter the list of ItemCategory by filtering is_published field of item. class ItemCategory(models.Model): category_name = models.CharField(max_length=50, unique=True) category_image = models.ImageField(upload_to='item-category', null=True) def __str__(self): return 'category: ' + self.category_name class Item(models.Model): item_name = models.CharField(max_length=50) item_desc = models.CharField(max_length=500, blank=True) price = models.FloatField() item_image = models.ImageField(upload_to='item-images') num_of_items_available = models.IntegerField() category_name = models.ForeignKey(ItemCategory, on_delete=models.CASCADE, null=True, related_name='items') is_published = models.BooleanField(default=False) def __str__(self): return 'item: ' + self.item_name Here is my approach but didn't get any success. class ItemCategoryView(viewsets.ViewSet): permission_classes = (AllowAny,) serializer_class = ItemCategoryListSerializer def list(self, request, format=None): queryset = ItemCategory.objects.filter(items__in=Item.objects.filter(is_published=True)) serializer = ItemCategorySerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ItemCategorySerializer looks like this class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'item_name', 'item_desc', 'price', 'item_image', 'num_of_items_available', 'category_name', 'is_published') class ItemCategorySerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = ItemCategory fields = ('pk', 'category_name', 'category_image', 'items') Can anyone tell my how i can approach to this problem? -
Django admin nested form can't submit, connection was reset
I have a django nested admin form and below code is my admin.py file content: # -*- coding:utf-8 -*- from django.db.models import Q from django import forms from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib import admin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher from django.forms.utils import flatatt from django.utils.html import format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _, ugettext from django.contrib.auth.models import Group, Permission from nested_admin.nested import NestedStackedInline, NestedModelAdmin from HomeMakers.apps.system.models import Dependant, Benefit, User, \ Unit, Stack, Parking from mtools.fields import UniqueValueWidget, PersianDateField class DependantAdminForm(forms.ModelForm): model = Dependant birth_date = PersianDateField(label=u'تاریخ تولد') class DependantAdmin(NestedStackedInline): model = Dependant form = DependantAdminForm extra = 0 exclude = ['changed_status', 'new_obj'] can_delete = True class BenefitSubAdmin(admin.TabularInline): model = Benefit extra = 1 min_num = 0 exclude = ['changed_status', 'new_obj'] can_delete = True class NewUserAdminForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User username = forms.RegexField(label=u"کد ملی", max_length=30, regex=r'^\d{8,10}$', widget=UniqueValueWidget, error_messages={'invalid': u"مقدار وارد شده قابل قبول نمیباشد."}) birth_date = PersianDateField(from_year=1290, to_year=1400, label=_('Birth Date')) start_date = PersianDateField(from_year=1290, to_year=1400, label=u"تاریخ شروع به کار") def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] if User.objects.filter(username=username).count() … -
500 Error when starting Django on Apache with mod_wsgi
I'm getting 500 error while trying to start Django (1.10.5) on Apache (with mod_wsgi) using postgre DB. The installation dependencies are django and. psycopg2. They are installed on a Python 3.6 virtual environment. Hint: Everything works fine, when I try to start the virtual environment via "python manage.py runserver 0.0.0.0:8000" but when I try to reach the :80 port on apache the following error is listed in /var/log/httpd/error_log Handling WSGI exception Traceback (most recent call last): File "/root/djangotest/djangotest/wsgi.py", line 40, in <module> application = get_wsgi_application() File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/root/djangotest/djangotestvenv/lib/python3.6/site-packages/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, … -
Haystack SearchQuerySet return Empty object array
I m trying to make autocomplete api for one model in django. First time using haystack with elastic search. When i hit api SearchQuerySet return array of empty objects. models.py from __future__ import unicode_literals from django.db import models class Movie(models.Model): title = models.CharField(max_length=250) year = models.CharField(max_length=250) location = models.CharField(max_length=250) fun_fact = models.CharField(max_length=250, null=True) production_company = models.CharField(max_length=250) director = models.CharField(max_length=250) actor1 = models.CharField(max_length=250) actor2 = models.CharField(max_length=250, null=True) actor3 = models.CharField(max_length=250, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6) latitude = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.title search_indexes.py from haystack import indexes from models import Movie class MovieIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) year = indexes.CharField(model_attr='year') content_auto = indexes.EdgeNgramField(model_attr='title') def get_model(self): return Movie def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() views.py from django.shortcuts import render # Create your views here. import json from django.http import HttpResponse from haystack.query import SearchQuerySet def autocomplete(request): sqs = SearchQuerySet().all() suggestions = [result.title for result in sqs] # Make sure you return a JSON object, not a bare list. # Otherwise, you could be vulnerable to an XSS attack. the_data = json.dumps({ 'results': suggestions }) return HttpResponse(the_data, content_type='application/json') movie_text.txt {{ object.title }} {{ object.year }} {{ object.production_company }} {{ object.director }} Indexing is … -
Django : Assigning initial values to fields of a form in a subclass of ModelAdmin
I am not sure how to assign values to fields in the form when it is presented to the user through the Admin App.What I am trying to do is present a form to the user in which the field called user is already assigned a value and is disabled (cannot be changed) if possible. Following are my models class modelStudent(models.Model): class Meta: verbose_name_plural = "Enrolled Students" #Name to display in admin interface user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) school = models.ForeignKey(modelSchool) first_name = models.CharField(max_length=128, unique=False) student_email = models.EmailField(unique=True, blank=False) class modelStudentAdminForm(forms.ModelForm): class Meta: model = modelStudent exclude = ['student_email'] Now this is the admin class for the admin form class modelStudentAdmin(admin.ModelAdmin): form = modelStudentAdminForm #Only display students that belong to this user def get_queryset(self, request): qs = super(modelStudentAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: # Get the school instance schoolInstance = modelSchool.objects.get(user=request.user) qs = modelStudent.objects.filter(school=schoolInstance) return qs def get_form(self, request, obj=None, **kwargs): #modelStudentAdmin.form.initial={"first_name":"JoeJoe"} return modelStudentAdmin.form In this case it says 'NoneType' object does not support item assignment I have tried assigning a value to a form field and was unable to do so. So my question is how can i mark a field as readonly in the form and assign … -
OperationalError from Django when adding a unicode string to my database
I've got a TextField in one of my models. I tried inserting a string of Japanse characters into the database and I got this error: OperationalError at /admin/pages/page/add/ (1366, "Incorrect string value: '\\xE3\\x83\\x91\\xE3\\x83\\xAF...' for column 'body' at row 1") I thought that Django, Python, and MySQL supported Unicode and uses it first. What is going on and how can I fix it? -
The page load, but didn't show up the content
I'm trying to connect to the server with IP_address_server:8000, but the page load without ever wanting to connect. In fact, I start a Django project, and I did python3 manage.py runserver 0.0.0.0:8000. In the project settings, I've included IP_address_server in ALLOWED_HOSTS, but I got the same issue. Could anyone be able to tell me what could be the problem? -
How to replace "/" whit "-" in Django DateField Form?
I have created the from with this DateField: registery_date = forms.DateField(widget=forms.DateInput(), initial=datetime.date.today()) this form only accept YYYY-MM-DD format but i use a javascript code in template that it create YYYY/MM/DD date format. so the datefield is unuseable how can i replace / Instead - in date form? -
What is the most efficient way for a mobile app to utilize an API being served on Google App Engine?
I am in the research stage of building my first app. I am a complete noob and the amount of information for all the different approaches in building an app is relatively overwhelming. My situation is that I currently have a web project being served by Google App Engine. This web project connects customers to a subscription-based portal. I used Django and its RESTful API as the backend. Now I've decided I want to create a hybrid app that utilizes the current REST API I have set up for the web project since the app will be accessing the same databases and authentication methods. However, I'm not sure what the best approach is in taking on this task. So far I've read a lot about Firebase and all its features, but it seems to offer more than what I currently need. I also read about Google Cloud Endpoints. The one that seems to be the most desirable is connecting directly to my Rest API, but I am getting the impression that this is only doable in Google Compute Engine. So for anyone out there who has experience with these various interfaces, what are the pros and cons of each of … -
How to do a reverse lookup in a get_queryset method
I currently have the following models in my application class modelSchool(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) class modelStudent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) school = models.ForeignKey(modelSchool) Now in my admin.py I have the following code. Basically I would like to only show each school their own students for that reason I am filtering the queryset. This is what my code looks like class modelStudentAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(modelStudentAdmin, self).get_queryset(request) if request.user.is_superuser: return qs admin.site.register(modelStudent,modelStudentAdmin) My question is how do I filter the query set to get the corresponding school instance and then filter that out to get all the students of that school ? -
How do I use python-social-auth with email addresses not username
I want to use python-social-login but with email addresses and not usernames. I have my Django set up using a Custom user model that works. I know that some social sites won't give you email addresses, but I will only use the ones that will. Currently- I get an error message when I try to login with Facebook oauth. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'username' is an invalid keyword argument for this function -
disable ssl forwarding in django local_settings
I'm using django, and my deployed version of the site on heroku works fine. I'm now using a new computer, and lost my local_settings.py file. Now I'm not sure what I need to put in my local_settings.py file in order for to work on the site locally. Currently http://0.0.0.0:5000 redirects to https://0.0.0.0/ and says "unable to connect" This is what I have tried so far to no avail in local_settings.py: DEBUG = True SECURE_SSL_REDIRECT = False ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]'] SSLIFY_DISABLE = True SESSION_COOKIE_SECURE = False I import it as follows: try: from .local_settings import * except ImportError as e: print "Production Environment" pass I use whitenoise for storage, and SSLify to force https requests. Any help is appreciated! -
Ajax call on Django returns 403 58 unless logged in
It seems that getting a 403 with Ajax on Django is a common problem. I've tried several of the solutions on stackoverflow and they fixed the CSRF problem. Now I'm able to login, signup and logout users through Ajax as long as I'm already logged in on the Django admin. Of course, I need to be able to perform this operations while not being already logged in. I have separated all the auth functionality into a session app. session.views: session.urls: "DjangoProject".urls: What can I do to be able to post session data through Ajax without already being logged in on the admin? -
how process static file when deploying django using docker and aws eb
I used Django, Docker and AWS Elastic Beanstalk to employ my website. I followed the instruction of https://github.com/glynjackson/django-docker-template. I met problem when I try to load static file, the browser try to visit mysite.com/static/css/xx.css to get the css and javascipt file which is different with what I run it locally. In settings.py: STATIC_URL = '/static/' STATIC_ROOT = 'static' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) I also used: # !/bin/sh cd /var/projects/mysite && python manage.py migrate --noinput && python manage.py collectstatic --noinput supervisord -n -c /etc/supervisor/supervisord.conf Currently, I write additional views and urls for javascript and css file. So browser can get these file from url. But how to do it correctly? -
Python/ Django Key already exists. Postgres
I Have a project built in django and it uses a postgres database. This database was populated by CSVs files. So when I want to insert a new object I got the error "duplicated key" because the object with id = 1 already exists. The code : user = User(name= "Foo") user.save() How can I save the user with an id that is not being used? -
Autocomplete is not working Haystack with elastic search
I m trying to make autocomplete api for one model in django. First time using haystack with elastic search. Getting error while trying to get autocomplete results. Failed to query Elasticsearch using 'content_auto:(Jitney)': TransportError(400, u'parsing_exception', u'[query_string] query does not support [fuzzy_min_sim]') models.py from __future__ import unicode_literals from django.db import models class Movie(models.Model): title = models.CharField(max_length=250) year = models.CharField(max_length=250) location = models.CharField(max_length=250) fun_fact = models.CharField(max_length=250, null=True) production_company = models.CharField(max_length=250) director = models.CharField(max_length=250) actor1 = models.CharField(max_length=250) actor2 = models.CharField(max_length=250, null=True) actor3 = models.CharField(max_length=250, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6) latitude = models.DecimalField(max_digits=9, decimal_places=6) class Meta: db_table = "sf_movies" def __str__(self): return self.title search.py from haystack import indexes from models import Movie class MovieIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) year = indexes.CharField(model_attr='year') content_auto = indexes.EdgeNgramField(model_attr='title') def get_model(self): return Movie def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() views.py from django.shortcuts import render # Create your views here. import json from django.http import HttpResponse from haystack.query import SearchQuerySet def autocomplete(request): sqs = SearchQuerySet().autocomplete(content_auto=request.GET.get('q', ''))[:5] suggestions = [result.title for result in sqs] # Make sure you return a JSON object, not a bare list. # Otherwise, you could be vulnerable to an XSS attack. the_data = json.dumps({ 'results': suggestions }) … -
Django makes two <select> instead of one, trying to use Bootstrap (Form upload)
So I'm trying to make a website with django and I'm running into a problem where when i create a select list, two shows up. Html: <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <select class="form-control"> {% for course in form.courseChoices %} <option value="{{course}}">{{course}}</option> {% endfor %} </select> <!--div class="col-lg-6 col-sm-6 col-12" id="upload_form" --> <label class="btn btn-block btn-primary"> {{ form.document }} <input type="file" style="display: none; width: 100%;" > </label> </div> </form> This is what is looks like here My form is just a simple ModelForm with a couple fields. forms.py class FileForm(forms.ModelForm): class Meta: model = FileUploads fields = ('semesterChoices', 'document', 'courseChoices',) Here is what my model looks like class FileUploads(models.Model): semestersList = ['Spring 2017', 'Fall 2016', 'Spring 2016', 'Fall 2015', 'Spring 2015', 'Fall 2014', 'Spring 2014', 'Fall 2013'] with open('polls/courses.txt', 'r') as f: coursesList = [line.strip() for line in f] semesters = [(option, option) for option in semestersList] courses = [(course, course) for course in coursesList] semesterChoices = models.CharField(max_length=20, choices=semesters, default="Spring 2017") courseChoices = models.CharField(max_length=20, choices=courses, default="ACCT Accounting") document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) I just want the bootstrap select, but it seems that whatever value is passed into it doesn't really matter, it takes the second select … -
Error trying to serve user uploaded files locally
I'm trying to serve user-uploaded images locally on Django 1.10. I'm following the documentation here and getting this error: SystemCheckError: System check identified some issues: Your URL pattern [<RegexURLPattern None ^media\/(?P<path>.*)$>] is invalid. Ensure that urlpatterns is a list of url() instances. The issue is from adding the static portion of my urls: urlpatterns = [ ...my urls... ] if settings.DEBUG: # This is causing the error. urlpatterns += [ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ] When I remove the static addition to my urls, the error goes away. What am I doing wrong here? My applicable settings are as follows: BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = BASE_DIR + "/static/" STATIC_URL = "/static/" MEDIA_ROOT = BASE_DIR + "/media/" MEDIA_URL = "/media/" -
Pycharm Error -1073741819 (0xC0000005)
I use Pycharm Pro 2016.3, Win 10 and get an error when running the project Process finished with exit code -1073741819 (0xC0000005) Unless the number of times to restart the project (more than 5 times) the project is started. Resets Pycharm, did not help