Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - built-in templates tags with variables
I am a new coder with Django. <form action = "{% url 'post:comment' topic=topic user_id=1 %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> I am try to use this code to make a comment function for my website. The following is some relevant functions: def comment(request, topic, user_id): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': topic} # save the data in database save_comments_into_database(topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': topic}) the namespace is already be named as "post" in urls.py However, I get this exception Exception Type: NoReverseMatch Exception Value: Reverse for 'comment' not found. 'comment' is not a valid view function or pattern name. Why the comment function cannot be matched? -
Django template custom form using text area not working
I am using custom template for django form, so i loop over the form fields and create hidden textarea boxes. On hitting the submit button i call the function save code which fills in value of textarea. Earlier i was using input html instead of textarea and it was working fine but I need multiple line value in my form (html input is only single line) so i had to change it to textarea But now probably i am getting 'this field is required' error! (the procedure is same, when i had input tag i did performed document.getelementbyid('id-name').value = required stuff) So i am confused why is it not working with textarea <form method="post" action="{% url 'problem' problem.problem_ID %}"> {% csrf_token %} {% for field in code_form %} <textarea id="{{ field.id_for_label }}" value="{{ field.value }}" style="visibility:hidden;"></textarea> {% endfor %} {% buttons %} <button onclick="save_code()" type="submit" class="btn btn-success center-block">Submit editor</button></td></tr> {% endbuttons %} </form> -
Generating Table of Contents in a Django Blog
How do I dynamically generate table of contents for every post in a Django blog? Thanks in anticipation! -
Running "coverage html" crashes
I'm new to the coverage library for python. But I've immediately encountered a problem and I can't find mention of it on google.. In my virtual environment (pipenv) I do: pipenv install coverage==3.6 coverage run manage.py test <app-name> coverage report coverage html All of them work nicely, I get a nice text report in my shell, but when I run coverage html it crashes... Traceback (most recent call last): File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\parser.py", line 571, in _arcs ch = byte_chunks[byte] KeyError: 22318 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\programming\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\programming\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Win7\.virtualenvs\app-87mb2psT\Scripts\coverage.exe\__main__.py", line 9, in <module> File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 710, in main status = CoverageScript().command_line(argv) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 452, in command_line **report_args) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\control.py", line 615, in html_report return reporter.report(morfs) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 90, in report self.report_files(self.html_file, morfs, self.config.html_dir) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\report.py", line 84, in report_files report_fn(cu, self.coverage._analyze(cu)) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 164, in html_file missing_branch_arcs = analysis.missing_branch_arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 127, in missing_branch_arcs missing = self.arcs_missing() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 88, in arcs_missing possible = self.arc_possibilities() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 76, in arc_possibilities arcs = self.parser.arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\misc.py", line 73, in _wrapped setattr(self, … -
Module Not Found Error: No Module Named 'my_project.settings' django gunicorn
I am trying to deploy on heroku but first I am trying to run on my machine but I keep getting the Module Not Found Error. My directory structure looks like this: To make it more clear, I have a folder called 'imperialtheatre' that holds the venv and requirements and inside that folder i have a folder called 'imperialtheatre' which holds the django project with manage.py etc. Why am I getting this error? I am running this command: gunicorn imperialtheatre.imperialtheatre.wsgi:application -t 120 -w 8 -k gevent --max-requests 250 --log-level debug wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imperialtheatre.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Django Mongoengine leading whitespace being stripped
I have a small issue that I'm struggling to find a solution on. Currently when I recieve the result from a POST with JSON data all leading whitespaces in some of the values as completely gone but all in between the words saved. Is there a setting for MongoEngine that stops this on StringFields? -
Django fail to use data from setting.ini [Errno 11001] getaddrinfo failed
When I set in setting.py the folowing paramters EMAIL_HOST ,EMAIL_PORT , EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_USE_TLS, DEFAULT_FROM_EMAIL And call send_mail every thing works fine but, when I move does paramters to setting.iniI I get error. I am able to see does param correct in my code when I try to view them: raise Exception('EMAIL_HOST -> ' + settings.EMAIL_HOST + 'EMAIL_PORT -> ' + str(settings.EMAIL_PORT) + 'EMAIL_HOST_PASSWORD -> ' + settings.EMAIL_HOST_PASSWORD + 'EMAIL_HOST_USER -> ' + settings.EMAIL_HOST_USER + 'EMAIL_USE_TLS -> ' + str(settings.EMAIL_USE_TLS) ) But when I try to send mail I get the folowing error [Errno 11001] getaddrinfo failed Any suggestion Why when I use does paramters in setting.py it works fine and when I put then in setting.ini I am able to see them but fail to send mail ,what am I doing wrong? I use: Django Version: 1.11 Python Version: 3.5.0 and I call send_mail as folow send_mail("this is the subject", "this is the content", settings.EMAIL_HOST_USER, ["eran3216@gmail.com","eran3216@gmail.com"]) Thanks for the help -
How to use LetsEncrpyt with Nginx and Gunicorn?
I deployed Django to DigitalOcean with the Gunicorn and the Nginx successfully. I want to switch to HTTPS then I have installed LetsEncrpyt with the Digitalocean's tutorial. This my Nginx confguration file: (/etc/nginx/sites-available/[MY_DOMAIN] ) server { listen 80; listen 443; server_name [MY_DROPLETS_IP_ADDRESS]; return 301 $scheme://[MY_DOMAIN].com$request_uri; } server { server_name www.[MY_DOMAIN].com; return 301 $scheme://[MY_DOMAIN].com$request_uri; } server { server_name [MY_DOMAIN].com; access_log off; listen 80; listen 443 ssl; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_certificate /etc/letsencrypt/live/[MY_DOMAIN].com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/[MY_DOMAIN].com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; if ($scheme != "https") { return 301 https://$host$request_uri; } location /static/ { alias /opt/data/static/; } location / { proxy_pass https://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } This is the sudo ufw status verbose output: Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp (OpenSSH) ALLOW IN Anywhere 80,443/tcp (Nginx Full) ALLOW IN Anywhere 22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6) 80,443/tcp (Nginx Full (v6)) ALLOW IN Anywhere (v6) This is the sudo systemctl status gunicorn output: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-10-21 16:46:22 UTC; 19min ago The … -
Django Posts on homepage
I am new to Django and I'm stuck on how to display latest blog articles on the homepage. I'm trying to insert them through a snippet which includes {{post.title}} but no luck. Any ideas? -
get No module named urls while rendering template in celery task
The site works ok, but when a celery task is called which renderes template for EmailMultiAlternatives, I get ImportError: No module named urls. If I comment out just one app in settings.py (modal_announcements), it works. The app itself runs ok in the site. This is the urls.py (which could not be found, thoght it apparently exists): from django.conf.urls import patterns, url from mezzanine.conf import settings from modal_announcements.views import announcement urlpatterns = patterns('', url("^announcement/(?P<pk>.*)%s$" % ("/" if settings.APPEND_SLASH else ""), announcement, name='announcement') ) here are the project's urls: if settings.USE_MODELTRANSLATION: urlpatterns += patterns('', url('^i18n/$', 'django.views.i18n.set_language', name='set_language'), url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^chaining/', include('smart_selects.urls')), ) urlpatterns += i18n_patterns("", url("^$", home, name='home'), url(r'^inliner$', inliner, name='inliner'), url(r'^autocomplete/', include('autocomplete_light.urls')), ("^orders/", include("orders.urls", namespace="orders")), ("^shop/", include("shop.urls", namespace="shop")), ("^programs/", include("programs.urls", namespace="programs")), ("^prices/", include("prices.urls", namespace="prices")), ("^tour/", include("tour.urls", namespace="tour")), ("^misc/", include("misc.urls", namespace="misc")), **("^announcements/", include("modal_announcements.urls", namespace="announcements")),** ("^%s/" % settings.EVENT_SLUG, include("mezzanine_agenda.urls")), # ``mezzanine.urls``. ("^", include("mezzanine.urls")), ) urlpatterns += patterns('', url('', include('social.apps.django_app.urls', namespace='social')), ) # Adds ``STATIC_URL`` to the context of error pages, so that error # pages can use JS, CSS and images. handler404 = "mezzanine.core.views.page_not_found" handler500 = "mezzanine.core.views.server_error" if settings.DEBUG: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), ) -
Django form validation not working after adding IntegerField with Radio Widget
I had my form set up and working with no errors, but after I added an IntegerFIeld with a RadioSelect widget the form no longer validates. (Before this I only had CharFields in the model and no widgets) I've searched other similar questions but haven't been able to find anything to solve this issue. At present I just keep getting the error message I coded in views.py. My set up is as follows: views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.utils import timezone from .forms import DiaryEntryForm from .models import DiaryEntry def new_entry(request): if request.method == "POST": form = DiaryEntryForm(request.POST) if form.is_valid(): entry = form.save(commit=False) entry.author = request.user entry.created_date = timezone.now() entry.save() messages.success(request, "Entry created successfully") return redirect(entry_detail, entry.pk) else: messages.error(request, "There was an error saving your entry") return render(request, 'diaryentryform.html', {'form': form}) else: form = DiaryEntryForm() return render(request, 'diaryentryform.html', {'form': form}) forms.py from django import forms from .models import DiaryEntry, FORM_CHOICES class DiaryEntryForm(forms.ModelForm): body = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES) mind = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES) class Meta: model = DiaryEntry fields = ('body', 'mind', 'insights') models.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.conf import settings from django import forms … -
Django Create Comment View pass Subject pk
I'm learning Django and have been beating my head against a wall trying to make a comment form work correctly. Basically what I'm building is a recipe app. This is just practice but the idea would be that someone posts a recipe and other people can comment on it. I have it basically working but I cannot work out how to have the redirect go back to the recipe detail view after the comment has been submitted. If I hard code in the pk it works, I just need to get a hold of that pk! Here is my stuff: Portion of Recipes views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView, View from django.views.generic.detail import SingleObjectMixin from django.core.urlresolvers import reverse_lazy #from comments.models import Comment from .models import Recipe from comments.models import Comment from .forms import RecipeCreateForm from comments.forms import CommentFormTrial from comments.views import CommentCreateView class PersonalRecipeListView(LoginRequiredMixin,ListView): def get_queryset(self): return Recipe.objects.filter(owner=self.request.user) class RecipeDetailView(View): def get(self, request, *args, **kwargs): view = RecipeContent.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentCreateView.as_view() return view(request, *args, **kwargs) class RecipeContent(DetailView): model = Recipe template_name = 'recipes/recipe_detail.html' context_object_name = 'recipe_data' def get_context_data(self, *args, … -
Create a model with content type fields on post_save receiver
I'm trying to link a post save receiver on a model I have, representing a buyable item, to create a product model for me. The product model is: class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODULE) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') ..... And my post_save is: @receiver(post_save, sender=BuyableItem, dispatch_uid="update_product_catalog") def create_product(sender, instance, **kwargs): Product.objects.create( user=instance.user, content_type=??, object_id=??, content_object=??, ) What do I put for the ?? fields I've marked? Also, is this a bad idea to do? I'm implementing a session based cart and there are differing product types so I wanted my cart to just reference the abstract product model since the different types can be uniquely identified (and gotten) through the content type / object id. -
which music player to use for a website made in django
I have some music files stored in my local file system. Which js framework can I use to get a music player box at the bottom of my website ? website is made with django. -
Asynchrone Django: Other Options than DRF + AngularJS
Developing a asynchrone Django frontend I know the combination of: Django Django REST Framework AngularJS What other options do exists and have proven to be work excellent? -
How to restore postgresql data without backup file?
I've deleted database tables from django shell by accident. I am using postgresql database. Is there a way to get at least some of the data back? -
Post request to detail_route [DRF]
I've been struggling with the POST method on a detail_route from a viewset and I don't know how to do it. I have this viewsets: class ListViewSet(viewsets.ModelViewSet): queryset = models.List.objects.all() serializer_class = serializers.ListSerializer @detail_route(methods=['get']) def entries(self, request, pk=None): list = self.get_object() serializer = serializers.EntrySerializer( list.entries.all(), many=True ) return Response(serializer.data) class EntryViewSet(viewsets.ModelViewSet): queryset = models.Entry.objects.all() serializer_class = serializers.EntrySerializer As you see, I did implement the get method on detail_route, but I don't know the best approach to implement the post method to append an entry to that specific list (like ListCreateAPIView for the detail_route). I have that EntryViewSet that is going to api/v1/entries, but I want to be able to send a POST request that will append an entry to a specific list, that's why I want post request to detail_route. I don't want the users to be sneaky and try to send an entry to a different list. Thanks in advance for the answers! -
Extended User, ManyToMany does not save to db
I have a problem with the registration of the new users while they are asked to choose different tags. This tags are not saved in the db and I do not know which is the problem. This is my app for registering (model.py, views.py and forms.py). First, I have import the user model from django and create a new class Perfil which inherit from User. The goal is to add an area where the user will be able to choose his/her tags. Look: models.py from django.db import models from django.contrib.auth.models import User from apps.Tags.models import Tags class Perfil(User): tag = models.ManyToManyField(Tags, blank = True) def __str__(self): return '{}'.format(self.username) forms.py from apps.usuario.models import Perfil from django.contrib.auth.forms import UserCreationForm from django import forms class RegistroForm (UserCreationForm): class Meta: model= Perfil fields = [ 'username', 'first_name', 'last_name', 'email', 'tag', ] labels = { 'username': 'Nombre de usuario', 'first_name' : 'Nombre', 'last_name': 'Apellidos', 'email': 'Correo', 'tag': 'Etiqueta', } widgets = { 'tag':forms.CheckboxSelectMultiple(), } views.py from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.views.generic import CreateView from django.core.urlresolvers import reverse_lazy from apps.usuario.forms import RegistroForm from apps.usuario.models import Perfil class RegistroUsuario (CreateView): model=Perfil template_name = "usuario/registrar.html" form_class = RegistroForm success_url = … -
Sent out broken link in a Mailchimp campaign - how to do a bulk redirect?
Just joined but have been a lurker for a while and found this community very helpful. I've just sent out an email newsletter via Mailchimp to our 15,000 subscribers and included the wrong link (it should have been .../grandchallenges not .../grand-challenges. I've done a simple redirect on our website, but Mailchimp inserts individual URLs, so folks end up with a link that looks like this: .../grand-challenges/?mc_cid=debb7846d7&mc_eid=18de3e5c2a. As such i'd have to do 15,000 individual redirect requests, unless there's a way to 'bulk' redirect everything after the slash. Btw - we're using Mezzanine as a Django CMS not Wordpress: http://mezzanine.jupo.org, so the answer won't be a WP plug-in. Thanks! -
Storing multiple API keys for a user in Django
I'm in the process of learning Django, and I'm building an app that has a "User" model, and I need to store a dictionary of private API keys for various other applications for each user, where the key is the service name and the value is the actual API key. My current plan was to have the dictionary be stored as JSON, but I was wondering if there is a better/more secure way I should be doing this? -
It is wise to Store all user data in session or unique id of database?
I am making a simple social networking site in Express Node Js Using mongo db. There are users info in database that is to be displayed in many pages. If I store a user Id of my db collections as a session variable, each time I should write db query to find user of that ID and display their info. Would it better if I store all the info of that user as a session variable. Or, there is another better approach -
How to get dynamically added checkbox value in django views.py?
I added checkbox in html page using javascript using following code var checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.name = 'chk'; checkbox.id = 'chk'; checkbox.value = i; y.appendChild(checkbox); And try to retrive value of selected checkbox value in views.py using following code chk1=request.POST.getlist('chk') but that not work, chk1 prints empty list. -
Django: Advanced Database Filtering
I have 3 Models, class Data(models.Model): ... class Game(models.Model): data = models.ForeignKey(Data) ... class Extras(models.Model): data = models.ForeignKey(Game) ... In view I have, def view(request): objects = Data.objects.all() In Template, {% for obj in objects %} {{ obj }}<br /> {% for new in obj.game_set.all|slice:"2" %} ... {% endfor %} {% endfor %} Here, I wants to filter out "Data" along-with latest 2 "Games" having "Extras". Slice is not working properly because it's giving 2 "Games" no matter they have "Extras" or not. Or if I use if statement something like, {% for new in obj.game_set.all|slice:"2" %} {% if new.extra_set.all %} .... {% endif %} {% endfor %} Nothing will return in case if latest 2 Games don't have extras. So, how can I filter out latest 2 "Games" having "Extras" in this case? -
how to import honeywordgen.py into hashers.py
hye there . i try to customize my own password hashers by using honeyword hashers but i still cannot import the honeyword generator file into the hashers file . i already follow django documentation for the hashers.py honeywordgen.py : import hashlib import string import re from django.db import models from django.contrib.auth.hashers import PBKDF2PasswordHasher from django.utils.crypto import constant_time_compare from django.utils.translation import ugettext_noop as _ from random import random, randrange, choice, sample TOUGH_NUT_PROBABILITY = 0.10 RANDOM_WORD_PROBABILITY = 0.03 EQUIV_CHAR_REPLACE_PROBABILITY = 0.25 MAX_PASSWORD_LENGTH = 256 PASSWORD_PUNCTUATION = '!@#$%^&*+-?' ALL_PASSWORD_CHARS = string.ascii_letters + string.digits + PASSWORD_PUNCTUATION VOWELS = 'aeiou' LETTERS = string.ascii_lowercase CONSONANTS = string.join([c for c in string.ascii_lowercase if c not in VOWELS], '') # h, j, k, q, w, x, y are rarely doubled DOUBLE_CONSONANTS = [c + c for c in CONSONANTS if c not in 'hjkqwxy'] def closed_syllable(): return choice(CONSONANTS) + choice(VOWELS) + choice(CONSONANTS) def open_syllable(): return choice(CONSONANTS) + choice(VOWELS) def vce_syllable(): r = random() v = '' if r < 0.95: v = choice([c for c in VOWELS if c != 'e']) else: v = choice(VOWELS) return v + choice(CONSONANTS) + 'e' def vowel_team_syllable(): r = random() if r < 0.30: return choice(['oo', 'ee']) if r < 0.70: v … -
Performant calculation of datetime diffs in days
I have a Django model that contains a unique record with a date . I'm currently counting records into ranges of days, e.g. X Number have already passed todays date, X will happen within the next 10 days, X will happen within the next 30 days. The code below is what I am currently using, it pulls all values back from an records.objects.all() query against the model and then loops through each object to calculate the datetime delta and increment the relevant counter. for x in records: if x.date is None: missingValue += 1 else: delta = x.date - date.today() if delta.days < 0: passed += 1 if delta.days < 10: tenDays += 1 if delta.days < 30: thirtyDays += 1 For around 50,000 records this takes about 5-6 seconds which is longer than I would like, I'm trying to reduce this as the number of records is likely to increase. The question is really around the performant calculation of datetime diffs and grouping the resultant number of days as if there is a better method through a Django Query or other method I've not been able to find I'm open to trying it. I've explored the use of DateAdd …