Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'list' object has no attribute 'queryset' error when adding a autocomplete field to a crispy-forms model.form
I want to add an another autocomplete field to my model.form. However, as soon as I add the autocomplete widget for the field "projektnummer" 'projektnummer': autocomplete.ModelSelect2(url='output:projekt-form-autocomplete'), I get an wired template error I cannot make sense of. Do you have some ideas what I can do here? Thank you very much! :) error message: AttributeError at /output/create/ 'list' object has no attribute 'queryset' Request Method: GET Request URL: http://127.0.0.1:8000/output/create/ Django Version: 1.8.7 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'queryset' Error during template rendering In template /home/bjoern/Developement/Django/Outputmeldetool/venv_outputmeldetool/lib/python3.5/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28 28 {% if field|is_checkbox and form_show_labels %} forms.py class KombiPublikationForm(forms.ModelForm): typtyp = forms.ModelChoiceField(label='Vorauswahl Outputtyp', required = False, queryset=KombiPublikationsTypTyp.objects.exclude(id__in=EXCLUDED_TYPTYP) ) class Meta: model = KombiPublikation exclude = ['pub_sprache'] widgets = { 'freigabe': DateTimePicker(options={"format": "YYYY-MM-DD HH:mm", 'sideBySide': True}), 'typid': autocomplete.ModelSelect2(url='output:typ-autocomplete', forward=['typtyp']), #adding following line generates the error: 'projektnummer': autocomplete.ModelSelect2(url='output:projekt-form-autocomplete'), 'monat': forms.NumberInput(), } def __init__(self, *args, **kwargs): super(KombiPublikationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.help_text_inline = True self.helper.form_tag = False self.helper.layout = Layout( #a lot of layout stuff is here ) -
Django Windows Authentication
Similar to this question: How to use windows authentication to connect to MS SQL server from windows workstation in another domain with Python My current database configurations looks like this: 'default': { 'ENGINE': "sql_server.pyodbc", 'HOST': "myServer\server1", 'USER': "myUserName", 'PASSWORD': "myPassWord", 'NAME': "myDB" However, I would like to pass through Windows Authentication so that I can keep track of who is making changes to the DB. I have Windows Authentication enabled through IIS, so users are prompted to login when they visit my app. I have tried this, but it did not work: 'default': { 'ENGINE': "sql_server.pyodbc", 'HOST': "myServer\server1", 'trusted_connection': 'yes' 'NAME': "myDB" Is there a way to pass through windows authentication to the Django database settings? -
Best method for separation of ADMIN and USERS entries in a database table
lets say i have separate table for users and admins users : username , password , email , name admins : username , password , level now i have a table that both users and admins can insert data in ... like a website for selling books : books : title , price so 3 methods comes to mind method 1 - adding 2 filds to books table for admin and user books : title , price , user_id , admin_id ----> some title , 1000 , 5 , -1 // user posted book ----> some other title , 2000 , -1 , 12 // admin posted book when user insert a book i'll save his id in user_id and put -1 for admin_idand vise versa for admin method 2 - saving user_id = -1 for admin entries books : title , price , user_id ----> some title , 1000 , 5 // user posted book ----> some other title , 2000 , -1 // admin posted book method 3 - having a user in the users table to represent admins and save all admin entries with this user id -- which doesn't feel like smart thing to do ! β¦ -
my django looks like can`t recognize the templates
i am a noob learning python,when i learning the template of django,i met some mistakes;what i am using is pycharm2016.2.3 ,python3.5.2,django1.10.1 here is my dir list: β db.sqlite3 β manage.py ββdjangotest β β settings.py β β urls.py β β view.py β β wsgi.py β β __init__.py β ββtemplates hello.html the url.py: from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] the setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, the hello.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>temtest</title> </head> <body> <h1>{{ hello }}</h1> </body> </html> the view.py: #coding:utf-8 from django.http import HttpResponse from django.shortcuts import render def hello(request): context = {} context['hello'] = 'yes i am' return render(request,'hello.html',context) def first_page(request): info = 'on yes' return HttpResponse(info) when i run and type 127.0.0.1:8000 i can open it successfully, but when i type 127.0.0.1:8000/hello ,it show me this:enter image description here it seems like that the templates can`t be recognized. can somebody do me a flavor? thank you! -
Django isn't finding my files in media/
I am trying to create a webpage where users can fill out a form and email me their name, email address, a message, and an image. My issue is getting the image attached to the email. When the code runs, the image is uploaded to my media root along with my other media files, but it throws an FileNotFoundError [Errno 2] No such file or directory: 'media/2016/10/14/image.png' Here's my models.py: class UploadedImage(models.Model): uImage = models.FileField(upload_to='media/%Y/%m/%d') forms.py: class QuoteForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) uImage = forms.FileField(required=False, help_text='5mb max.') message = forms.CharField(widget=forms.Textarea) views.py: def quote(request): form = QuoteForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] subject = "Quote" message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message newImage = UploadedImage(uImage = request.FILES['uImage']) newImage.save() msg = EmailMessage(subject, message, from_email, ['zbloss@emich.edu'], reply_to=[from_email]) image_url = newImage.uImage.url msg.attach_file(image_url) try: msg.send() except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('/thankyou') return render(request, "quote.html", {'form': form}) -
Django add field to auth_user
I am trying to implement the above to add a field 'posts' to the user model using the first option, extended it. models.py from django.contrib.auth.models import User class NewUserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) posts = models.IntegerField(default=0) views.py def site_users(request): site_users = User.objects.all().reverse() paginator = Paginator(site_users, 10) page = request.GET.get('page') try: users_model = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. users_model = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. users_model = paginator.page(paginator.num_pages) return render(request, 'site_users.html', {'users_model': users_model, 'current_time': timezone.now()}) But how can I get the posts field in the template, {% for item in users_model %} <tr> <td><a href="{% url 'profile' item.id %}">{{ item.username }}</a></td> <td>{{ item.posts }}</td> <td></td> <td></td> </tr> {% endfor %} Thanks, -
How to change values in database at a specific time
I'm trying to change values of a column in a table in a database at a specified time without having to do it manually. Is there a way to achieve this? If yes, wouldn't mind an example or something. Thanks!! :) ps. I'm using django with sqlite (using sqlite just because it comes with django as a default and I'm still learning django) -
add boostrap template in django
I download a boostrap template from https://startbootstrap.com/, this is basically a set of html, css and js files. I would like to open it in a django project. I created an app called main, and also a templates folder in the root of the project. So, it looks like: proj/main proj/templates/main/[downloaded files] the index file is located in: proj/templates/main/index.html in the main/views.py file I added: from django.shortcuts import render def index(request): return render(request, 'main/index.html') I defined also a template folder in settings.py: TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The main/urls.py is: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] when I entered the url http://192.168.226.128/main/ I have the message: The current URL, main/pages/index.html, didn't match any of these. Why is this happening? What can I do for opening the files? Thanks -
Unable to get post value from select after POST in Django
Hello everyone I am new to Django and I have tried a bunch of different approaches I have found online yet I still cannot get the value from my select dropdown after POST. Even after I hardcoded the value as 1 just to test it I still wasn't able to get the value. The dropdown is getting populated correctly which means {{ d.name }} works. Originally I had the value set to {{ d.name }} as well. I did not use forms.ChoiceField as I wasn't aware of this yet when I made my form. Here is my code: forms.py class MyForm(forms.ModelForm): class Meta: model = MyList fields = ['field1', 'field2', 'field3' ] Template: <div class="form-group pull-right"> <label class="control-label" for="apply"> Apply: </label> <select class="span4" name="apply" id="apply"> {% for d in devs %} <option name="somename" value=1>{{ d.name }}</option> {% endfor %} </select> </div> views.py def View(request): if request.method == "POST": form = MyForm(request.POST or None) if form.is_valid(): print(request.POST["apply"]) Thank you in advance for all your help. -
Why does Django not find the admin/base_site.html file when I dockerize the app?
I've downloaded this Django app and put it in a docker container. However, I get the error "admin/base_site.html" not found. If I open a shell on the container and do find /|grep base_site I see the file is correctly installed in /usr/local/django/contrib/admin/templates/admin/base_site.html The code I'm referring to can be found in https://github.com/DDecoene/bots Could you be so kind and take a look? I've busted my head over this for a day and can't figure it out, nor find anything on Google that is even remotely related. Thanks! -
django: which packages to use for billing plans, stripe and invoicing
I want to add stripe based recurring payments, pdf invoice generation for each of those and 3 billing plans for a SaaS product. I'm using django/python: which packages are the best to glue together for this purpose. -
MySQL-python module cannot be installed with Pip in windows
I tried to install MySQL-python module but i got the following error: Sorry for the long code but i really hv no idea what to make sense of it. I run pip install python, pip install Django, etc. started a project andd created app... now i wanted to conenct to mysql database. D:\>pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Running setup.py bdist_wheel for MySQL-python ... error Complete output from command c:\python35-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Adrian\\AppData\\Local\\Temp\\pip-build-mrwh3am4\\MySQL-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\Adrian\AppData\Local\Temp\tmpjlbwqr27pip-wheel- --python-tag cp35: running bdist_wheel running build running build_py creating build creating build\lib.win32-3.5 copying _mysql_exceptions.py -> build\lib.win32-3.5 creating build\lib.win32-3.5\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.5\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.5\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.5\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.5\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.5\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.5\MySQLdb creating build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.5\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.5\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.5 creating build\temp.win32-3.5\Release C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python35-32\include -Ic:\python35-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio β¦ -
Reorganizer Project in django-CMS
Hi everyone I have a project works with this characteristic! Django==1.8.14 django-cms==3.2.5 Python 2.7.12 my project work fine, but now I am trying to reorganizer my apps Right now I have something like this in my case api_cpujobs, APIchart, drawChart, cms_extensions and readRSS are apps, so to reorganizer I create a folder inside portal calls apps and move there my apps. I modified my setting.py so now I have this 'portal', 'portal.apps.APIchart', 'portal.apps.drawChart', 'portal.apps.readRSS', 'portal.apps.cms_extensions', But when I start the server I obtain this error ImportError: No module named apps I look for in internet and even other tutorial have the same organization, but I don't find what am I missing? Thank in advice! -
Python VBA-like left()
I've been looking around but don't see anything similar to what I'm looking for. Within a django site I want to add some code that looks at a values furthest left (or the first) character in a variable (which is populated by a DB query), and if it's a particular letter or number, do something with said variable. How can I do this? -
Cant find module Django while deploying on Elastic Beanstalk
I am trying to deploy the backend of this repository https://github.com/LaunchKit/LaunchKit on Elastic Beanstalk. I am very new to Django and I successfully did those two tutorials explaining how to deploy Django on Elastic Beanstalk: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/ I keep having the message ImportError: No module named 'django' Here is a part of my file structure located into the folder "firekit" βββ LICENSE βββ README.md βββ backend β βββ __init__.py β βββ __init__.pyc β βββ celery_app.py β βββ celery_app.pyc β βββ lk β β βββ __init__.py β β βββ __init__.pyc β β βββ logic β β βββ migrations β β βββ models β β βββ oauth_middleware.py β β βββ oauth_middleware.pyc β β βββ tasks.py β β βββ templates β β βββ templatetags β β βββ urls.py β β βββ urls.pyc β β βββ views β βββ manage.py β βββ middleware.py β βββ middleware.pyc β βββ requirements.txt β βββ settings.py β βββ settings.pyc β βββ site_media β β βββ images -> ../../skit/lk/__static__/images β βββ templates β β βββ robots.txt β βββ urls.py β βββ urls.pyc β βββ util β β βββ __init__.py β β βββ __init__.pyc β β βββ bitwise.py β β βββ bitwise.pyc β β βββ cryptoid.py β β βββ cryptoid.pyc β¦ -
multiple domains - one django project
I want to run ONE django project on multiple domains/websites. The websites each need to access a unique "urls.py"/"views.py". I tried it already with this tutorial, but it doesn't work for me. Is there a way to do this with middleware in an easy way (without the Sites framework)? A little bit of help would be really great. Thanks. -
Django allauth redirecting to localhost from production
I have implemented django all auth and it works fine in devlopment. In production the redirect uri changes to redirect_uri=http://localhost/accounts/google/login/callback/. I am using gunicorn with nginx and tried setting proxy_set_header Host $http_host; in the nginx configuration as well. How do I set the redirect uri to http://example.com/accounts/google/login/callback/? -
Combine model fields
I would like to add a field to a read-only database. So, I would like to create a dummy database of the form; class ReadOnly(models.Model): first = models.CharField(db_column='First') second = models.CharField(db_column='Second') class ExtraStuff(models.Model): first = models.CharField(db_column='First') second = models.CharField(db_column='Second') combined = first+second I have used the @property but as I cannot combine properties and filters I feel like this is a better solution. However, I am out of ideas for how to achieve this. -
Django POST does not return all elements of the zipped list
I have a class view with both get and post methods. In the get method, I have these items: items = Item.objects.filter(user = the_user) item_pricing_forms = [] # list of forms item_component_formsets = [] # list of inline formsets for item in items: item_pricing_form = ItemPricingForm() item_pricing_forms.append(item_pricing_form) item_component_formset = inlineformset_factory(Item, Component, form = ComponentForm, can_delete = False, extra = item.num_of_components) item_component_formsets.append(item_component_formset) then, I zip them into one variable zipped_item_pricing_components = zip(items, item_pricing_forms, item_component_formsets) In my template: <form action = "" method = "post"> {% csrf_token %} <table> {% for item, item_pricing_form, item_components_formset in zipped_item_pricing_components %} <tr><th>Item {{item}}</th></tr> {{ item_pricing_form }} {{ item_components_formsets.management_form }} {% for item_components_formset in item_components_formsets }} {{item_components_formset }} {% endfor %} {% endfor %} <tr><td> <input type="submit" value="Submit"> </td></tr> </table> </form> This renders fine in the get request. However, when the post request is passed, I can only see the last element of each list. So, if I do assert False somewhere in the beginning of my POST view, the POST data has the information for the last element of each list (e.g. the last element of it item_pricing_forms and the last item of item_component_formsets. Why does Django not returning the full list? What am I doing β¦ -
how to use webcam for face-detection in web page using OpenCV and python with django server
I am using OpenCV library for Face-detection with Python. I am using Django as my server. And I am sending images for face-detection via curl. Actually I followed this tutorial. It's working fine but I want to integrate OpenCV with my web page so that I can detect faces directly from my web app using my laptop's webcam, something like this image. I want some tutorial or examples to do that. But I am preferring Python for server-side and Javascript for client-side. Any kind of technic or example will be helpful. Thank you. -
I can not run a server on Django
I have a problem: after the python manage.py runserver command I receive the following error which I can not solve: Unhandled exception in thread started by <function wrapper at 0xb6712e64> Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/usr/lib/python2.7/dist-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/usr/lib/python2.7/dist-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/usr/lib/python2.7/dist-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/redactor/admin.py", line 3, in <module> from redactor.widgets import JQueryEditor ImportError: cannot import name JQueryEditor How can I solve this problem? Many where we recommend that you sudo easy_install pip the team, but it did not help. -
Reducing the amount of results from a Django query
I am trying to reduce the amount of events I get from a query on a table in mysql which has a lot of events stored in it. There is roughly one event each minute, each event has a datetime and then some other sensor readings. I would like to reduce the amount of data so that I'm only getting one reading every hour or so. I realise I can do something like: IncomingData.objects.filter(utctime__range=('2016-10-07', '2016-10-14'))[::60] This will give me 1 event an hour (assuming they are ordered by time?) but I am still reading 60 events an hour from the database. Potentially I might want to read a bigger date range and less events. I have seen some solutions using ROWNUM but I want to keep away from raw sql if possible. -
How to configure nginx for django with gunicorn?
I have successfully run gunicorn and confirmed that my web runs on localhost:8000. But I can't get nginx right. My config file goes like this: server { listen 80; server_name 104.224.149.42; location / { proxy_pass http://127.0.0.1:8000; } } 104.224.149.42 is the ip for outside world. -
Virtual environment not recognized in WSGIPythonPath
I'm trying to set up my Django project in production by using a virtual environment, using the documentation: https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/#using-a-virtualenv So, in my configuration I have: WSGIPythonPath /srv/zboss/zboss:/srv/zboss/venv/lib/python3.4/site-packages I restart Apache and I get the following error: Internal Server Error: /prot/ InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'core.templatetags.wiki_formatter': No module named parse Request Method: GET Request URL: http://babylon/prot/ Django Version: 1.10.1 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/srv/zboss/zboss'] However the error is something because that library is not used anymore in Python3. I see the python path and no trace of my virtual environment directory. -
Django IntegrityError not-null and foreignKey
Im trying to make some simple relations but it seems I've missed something. These are my models class Ability(models.Model): name = models.CharField(max_length=200) id = models.AutoField(primary_key=True) def __str__(self): return self.name class Hero(models.Model): hero_name = models.CharField(max_length=100, primary_key=True) portrait_link = models.CharField(max_length=200) ability = models.ForeignKey(Ability, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.hero_name When trying to add a new Ability through the admin interface, I get the following: IntegrityError at /admin/patch/ability/add/ null value in column "owner_id" violates not-null constraint DETAIL: Failing row contains (5, Blade Fury, null). Request Method: POST Request URL: http://127.0.0.1:8000/admin/patch/ability/add/ Django Version: 1.10.2 Exception Type: IntegrityError Exception Value: null value in column "owner_id" violates not-null constraint DETAIL: Failing row contains (5, throw banana, null). Exception Location: C:\Python27\lib\site-packages\django\db\backends\utils.py in execute, line 64 Python Executable: C:\Python27\python.EXE Python Version: 2.7.10 What am I doing here? I tried adding the id fields since django complained there was no ID field. However, I can't get around the not-null issue..