Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use elasticsearch in Wagtail CMS?
Can anyone give a brief tutorial on 'how to implement elasticsearch in wagtail cms.' i am new at both wagtail and elastic search. i have gone through the documentation of implementing search in wagtail > http://docs.wagtail.io/en/v1.8.1/topics/search/index.html but couldn't help myself out. -
CSS Background Image WILL NOT Load
apologies in advance, as I am relatively new to programming. I'm trying to load an image to my page and set it as my background, below is the css and html that I am working with. The CSS page seems to load, as my test font and background colors show up. For whatever reason my background image WILL NOT, i've looked all over the web for an answer and have spent too long trying to figure this out. I am using Django as my web application by the way. Appreciate the help!!! HTML: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>Test</title> <meta charset="utf-8" /> <link rel="stylesheet" href="{% static 'personal/css/frontpagebackground.css' %}" type = "text/css"/> </head> <body> <p>This is a test</p> </body> </html> CSS: body { background-image:url(personal/static/personal/img/home.jpg) no-repeat; background-repeat:no-repeat; background-size:100%; background-color: green; min-height: 100%; } p { font-style: italic; color: red; } -
how to aligin fields django cms plugin
When I click to add new plugin in django cms, fields in plugin admin style are positioned vertical as default. I've got an app, lets call it "test". I changed changed test/admin.py in my app.If i go in django admin i see horizontal aligned fields. When i click add plugin(django cms), fields aren't aligned horizontal. How can I change django cms plugin style too? admin.py @admin.register(models.Projects) class FlatPageAdmin(admin.ModelAdmin): fields = (('image','service'),'text') -
Get a value error when I submit a post form in Django
I am trying to make a submit form for a django based web app i am building. However, when I press submit I get this error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create Django Version: 1.10.5 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'bootstrap3'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/wtreston/GDrive/Django/blog/posts/views.py" in post_create 15. instance = form.save(commit=False) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/models.py" in save 448. 'created' if self.instance._state.adding else 'changed', Exception Type: ValueError at /create Exception Value: The Post could not be created because the data didn't validate. This is my html file for the create form: {% extends "base.html" %} {% block title %}Create new Post | {{ block.super}}{% endblock title %} {% block content %} <h1>Create Post</h1> <form method = 'POST' action = '' class = 'form'>{% csrf_token %} <div class="form-group"> <label for="post_title">Post Title</label> <input class="form-control" id="post_title" placeholder="Post Title"> </div> <div class="form-group"> <label for="post_content">Post Content</label> <textarea class="form-control" rows="6" placeholder="Post Content"></textarea> </div> <!--<div class="form-group"> <label for="exampleInputFile">File input</label> <input type="file" id="exampleInputFile"> </div>--> <button type="submit" name="your_name" value="your_value" … -
Please tell me how to deploy Django application to EC2 of AWS
Premise · What you want to realize I would like to deploy django application to EC2 of AWS. The server uses nginx. I am also trying to do with uWSGI. The virtual environment is made with virtualenv. Thank you. Problems occurring · Error messages The process of nginx, wsgi is running, but localhost can not run the application. If I hit curl it will get Internal Server Error. log !!! no internal routing support, rebuild with pcre support !!! chdir() to /opt/app/apolo_api your processes number limit is 3896 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: enabled uWSGI http bound on :5001 fd 3 uwsgi socket 0 bound to UNIX address /tmp/uwsgi.sock fd 6 Python version: 3.5.1 (default, Sep 13 2016, 18:48:37) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] Set PythonHome to /opt/app/venv/ Python main interpreter initialized at 0x225ace0 python threads support enabled your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 166112 bytes (162 KB) for 2 cores * Operational MODE: threaded * added /opt/app/apolo_api/api/ to pythonpath. unable to load app 0 (mountpoint='') (callable not found … -
django how to populate a drop down list with two values from the same row in a database
I am trying to populate a drop down list in django with two values from the same row. expected output Product category - product name actual output product name forms.py class AddproductForm(ModelForm): class Meta: model = product fields = [ 'category','name'] products.html {{ form.category.form.name}} -
Django: sending e-mail with ajax - security issue
I am working with Django and after few tasks that require ajax calls I would like to send an email: $.when($.ajax({ type: "POST", url: "{% url 'check_status' %}, data: {'params':'data'}, }), ).then(function(){ $.ajax({ type: "POST", url: "{% url 'send_email' %}", data: {'email': email} }); }); I have set up CSRF tokens and the requests are post. However, I am concern with that somebody can use my send_email view to send unwanted e-mails. I would like to restrict the view to be used only for this given template/context not eg. from python requests library. Is it even possible? -
Django-star-ratings model and queryset sorting
New to Django and was hoping to get a little help with integrating the django-star-ratings module. As per the README I have the model: class Post(models.Model): date= models.DateTimeField() title = models.CharField(max_length = 140) artist= models.CharField(max_length = 140) ratings = GenericRelation(Rating, related_query_name='foos') and I'm not entirely sure how sorting the queryset works so I plugged url(r'^$', ListView.as_view(queryset=Post.objects.filter(ratings__isnull=False).order_by('ratings__average'), template_name="UploadApp/upload.html")), as a listview into my urls.py to pass the view . My first question is: even after making migrations, the new ratings field is not showing up in my admin. Any ideas on where I've gone wrong? Second question: have I done the listview sorting bit right? Any help is appreciated! -
Django countries adding cities to top of list
Using django-countries which works as expected with django, is it possible to add a list of cities to the top of the countries list, instead of getting all the countries and populating a new country model. -
Revoking tokens using Django rest-framework-jwt
I'm thinking of allowing a user to revoke previously issued tokens (yes, even though they are set to expire in 15 minutes), but did not find any way to do so using DRF-jwt. Right now, I'm considering several options: Hope someone on SO will show me how to do this out-of-the-box ;-) Use the jti field as a counter, and, upon revocation, require jti > last jti. Add user-level salt to the signing procedure, and change it upon revocation Store live tokens in some Redis DB Is any of the above the way to go? -
django sending email not show up in inbox
I am sending email with django with company local host address. When I get data from form and send them, it shows up in terminal, but not being received in inbox. I checked both company and gmail emails,result is same. #settings EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST_USER = '---' EMAIL_HOST_USERNAME = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 25 EMAIL_USE_TLS = False view def contact(request): title = "Content" form = contactForm(request.POST or None) context = {'title': title, 'form': form,} if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = "Thanks" message = "%s %s" % (comment, name) emailTo = [form.cleaned_data['email']] emailFrom = settings.EMAIL_HOST_USER send_mail( subject, message, emailFrom, emailTo, fail_silently=False, ) title = "Thanks" confirm_message = "Thanks for the message. We will get right back to you." template = "contact.html" return render(request,template,context) inTerminal ------------------------------------------------------------------------------- [08/Feb/2017 07:53:13] "POST /contact/ HTTP/1.1" 200 7666 MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: #subject From: #host address To: #receiver address Date: Wed, 08 Feb 2017 07:53:20 -0000 Message-ID: <-----.----.---- @natiq-macbook-pro.local> # Message ------------------------------------------------------------------------------- -
tuple object has no attribute 'stripe_customer_key in webhook
hi iam tring to process a stripe webhook when i run into this issue AttributeError: tuple object has no attribute 'stripe_customer_key my code is: dash_user.stripe_customer_key = event_json['data']['object']['subscriptions']['data'][0]['customer'] -
Print a template with forms and input to PDF in Django
I'm trying to display a template which has multiple Django forms on it (where users can add comments to a specific section). Then, when they hit a submit button, that template and form data is saved as a PDF to a FileField in the model. My initial inclination is to use a button to kick off the POST request, pull the form information out of it, then create a new request to the template with the form initialized to the data that was pulled out in the post request, and just render that as a PDF using reportlabs or something like that. However, I seem to be struggling to implement it in code, any suggestions? I'm using Django 1.10 and Python3. Thanks! -
Django URL regex with variables
Was hoping someone could point me in the right direction with this. I've tried nearly everything I can think of, but I can't seem to get it to work. I've got a set of URLs I'd like to match in Django: www.something.com/django/tabs/ www.something.com/django/tabs/?id=1 Basically, I want to make it so that when you just visit www.something.com/django/tabs/ it takes you to a splash page where you can browse through stuff. When you visit the second URL however, it takes you to a specific page which you can browse to from the first URL. This page is rendered based on an object in the database, which is why the id number is there. I've tried to account for this in the URL regex, but nothing I try seems to work. They all just take me to the main page. This is what I have in urls.py within the main site folder: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^tabs/', include("tabs.urls")), ] and within urls.py in the app's folder: urlpatterns = [ url(r'\?id=\d+$', tab), url(r'^$', alltabs) ] Would anyone be so kind as to point me in the right direction? Thanks in advance! -
Django ManyToManyField Admin Green button not working
I am using Django 1.8. I have a model named Service and it is defined as below: class Service(models.Model): name = models.TextField(blank=False, null=False) ... categories = models.ManyToManyField(Category) ... In the admin panel, there is a green '+' icon with Categories field. On my local machine, when I click on the button, a popup opens, I add a category and the flow goes back to the previous form. However, on production, when I click on the button, a new page opens in the same browser tab. And after adding the category, the page goes blank. In the browser's javascript console, I am getting the following error: caught ReferenceError: showRelatedObjectPopup is not defined at HTMLAnchorElement.<anonymous> (related-widget-wrapper.js:19) at HTMLDocument.dispatch (jquery.min.js:3) at HTMLDocument.v.handle (jquery.min.js:3) I have run the collectstatic command and the file related-widget-wrapper.js exists on the server. What is going wrong here? TIA. -
Django 'OneToOneField' object has no attribute 'id'
I'm trying to create an encoded id field based on the default User object's id, but receive the following error (full trace): Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/default_user/Documents/pumac3/pumac3/registration/models.py", line 52, in <module> class Coach(models.Model): File "/Users/default_user/Documents/pumac3/pumac3/registration/models.py", line 61, in Coach user_id = models.CharField(max_length=254, default=urlsafe_base64_encode(force_bytes(user.id))) AttributeError: 'OneToOneField' object has no attribute 'id' My Coach model in my models.py looks as follows: class Coach(models.Model): user = models.OneToOneField(User, unique=True) # Sets default user values user.is_active = False # For account activation and password resetting user_timestamp = models.IntegerField(default=int(time.time())) user_id = models.CharField(max_length=254, default=urlsafe_base64_encode(force_bytes(user.id))) user_token = models.CharField(max_length=254, default=default_token_generator.make_token(user)) name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) class Meta: verbose_name_plural = "Coaches" ordering = ['name'] def __unicode__(self): """Returns the name of the coach if has name, otherwise returns email.""" if self.name: return self.name else: return self.user.email def update_token(self): """Updates the user_token and timestamp for password reset or invalid activation""" self.user_timestamp = int(time.time()) self.user_token = default_token_generator.make_token(user) self.save() @staticmethod … -
How to use dyanamic urls on templates
I using python 2.7.11 and djnago 1.10.2. I created urls and use dyanamically templates. urls.py url(r'^suits-anarkali/', include([ url(r'^$', category_page, name="suits-anarkali"), url(r'^(?P<slug>[\w-]+)/$', category_page, name="suits-anarkali"), url(r'^(?P<slug>[\w-]+)/$', single_product, name='singleproduct'), url(r'^(?P<slug>[\w-]+)/(?P<singleproduct_slug>[\w-]+)/$', singleproduct, name="singleproduct"), ]) ), this is my url structure. If i call category_page with slug then its working proper but i call single_product with slug then its redirect category page. I have try lot of time but it is not working. So how to manage urls on templates. product.html {% if slug %} <a href="{% url 'singleproduct' slug detail.slug %}">{{ detail.product_name }}</a> {% else %} <a href="{% url 'singleproduct' detail.slug %}">{{ detail.product_name }}</a> {% endif %} -
Django DateTimeField not saved most of the times
In Django 1.8 using pytz==2014.10 I have this weird problem that the datetime field updates appearently on random basis: The model: class Post(models.Model): title = models.CharField(max_length=300, blank=False) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, blank=True, null=True) updated = models.DateTimeField(auto_now=True) lastposted = models.DateTimeField(blank=True) #This is problematic And in views: print 'going to update lastposted', post_id, timezone.now() post = Post.objects.get(pk=post_id) post.lastposted = timezone.now() post.save() in the settings I have: USE_TZ = True TIME_ZONE = 'Europe/Berlin' Example print output in terminal: going to update lastposted 270405 2017-02-08 06:55:04.908058+00:00 But in MariaDB, I see the field has not been updated and it maintains the previous value, which is 2017-02-07 17:01:32 I have no issues saving other fields. The strange thing is that sometimes the lastposted is actually updated, but not most of the times. So I'm really confused and appreciate your clues. -
How to use hostmode in docker compose file
I want to use compose file with host mode networking. My ultimate goal is let Django container use Host postgres on port 5432. I do not want to use postgres on the docker ecosystem. Here is my simplified version. --- version: '2' services: backend: build: context: . dockerfile: dockerfiles/backend_dev image: 703402649386.dkr.ecr.ap-southeast-1.amazonaws.com/clhm-ops-web:backend command: ["python", "manage.py", "runserver"] ports: - "80:80" restart: "always" environment: DJANGO_SETTINGS_MODULE: cdmop.config.settings.local DATABASE_URL: postgres://cdmop:password@postgres:5432/cdmop ... How can I enable host mode networking in here? I have read https://docs.docker.com/compose/compose-file/#/network-configuration-reference And when I read host mode I read http://www.dasblinkenlichten.com/docker-networking-101-host-mode/ But no any other source on host mode compose file example for me Any help would be appreciated -
How to get all the options submitted by form
How to get all the options submitted by the form in Django, this is the form which I used. {% extends 'quiz/base.html' %} {% block content%} <h1>You are at quiz page</h1> <form action="{% url 'quiz:process_data' %}" method="post"> {% csrf_token %} {% for question in question_set %} <h3>{{question.id}}.{{question.question_text }}</h3> {% for option in question.options_set.all %} <input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br> {% endfor %} {% endfor %} <input type="Submit" name="Submit"> </form> {% endblock%} I tried selected_choice=request.POST ,but getting this as output csrfmiddlewaretokenchoice1Submitchoice3. How can I solve this? Thank you -
How to add new item in foreign key in Django like the admin panel?
There is a small + sign on the right of a dropdown list in Django Admin panel which lets me add a new item after a new window pops up. Afterwards it gets automatically selected. How can I do that to my form in Django? I am quite comfortable in using jQuery. -
django combine filter on two fields
i am relatively new in django.Having problem when filtering data.I have two models, given below, Account(models.Model): name = models.CharField(max_length=60) hotel = models.ForeignKey(Hotel) account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30) Transaction(models.Model): account = models.ForeignKey(Account, related_name='transaction') transaction_type = models.CharField(choices=TRANSACTION_TYPE, max_length=15) description = models.CharField(max_length=100, blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) here in mention ACCOUT_TYPE are ACCOUNT_TYPE = ( (0, 'Asset'), (1, 'Liabilities'), (2, 'Equity'), (3, 'Income'), (4, 'Expense') ) now i want to filter all the transactions which account type is Income and Expense within a given date range.How can i combine those filters in django, i have tried so, income_account = Account.objects.filter(account_type=3) expense_account = Account.objects.filter(account_type=4) transactions = Transaction.objects.filter(Q( account=income_account, date_created__gte=request.data['start_date'], date_created__lte=request.data['end_date'] ) & Q( account=expense_account, date_created__gte=request.data['start_date'], date_created__lte=request.data['end_date'])).order_by('date_created') but its not working, raise following error, ProgrammingError: more than one row returned by a subquery used as an expression -
Real-time chat with Django REST backend and iOS
I'm currently developing an iOS app with a custom Django REST backend. Using REST calls I can create/login users and make blog entries. I wanted to implement a chat feature so that my users could send private real time messages to each other. I have no experience with web sockets and how they work. I wanted to know what is the best way to go about developing the chat feature. Current set-up: - iOS app using swift 3 - Django 1.10 for server -
Not able to pass API urls to the REST API app
I have my Django project split into three apps: frontend: You guessed it, the pure frontend. shared_stuff: This is where I've put my models, because I feel they might be shared between apps later on. rest_api: The, well, REST API. All three apps are also registered in settings.py. Now my problem is that the urls meant for rest_api app are also being serviced by the frontend app. Here's what my main urls.py looks like: urlpatterns = [ url(r'^api/v1', include('rest_api.urls')), url(r'^', include('frontend.urls')), ] Am I doing something wrong? Please feel free to ask for more info! -
Django - IntegrityError null value in column "user_id" violates not-null constraint
I am getting an error that is quite weird and I have no clue what could be causing that. I just want to do a simple signup using either Facebook or on-site registration using AllAuth (a third party registration app). Somehow every time I try to register a new user a new ID is created and a new USER_ID as well. But they are not the same (superuser Id = 1 apart), one seems to be always even and the other one odd. It's like two new users are being created at the same time, but one lacks the USER_ID bringing this integrity error. I even tried to DROP my original database to see if it helps, but the issue remained. I'm using Django 1.8 and Python 3.5 It was working fine until I decided to do a little extension to the user module as shown bellow: profiles/models.py from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.utils.encoding import smart_text UF_CHOICES = ( ('SP', 'SP'), ('RJ', 'RJ'), ) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_USER_MODEL_EMAIL_FIELD = 'email' ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' uf = models.CharField( max_length …