Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return related Guids instead of Ids in Django-Rest-Framework Serialization
I have a model that has the following: class TeamInvite(models.Model): inviter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='invites_sent') invitee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='invites_received') team = models.ForeignKey(Team, related_name='team_invites') guid = models.UUIDField(default=uuid.uuid4) class UserMetaData(models.Model): user = AutoOneToOneField(settings.AUTH_USER_MODEL, related_name='usermetadata') guid = models.UUIDField(default=uuid.uuid4) I'm trying to obscure the serialization of my users by returning only the guid field in Django Rest Framework. Here was my first attempt, but it doesn't work (it returns the same guid twice. How can I get 'inviter' and 'invitee' to each display their respective guids? class InviteListingField(serializers.RelatedField): def to_representation(self, value): return value.usermetadata.guid class TeamInviteSerializer(serializers.ModelSerializer): lookup_field = 'guid' inviter = InviteListingField(read_only=True) invitee = InviteListingField(read_only=True) class Meta: model = TeamInvite fields = ('guid', 'inviter', 'invitee', 'team' ) -
Search Functionality on a Django Site
I'm trying to add a search function to my website but I'm having some issues. It's currently telling me that "Search" is not defined, but I have the class in my views file. This is what I have thus far: urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^player/(?P<pk>\d+)/$', views.player, name='player'), url(r'^season/(?P<pk>\d+)/$', views.season, name='season'), url(r'^seasons/$', views.seasons, name='seasons'), url(r'^search/$', Search.as_view(), name='search'), ] views.py from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView from .models import Player, Season, PxS, Statistics def home(request): seasons = Season.objects.order_by('sid') return render(request, 'webapp/home.html', {'seasons': seasons}) def player(request, pk): player = get_object_or_404(Player, pk=pk) return render(request, 'webapp/player.html', {'player': player, 'seasons': player.season_set.order_by('sid'), 'statistics': player.statistics_set.all()}) def season(request, pk): season = get_object_or_404(Season, pk=pk) return render( request, 'webapp/season.html', {'season': season, 'players': season.players.order_by('lastname')} ) def seasons(request): seasons = Season.objects.order_by('sid') return render(request, 'webapp/seasons.html', {'seasons': seasons}) class Search(ListView): template_name = 'search.html' model = Player context_object_name = 'list' def get_context_data(self, **kwargs): context = super(Search, self).get_context_data(**kwargs) context['count'] = self.get_queryset().count() return context def get_queryset(self): pobj = Player.objects.all() var_get_search = self.request.GET.get('search_box') var_get_order_by = self.request.GET.get('pid') if var_get_search is not None: pobj = pobj.filter(playername__icontains=var_get_search) if var_get_order_by is not None: pobj = pobj.order_by(var_get_order_by) return pobj Any insight is greatly appreciated. I'm kind of just piecing … -
How does django treat login/signup based on modal?
I'm using modal for login/signup in django. (http://bootsnipp.com/snippets/featured/modal-login-with-jquery-effects) But I wonder how django treat this in template rendering. As you can see above url, it has only one html file, say, login.html. In django views, I have two views named LoginView and SignupView. These are what I thought as problems. Each View gonna render template : LoginView --> login.html SignupView --> signup.html but as you can see above, if I used modal, there is only one html file for both signup and login. I want to know how I can deal with it. Also, Each view gonna pass its form, say, UserCreationForm, CustomLoginForm for getting input from user. But if there were only one html file, would there be conflict between those forms? Thanks. -
TypeError: view must be a callable or a list/tuple in the case of include() with django 1.9
I am new to django and python and using http://slash4.net/learn-django/day1.html to built my website.I am using Django 1.9,when i try to map url to view i get this error TypeError: view must be a callable or a list/tuple in the case of include() My views.py looks like this- from django.shortcuts import render def home(request): return render(request, 'events/home.html') and url.py looks like- from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^home/$', 'events.views.home', name='home'), ] Help please..!!!! -
Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet?
I'm working on a Django 1.8.2 project. This project has multiple Django applications. Application app_a has class MyClassA as follows: class MyClassA(models.Model): name = models.CharField(max_length=50, null=True, blank=True) @staticmethod def my_static_method(): ret_val = MyClassA.objects.filter() return "World" Application app_b has class MyClassB as follows: class MyClassB(models.Model): name = models.CharField(max_length=50, null=False, blank=False) def my_method(self, arg1=MyClassA.my_static_method()): return "Hello" When I run manage.py test, it works fine. However, then I change MyClassA.my_static_method() to the following: @staticmethod def my_static_method(): ret_val = MyClassA.objects.filter(name=None) return "World" When I do that, and then run manage.py test, it fails with the following error: File "my-virtual-env/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Why is this happening? How do I fix this? The only change that I made is adding the filter value name=None. -
How to import python module from docker
I made a docker image contains nginx, uwsgi and some python module, using volumes out the docker to develop code. So how should I use python environment from docker when coding? -
How to check if Django object is None in javascript?
How do you check if a Django object is None in js? I currently have a variable person that stores a Django object or None. In my js I have: if ({{person}} != None) { execute_function({{person}}) } What seems to be the issue here? -
How to read data, apply a function and return the result with Django REST Framework?
Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15. Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the server and only return "y". However, I can't figure it out how to get "x" from the URL and where to place the last function to return "y" to the JSON. Any thoughts? models.py: from django.db import models class SimpleEquation(models.Model): a = models.IntegerField() b = models.IntegerField() serializers.py: from rest_framework import serializers from .models import SimpleEquation class SimpleEquationSerializer(serializers.ModelSerializer): class Meta: model = SimpleEquation fields = ('a','b') # Should return 'y' instead views.py: from rest_framework import generics from .serializers import SimpleEquationSerializer class Results(generics.ListAPIView): queryset = SimpleEquation.objects.all()[0] serializer_class = SimpleEquationSerializer My dumb function so far: def the_function(request): x = SOME_REQUEST_GET_METHOD pars = SimpleEquation.objects.all()[0] a = pars.a b = pars.b y = a*x + b return y -
Django Test_Deferred
I am trying to perform a simple RAW query by following [https://docs.djangoproject.com/en/1.10/topics/db/sql/#executing-custom-sql-directly][1] My model is: class Test(models.Model): ID = models.IntegerField() My RAW query is: for p in Test.objects.raw('select ID from table')" print(p) Yet, when I run the code I'm given 'Test_Deferred_ID' in the terminal. What does 'Deferred' mean in this context? -
How to make application urls appear throughout the project?
My templates dont see urls which are in my application, in code: urls.py in project: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('search.urls')), url(r'^accounts/', include('accounts.urls')), ] urls.py in application: urlpatterns = [ url(r'^', include('registration.backends.simple.urls')), ] I have error and i know why: NoReverseMatch at /accounts/login/ Reverse for 'auth_password_reset' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] <p>{% trans "Forgot your password?" %} <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>.</p> But when i put include('registration.backends.simple.urls') in project urls everything is good. I know i can namespace my url but i dont want do this. I want only 'see' my urls from my app in all my application, and i dont want put my urls in root urls.py. I want them in a separate file. Can you do something about it ? -
Python 3.5 and mod_wsgi
I use Python 3.5 with virtualenv, and I'm trying connect it with mod_wsgi Exception occurred processing WSGI script '/home/myapp/my_app/my_app/wsgi.py'. Traceback (most recent call last): File "/home/myapp/my_app/my_app/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' Apache config: ... DocumentRoot /home/myapp/my_app/ WSGIScriptAlias / /home/myapp/my_app/my_app/wsgi.py WSGIDaemonProcess python-path=/home/myapp/my_app/:/home/myapp/myapp_venv/lib/python3.5/site-packages:/home/myapp <Directory /home/myapp/my_app/ad_server> <Files wsgi.py> Require all granted </Files> </Directory> <Location "/"> Require all granted </Location> Alias /static /home/myapp/my_app/static ... And wsgi from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") application = get_wsgi_application() What I'm doing wrong? -
SSLV3 handshake failure with latest version of pyOpenSSL
I am trying to use Paypal's REST API, but when I try to connect, it raises this error. ERROR 2016-08-22 16:54:54,039 views.py processPayment 149 [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:645) I installed pyOpenSSL 16.0.0 in my virtual environment I am using, but I still get this error, and am unsure why. views.py def processPayment(request, cart, card_form): temp_exp_year = '2020' temp_exp_month = '09' temp_card_type = 'visa' json_data = {'billing_status': '200'} temp_api = paypalrestsdk.Api({ "mode": "sandbox", "client_id": settings.API_KEY.client_id, "client_secret": settings.API_KEY.secret }) transactions = createPaypalApiTransactions(cart) # Payment Creation payment_dict = { "intent": "sale", "payer": { "payment_method": "credit_card", "funding_instruments": [{ "credit_card": { "type": temp_card_type, "number": card_form.cleaned_data['acct'], "expire_month": temp_exp_month, "expire_year": temp_exp_year, "cvv2": card_form.cleaned_data['cvv2'], "first_name": cart.first_name, "last_name": cart.last_name, } }] }, "transactions": transactions } payment = paypalrestsdk.Payment(payment_dict, api=temp_api) try: if payment.create(): payment_resource = payment['id'] transaction_id = payment['transactions'][0]['related_resources'][0]['sale']['id'] transaction_state = payment['transactions'][0]['related_resources'][0]['sale']['state'] return closeOutCartWithPayment(request, cart, json_data, payment_resource, transaction_id, transaction_state) else: card_form.add_error(None, payment.error['message']) json_data['credit_status'] = '300' json_data['credit_errors'] = card_form.errors return ComposeJsonResponse(200, "", json_data) except Exception as e: logging.error(e) try: card_form.add_error(None, '{}. Please try again or <a href="/contact-us">contact us.</a>'.format( json.loads(e)['message'])) except Exception as e: card_form.add_error(None, e) return ComposeJsonResponse(200, "", json_data) def createPaypalApiTransactions(cart): transactions = [{ "item_list": { "items": [{ "name": item.product.product.label + '(' + item.product.label + ')', "price": "{:.2f}".format(item.line_total()), … -
Django paginator with many pages
I have implemented a paginator with the generic ListView. My problem is that for list with many pages it displays all the page numbers instead of for example five pages before and after the current page. Is there an easy way to fix this? in the views.py: class CarList(LoginRequiredMixin, ListView): model = Car paginate_by = 20 in the html: {% if is_paginated %} <ul class="pagination pagination-centered"> {% if page_obj.has_previous %} <li><a href="/car?ordering={{ current_order }}&page=1"><<</a></li> <li><a href="/car?ordering={{ current_order }}&page={{ page_obj.previous_page_number }}"><</a></li> {% endif %} {% for i in paginator.page_range %} <li {% if page_obj.number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li> {% endfor %} {% if page_obj.has_next %} <li><a href="/car?ordering={{ current_order }}&page={{ page_obj.next_page_number }}">></a></li> <li><a href="/car?ordering={{ current_order }}&page={{ page_obj.paginator.num_pages }}">>></a></li> {% endif %} </ul> {% endif %} -
Django null value in column "user_id" violates not-null constraint
I have a model userpreference that references Django model User. I keep getting error null value in column "user_id" violates not-null constraint when trying to post a new userpreference. the data I sent for post is: { "user": "http://127.0.0.1:8000/user/4/", "send_email": false } my userpreference model is: import uuid from django.db import models from django.contrib.auth.models import User class UserPreference(models.Model): class Meta: app_label = 'my_app' permissions = ( ('view_userpreference', 'View User Preference'), ) uuid = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) user = models.OneToOneField(User, related_name="user_preference", on_delete=models.CASCADE, db_index=True) send_email = models.BooleanField(default=True, db_index=True) def __unicode__(self): return u"<UserPreference {0} {1}>".format(str(self.uuid), self.user.id) my userpreference view is: class UserPreferenceList(generics.ListCreateAPIView): model = UserPreference permission_classes = (permissions.IsAuthenticated, CustomObjectPermissions) serializer_class = UserPreferenceListSerializer queryset = UserPreference.objects.all() class UserPreferenceDetail(generics.RetrieveUpdateDestroyAPIView): model = UserPreference permission_classes = (permissions.IsAuthenticated, CustomObjectPermissions) serializer_class = UserPreferenceSerializer queryset = UserPreference.objects.all() and my userpreference serializer is: class UserPreferenceSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True, lookup_field="id", lookup_url_kwarg="pk") class Meta: model = UserPreference fields = ('url', 'user', 'send_email') class UserPreferenceListSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True, lookup_field="id", lookup_url_kwarg="pk") class Meta: model = UserPreference fields = ('url', 'user', 'send_email') Any suggestions? -
Changing the behavior of the Django admin messages
I have overridden the save and continue button in the admin (I added some things that take time to process). If I click on the save and continue button, when the processing is done, the green successful save message is displayed. If I make a change to a field in my form, and click the save and continue button again, the successful save message from the previous click stays on the screen (until the process has been completed). Is it possible to get the successful save message from the previous click to disappear immediately after I click the save button again? -
Changes in Django View Lagging
I'm a fairly new to web development so this might actually be normal behavior - but when I make logic changes in my views, it can take about an hour for those changes to show up on my production site. The changes are instant if I fire up the localhost. Server is Windows IIS 7.5. HTML, CSS, and JS changes show up instantly, it's the code in the view that takes a while to filter through. Any ideas on what is causing this and how to fix it? -
Import Error: No module named 'allauth.account'
When I try and login to my Django app, I am given this error when logging in on localhost ImportError: No module named 'allauth.account' But when logging in on the live app (Heroku), there is no error. Any thoughts? It makes it frustrating when I have to push the site for every small change I make on the portion of the site that you have to login to. settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', # 'allauth.account', Does not work when running the app #My apps# 'home', 'projects', 'accounts', 'storages', ) -
Using Taggit with custom view Django
I am currently trying to implement a tag system into my Django project. I am trying to add the tags within each post, and have a category on the right hand side that displays maybe 10-20 of the tags. I am trying to implement this into the feed view, but i am unsure of how to call the slug for each tag in order to do /posts/tag/feed. So once you click on a tag it will redirect to the slug of the tag. Which would make the tag clickable. I tried to follow the link below but it only shows how to do it with the class view. https://godjango.com/33-tagging-with-django-taggit/ views.py def post_feed(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 queryset_list = Post.objects.all() tags = Tag.objects.all() query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query)| Q(tags__icontains=query)| Q(description__icontains=query)| Q(user__first_name__icontains=query)| Q(user__last_name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 5) page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "title": "List", "page_request_var": page_request_var, } return render(request, … -
Iterating over paginated list of objects in Django template, via JS
In a Django web app I maintain, users upload videos that others can playback. All videos are encoded as mp4s. In certain cases where browsers can't play this format (e.g. Firefox), I need to program an elegant fallback. I'm following the example here - it covers all the bases nicely. My Django template is backed by a paginated class-based ListView. It gets an object_list passed to it. I then iterate through this list and display the videos one by one. Each page has 10 video objects. I.e., something like the following (simplified code): {% for vid in object_list %} <video width="500" height="350" controls autoplay> <source src="{{ vid.streaming_url }}" type='video/mp4; codecs="mp4v.20.8, samr"'> <a href="{{ vid.streaming_url }}"> <img src="https://a2ua.com/404/404-005.jpg" title="Your browser does not support the <video> tag"> </a> <p>This browser can't run this video</p> </video> {% endfor %} This is pretty straight forward. What's not straight forward (for me) is the accompanying JS, since I'm not well-versed in JS. I'm trying the following: <script> var videos = document.querySelectorAll('video'); for (var i = 0; i < videos.length; i++) { var v = videos[i]; var sources = v.querySelectorAll('source'), lastsource = sources[sources.length-1]; lastsource.addEventListener('error', function(ev) { var d = document.createElement('div'); d.innerHTML = v.innerHTML; v.parentNode.replaceChild(d, v); }, … -
Implement hashid in django
I've been trying to implement hashids in django models. I want to acquire hashid based on model's id like when model's id=3 then hash encoding should be like this: hashid.encode(id). The thing is i can not get id or pk until i save them. What i have in my mind is get the latest objects id and add 1 on them. But it's not a solution for me. Can anyone help me to figure it out??? django model is: from hashids import Hashids hashids = Hashids(salt='thismysalt', min_length=4) class Article(models.Model): title = models.CharField(...) text = models.TextField(...) hashid = models.CharField(...) # i know that this is not a good solution. This is meant to be more clear understanding. def save(self, *args, **kwargs): super(Article, self).save(*args, **kwargs) self.hashid = hashids.encode(self.id) super(Article, self).save(*args, **kwargs) -
How to use display data from json retrieved from django-rest-framework?
I've cloned tour of heroes tutorial product from angular team where demo data is storing in in-memory-data-service.ts. Since my preferred backend is django-rest-framework, I need to link them together. For example, my heroes are translating from localhost:8000/api/v1/heroes/. What should I do except removing in-memory-data-service.ts to replace heroes list with provided by django backend via json? It would be great if you'll tell me do I need model declaration yet if rest-framework gives me full object structure stored in JSON. export class Hero { id: number; name: string; } -
Django Rest Framework Api populate post form
My authenticated user has a profile property defined this way (on my profile model class) user = models.OneToOneField(User, related_name='profile') Thanks to related_name, I can access 'profile' property from my 'user' object. I'm trying to develop end-points with Django Rest Framework to get and update my user profile. Here is my view : class ProfileViewSet(APIView): """ Edit connected user's profile """ queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer permission_classes = (IsOwner,) def get(self, request): if not request.user.is_authenticated: return Response({"error": _("User is not connected")}, status=status.HTTP_511_NETWORK_AUTHENTICATION_REQUIRED) profile = UserProfile.objects.get(pk=request.user.profile.id) serializer = UserProfileSerializer(profile) return Response(serializer.data) def post(self, request, format=None): if not request.user.is_authenticated: return Response({"error": _("User is not connected")}, status=status.HTTP_511_NETWORK_AUTHENTICATION_REQUIRED) serializer = UserProfileSerializer(data=request.data) if not request.user.is_authenticated: return Response(serializer.errors, status=status.HTTP_511_NETWORK_AUTHENTICATION_REQUIRED) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My problem is that the post form (at the bottom of the DRF Api page) is empty. I would like to populate the fields with the instance I am editing. And when I navigate through variables (with a breakpoint in visual studio) in my post method, the object in my serializer is not the same as I've in my get method (it's like it's a new or emty object). The user property of my profile is empty. How can … -
NoReverseMatch at / Python Django
I'm taking a Django course, and I'm having the next error: Reverse for 'products.views.product_detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I'm trying to send an argument to a view from a file that is called index.html My index.html looks like this: {% for pr in product %} <li> <a href="{% url 'products.views.product_detail' pr.pk %}">{{ pr.name }} </a> | {{ pr.description }} <img src="{{ pr.imagen.url }}" alt=""> </li> {% endfor%} I already declared the url that is associated: urlpatterns = [ url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='views.product_detail') ] And my views.py looks like this: def product_detail(request, pk): product = get_object_or_404(Product, pk = pk) template = loader.get_template('product_detail.html') context = { 'product': product } return HttpResponse(template.render(context, request)) Does someone know why is this error happening? Thanks. -
django testing without email backend
I want to test a view in my Django application. So I open the python shell by typing pyton and then I type from django.test.utils import setup_test_environment. It seems to work fine. Then I type setup_test_environment() and it says django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't need to send mails in my test, so why does Django wants me to configure an email back-end ? Are we forced to configure an email back-end for any test even if it doesn't need it ? -
Django: is there a short cut to use admin/change/ in my own app?
So I am writing a view that let a user edit/update/ fields of a model, before I realize that what I want is exactly admin/change. So I am wondering if there is shortcut to just use that in my app instead of reinventing the wheels? Of course I mean other than a direct link to admin/change.