Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to create custom django model field for representing opening and closing hours of a place
I have an application about Restaurants. You can set its opening and closing time. I do it by adding two time fields like this. class Place(models.Model): # other fields opening = models.TimeField() closing = models.TimeField() However I want to do it with one, custom field something like this. class Place(models.Model): # other fields operating_hours = models.DualTimeField() -
Add multiple fields to django form
I am new to django and I'm making food recipe app. I want the users to be able to add their own recipe. models.py from django.db import models from django.core.urlresolvers import reverse class Recipe(models.Model): def __unicode__(self): return self.recipe_name recipe_name = models.CharField(max_length=250) category = models.CharField(max_length=50) description = models.CharField(max_length=1000) image = models.CharField(max_length=1000) prep_time = models.CharField(max_length=250) difficulty = models.CharField(max_length=50) instructions_url = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('detail', kwargs={'pk': self.pk}) class Ingredients(models.Model): def __unicode__(self): return self.ingredients recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredients = models.CharField(max_length=1000) views.py class RecipeCreate(CreateView): model = Recipe fields = ['recipe_name', 'category', 'image', 'prep_time', 'difficulty', 'instructions_url'] At the moment my form display the fields only from my "class Recipe", but what i want is to have Ingredient field with option to add additional fields. Do you have any suggestions how to do this? Thanks! -
prefetch_related data can not be acquired
There are models as follows. class Account(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(verbose_name='email address', max_length=255, unique=True) ... class Follow(models.Model): followed_user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='followed_user', verbose_name='followed_user', on_delete=models.CASCADE ) follow_user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='follow_user', verbose_name='follow_user', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.followed_user) Then, in the view, as we get information on the Account as follows, we are also going to give follow / follow information associated with that account. class AuthInfoGetView(generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = Account.objects.all() serializer_class = AccountSerializer def get(self, request, format=None): instance = self.queryset\ .prefetch_related('followed_user', 'follow_user')\ .get(email=self.request.user) However, debugging with print (instance.follow_user) in this view will return api.Follow.None even though there are other accounts that follow. Please tell me how to do it is best. -
How to read cookie from PHP set by Django on subdomain?
I am using Django v1.11 on sub.domain.com and PHP 7 on domain.com Is it possible to set cookie on sub.domain.com and read it on domain.com? I guess yes, but it does not work. Moreover, I don't understand how use and should I use SECRET_KEY and SESSION_COOKIE_NAME on Django. So, on Django (sub.domain.com) I set like this in view: response = redirect('home:index') response.set_cookie('my_cookie', 'test123') return response Django settings: SECRET_KEY = 'vnw8*o1cuc7bia1b8#c...' SESSION_COOKIE_DOMAIN = ".domain.com" SESSION_COOKIE_NAME = "mycookiename" PHP on domain.com: <?= $_COOKIE['my_cookie'] ?> // empty <?php print_r($_COOKIE); ?> // empty too BUT. If I check cookies on my Chrome browser, the domain is sub.domain.com instead of .domain.com (perhaps, SESSION_COOKIE_DOMAIN not working?) What am I doing wrong?