Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Problems getting Django/Apache2/mod_wsgi configured without having extra component in URL
What I'm trying to accomplish is to have Apache serve all content at mysite.com/ and have Django handle everything under mydomain.com/signup and mydomain.com/login. The problem is that right now the user has to browse to mydomain.com/mysite/signup or mydomain.com/mysite/login for things to work. I want to get rid of the mysite part of the URLs. I created a project with django-admin startproject signup mysite cd mysite django-admin startapp login I ended up with this directory structure. mysite ├── login │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── signup ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py I have the following urlpatterns in signup/urls.py urlpatterns = [ url(r'^signup/', views.index, name='index'), url(r'^login/', include('login.urls')), url(r'^admin/', admin.site.urls), ] I have Apache mod_wsgi installed and working and have this WSGIScriptAlias in my virtual host file. WSGIScriptAlias /mysite /usr/local/www/wsgi-scripts/mysite/signup/wsgi.py process-group=mysite.com When the user goes to either mydomain.com/mysite/signup or mydomain.com/mysite/login everything works. What I want to do is get rid of the 'mysite' part of the above URLs so the user just has to browse to mydomain.com/signup or mydomain.com/login. I've tried WSGIScriptAlias /signup … -
how to get a CSV from an API and map it into a model
I am using Django and I want to get data via an API in CSV format and import it to my models but I don't know how to do this properly. Please help me. -
Django - csfr_token did not registered or not loaded
<form action = "" method="post"> {% csfr_token %} {{ form.as_p }} <button type="submit">submit</button> </form> This is where I am trying to use a csrf token to protect my form. However, when I try to run the website, it throws me an exception Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 25: 'csfr_token'. Did you forget to register or load this tag? So I search some website, and changed my settings to TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.csrf', ], }, }, ] 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', ] After all these are done, I still get the same exception. Can anybody help me with it? -
Error POST 405 Phyton Django
I'm trying to create a webpage in html in which a user have to input a url into a textfield. <form name="submitURL" method ="post"> <input type="text" name="url_target"> <button type="submit">submit</button> When the user press the submit button a python script should intercept the data inserted by the user and pass it to another function inside this script. Python script: from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def indhtml() : return render_template('index.html') @app.route('/index.html', methods = ['POST']) def result(): result = request.form('url_target') link = result.link print (link) return if __name__ == '__main__' : app.run(debug = True) the first render is fine and i can see the index.html page, but when i insert something in the textfield appears the error HTTP 405. Do you have any suggestion for that? :( Thanks! -
Django - Should I use Django REST framework for a basic HTML site?
Per the suggestion in the answer to the question Django url paths what is optimal number to cover all combinations. I have been looking into Django REST Framework, it definitely looks a useful API, but I am just trying to make HTML website at the moment. The only rendering for HTML is 'TemplateHTMLRenderer' (and 'StaticHTMLRenderer'). I think I should be using REST Framework but there is not much on how to use on a basic website. As I am new to Django and Django REST Framework. Should I be using the REST Framework for a solo HTML render site? I am getting myself in a knot and I really need a pointer from someone who knows their way around this area. Thank you for your time.