Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom decorator - function has no attribute get
I'm trying to create my own decorator based on @cache_page decorator. My decorator should work exactly like @cache_page except when slug attribute of the view matches request.user.userprofile slug, then normally process the view and return not cached response Pseudocode: def profile(request,slug): # if not request.user = User.objects.get(userprofile__slug=slug): # return cache # else compute response and return it My decorator: def exclude_cache_for_request_user(*args, **kwargs): def exclude_cache_for_request_user_decorator(func): def func_wrapper(*fargs,**fkwargs): request = fargs[0] if request: user = getattr(request,'user',None) owner_slug = fkwargs.get('slug') owner = User.objects.get(userprofile__slug=owner_slug) if user==owner: return func(*fargs, **fkwargs) else: if len(args) != 1 or callable(args[0]): raise TypeError("cache_page has a single mandatory positional argument: timeout") cache_timeout = args[0] cache_alias = kwargs.pop('cache', None) key_prefix = kwargs.pop('key_prefix', None) if kwargs: raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix") return decorator_from_middleware_with_args(CacheMiddleware)( cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix ) return func_wrapper return exclude_cache_for_request_user_decorator This works if user matches the slug. Otherwise, it raises: Exception Value: 'function' object has no attribute 'get' Full traceback: File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/utils/deprecation.py" in __call__ 142. response = self.process_response(request, response) File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response 32. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /profiles/detail/cingo/ Exception Value: 'function' object has no attribute 'get' Do you know where is the … -
Django URL invalid literal for int() with base 10
I have a Location model setup in Django and I originally set it up so that the URL was /location/3/ using the primary key. but the client want to change it to use a slug of the location name. I created a slug field in the model. And changed the URL pattern in urls.py. urlpatterns = [ url(r'^(?P<pk>[\w-]+)/$', views.LocationsSingleView.as_view(), name='detail'), ] I can link to them fine. But when it tries to actually load that page I get an error: invalid literal for int() with base 10: 'eau-claire' Where eau-claire is the slug for that Location. Documentation doesn't say anything about this. A lot of people with this issue have issues with their view. But my view is super simple. So I don't know what's wrong. Here is my view: class LocationsSingleView(DetailView): model = models.Location -
How to save button value to databse in django?
I'm trying to create my first django app - sports predictions game. I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db: 1 - home team wins 0 - draw 2 - away team wins I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database? code on my game.html: {% csrf_token %} {{ form }} <input type="submit" value = 1> <input type="submit" value = 0> <input type="submit" value = 2> </form> and my view: def game(request, Game_id): thisgame = get_object_or_404(Game, pk=Game_id) nextgame = int(thisgame.id)+1 template = loader.get_template('polls/game.html') form = NewBetForm(request.POST or None) current_user = request.user allgames = Game.objects.all() betchoices = BetChoice.objects.all() context = { 'thisgame': thisgame, 'nextgame': nextgame, 'form': form, 'current_user': current_user, 'betchoices': betchoices,} if form.is_valid(): bet = form.save(commit=False) bet.gameid = Game.objects.get(id=Game_id) bet.userid_id = current_user.id bet.save() else: print (form.errors) and my form: class NewBetForm(forms.ModelForm): class Meta: model = GameBet fields = ['bet'] and the error I get is Bet - this field is required Thank you for all ideas! -
Can I use neomodel with Django's authentication system?
I want to use neomodel in my Django project. So I've created a simple User model like this to store users: class User(DjangoNode): uid = UniqueIdProperty() username = StringProperty(unique_index=True, required=True, label="Username") password = StringProperty(label="Password", required=True) name = StringProperty(label="Name", required=True) class Meta: app_label = "myapp" Now I need to authenticate the users. Can I use the standard Django's auth app for this or it only works with Django models? -
Django don't redirect to a external url
I have this view where I execute a redirect to an external site: def redpagopa(request): if request: return redirect('http://www.google.com/') else: return render_to_response('404.html') .... call=redpagopa(urlpa) # call of the redirect function, redirect doesn't work where urlpa is the url passed to the function redpagopa..in this code I explicited the address for example google. But the redirect doens't work. If I create an url entry in urls.py: url(r'^redpagopa/$', 'mopa.views.redpagopa', name='redpagopa') and in the browser I give the address: http://example.com/redpagopa the redirect works. I need when redirect is called, the browser be redirect on the specified url. There is some error in my code? I use Django v1.3, version mandatory. -
Authentication of different types of user of same name in django?
I have a model of teacher and student . If I created a Student and again create a teacher with same name and email and stuffs, It gets created .. Can't be a teacher and student of same people in a college. How to apply in rest api? -
Inplace edit form with Django + Bootstrap
Can someone guide me how can I create inplace edit forms for my table the easiest way? I have table with a lot of data. I want to edit that data directly from the table view just clicking on a row. I tried x-editable but it's not working with Bootstrap v4. -
why i am not able to view with classbased (list view )but for function based view it is working fine?
My question: why i am not able to view search only ayan rand's book with classbased list view? this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine. But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted . Views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect from django.views.generic import TemplateView,ListView,DetailView def store_listView(request,): queryset=Book.objects.all() context={ "objects_list":queryset } return render(request,'bookstores/store.html',context) class SearchBookDetail(ListView): template_name = "bookstores/store.html" queryset = Book.objects.filter(author__icontains='Ayan Rand') print("Ayan Rand query set", queryset) Urls.py: from django.conf.urls import url from django.contrib import admin from django.views.generic import TemplateView from store.views import (Home,ContactView,LoginView, store_listView, SearchBookDetail, book_createview, QuoteslistView, AyanRandBookDetail, quotesFunctionView) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',Home.as_view()), url(r'^contact/$',ContactView.as_view()), url(r'^login/$',LoginView.as_view()), url(r'^store/$',store_listView), url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()), url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()), url(r'^quotes/$',quotesFunctionView)] -
I don't understand the meaning of "create new view as a subclass"?
DRF REST AUTH DOC <- I'm following Facebook social login implementation (Step 3 and 4) I'm building Social Login with django-rest-auth, and I can't follow this simple step. It says Create new view as a subclass of rest_auth.registration.views.SocialLoginView with FacebookOAuth2Adapter adapter as an attribute: And what does subclass mean????? I put FacebookLogin view in [project-name]/urls.py and it seems right. But I put these lines of example code as shonw below in [project-name]/views.py and the social login doesn't work. from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter -
Django @cache_page based on condition
Can I specify a condition for cache_page decorator? I use @cache_page to cache userprofile detail page. The problem is that there is a different HTML for user about who is this detail page and for visitors. The particular user can update their profile picture etc. which visitors can't. if "peter" visits /userprofile/peter/ - he can change his profile picture if "andre" visits /userprofile/peter/ - it's readonly for him, so he can't change profile picture etc. If I use cache_page and the user "peter" is the first person who visited the page, it is cached, and another users/visitors like "andre" see this page like it was their profile. Can I cache for "peter", so owner==request.user and anybody else differently? @cache_page(1*60) @login_required def profile(request, slug): owner = User.objects.filter(userprofile__slug=slug).first() profile_picture_update_form = UserProfileUpdateProfilePictureForm(request.POST or None, request.FILES or None) return render(request, 'profiles/profile/profile.html',context={'owner': owner, 'profile_picture_update_form': profile_picture_update_form} ) EDIT: Moving @cache_page to URLConf won't help since it's the same url for user and for visitors. -
Django way to "Pre-cache" an existing database table?
I have a 200MB sized csv file containing rows where a key term is matched against a list of strings inside the second column. term_x | ["term_1","term_2"] term_y | ["term_1","term_2"] term_z | ["term_1","term_2"] My Django app is not configured to use any complex memory caching (Redis, Memcached) and in practice, I want to pass a term into the database table to retrieve the corresponding list value. Due to its size however, retrieving the list from the correct row takes around half a second to do, on top of other actions being performed while loading the page. Is it possible in Django to "pre-cache" this table upon server startup? i.e. add all of those values to the cache with the first column being the key? I have attempted something similar by overriding the "ready" method in my app.py to load the database table into the cache on startup, but I get null values when I try to use a term I know is in the table: print("Loading RS Lookup cache..."), #setup database connection.... cache_df = pd.read_sql_query("Select * from table_to_cache", engine) print("Table loaded") for index, row in cache_df.iterrows(): cache.set(row['term'], row['list_of_terms'], None) print("RS Table loaded") -
Django Rest Framework IsAuthenticated permission Error Anonymous user
I'm writing api using django rest framework using Token Authentication method written as below @api_view(['GET']) @permission_classes((IsAuthenticated, )) def ah(request, format=None): result = request.user.is_authenticated() content = {"hello":result} return Response(content) my settings are REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication' ) } MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', #'middleware.FirstTokenAuth.AuthenticationMiddlewareJWT', #'middleware.TokenAuthTest.JWTAuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', #'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] When I call this API using IsAdminUserpermission class The django restframework returns: 403 response "detail": "Authentication credentials were not provided." if the token wasn't provided in the header 401 response "detail": "You do not have permission to perform this action." if the token was not for admin user but the main problem is here when I set @permission_classes((IsAuthenticated, )) The API is called normally without returning 403 or 401 even if i didn't add a token to the header and the user returned is anonymous user. How can I prevent anonymous user from calling API and return 403 response for him. Any help Please !! -
Django Allow current user to some if some other user is also online/logged in
I'm trying to figure out how to check if some other user is logged in. I'm able to check if the current user is logged in with request.user.is_authenticated(), however, I want my current user to be able to see all other users of the site that are also logged in at the same time. How can this be done? -
Pycharm and Django TypeError for request.GET[value]
This is more of an annoyance than a real problem, but when using the following code: if request.method == "GET": device_id = request.GET['id'] The request.GET has the following error: Class 'type' does not define 'getitem', so the '[]' operator cannot be used on it's instance. A really great description of the problem (although in a different situation) can be found here: Pycharm: Type hint list of items I am simply trying to get rid of the PEP errors in PyCharm without disabling them. Any thoughts on how to change the above code? Thanks! -
How to use Django ORM in Wagtail when querying outside of Page context?
I am using Wagtail with another cart application. They are using the same DB. By now I have been using def get_context(self, request): context = super(HomePage, self).get_context(request) blogs = Blogs.objects.all() context['blogs'] = blogs return context However, now I need data that is outside the context of the page and I am using a custom query e.g. def my_custom_sql(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM product_product") row = cursor.fetchone() return row Is there a way to use the ORM instead and get a QuerySet? In other words I want to query the DB from all the page methods with the ORM agnostic of the context that I am in. -
uwsgi deploy django failed to open python file blog/wsgi.py
when i use uwsgi deploy my django application,occur this error your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 71400 bytes (69 KB) for 2 cores *** Operational MODE: threaded *** failed to open python file blog/wsgi.py unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 2040, cores: 2) (py3env) [root@host blog]# pwd /yuyang/djangoblog/djangblog/blog (py3env) [root@host blog]# ls celery.py __init__.py mywsgi.ini __pycache__ settings.py urls.pywsgi.py(py3env) -
Django-Sphinx RuntimeError: Model class models.Project doesn't declare
I am attempting to generate a html documentation with Sphinx of a django project. I am getting the following error when executing make html on windows cmd. > C:\django_project\docs\source\models.rst:4: WARNING: autodoc: failed to > import module 'models'; the following exception was raised: Traceback > (most recent call last): File > "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\sphinx\ext\autodoc.py", > line 658, in import_object > __import__(self.modname) File "C:\django_project\project_name\models.py", line 8, in <module> > class Project(models.Model): File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\django\db\models\base.py", > line 118, in __new__ > "INSTALLED_APPS." % (module, name) RuntimeError: Model class models.Project doesn't declare an explicit app_label and isn't in an > application in INSTALLED_APPS. Thanks for your help! -
How import a function from another view with Django?
I have this folder hierarchy: |---- saga |---- core |---- views.py |---- study_time |---- views.py On my study_time/views.py, I have this functions: def study_time(request): def tasks_subjects(week_day, key): #Code here return __tasks def day_studies(week_day): __tasks_subjects = tasks_subjects(week_day, 0) #Code here return __studies return render(request, 'study_time.html', context) On my study_time/views.py, I need the day_studies() function, so I'm importing like this: from saga.study_time.views import day_studies def home(request): day_progress = day_studies(datetime.date.today().isoweekday()) But I'm getting the error: ImportError: cannot import name 'day_studies' How can I make this importation? I don't want to reply all code. -
How to change the Column Names of a database created by Django (from models.py)?
So I have a MySQL Database in my local PHPMyAdmin with DBs and Tables already filled in with data. I have to now port that DB into django. For example, the name of a table in the DB is "ratings". So using django, I have to first create an app named something (let's say "website") and then I can add the model ratings to that app. This creates a table "website_ratings" in the DB. Which is not what I want, I want the name of the table to be just ratings. Is there any way to get this done? -
APP: ERROR (no such file) error happens
APP: ERROR (no such file) error happens. I wanna run APP server which I made Python&Django on Nginx & Gunicorn & Supervisor.I could run Nginx & Gunicorn's install command, so now I have to use and run Supervisor.I run command supervisord & supervisorctl reread ,it was successful.But when I run command supervisorctl start APP,APP: ERROR (no such file) happens.Why does this error happen but can't I use only this command ?What is wrong?How should I fix this? -
Running Django server on localhost
I would like to run a Django server locally using a local IP. I have localhost mapped here: $ head -n 1 /etc/hosts 127.0.0.1 localhost I have this chunk of code in my settings.py: import os ALLOWED_HOSTS = ['HERE.IS.MY.IP', 'localhost', '127.0.0.1'] print "ALLOWED_HOSTS: {}".format(ALLOWED_HOSTS) In my mysql database I have this site table: mysql> select * from django_site; +----+--------------------+----------------+ | id | domain | name | +----+--------------------+----------------+ | 1 | example.com | example.com | | 5 | HERE.IS.MY.IP:8000 | projectsdb | | 8 | 127.0.0.1:8000 | projectsdb | | 9 | localhost:8000 | projectsdb | +----+--------------------+----------------+ I run the server locally on 127.0.0.1: $ python manage.py runserver 8000 ALLOWED_HOSTS: ['HERE.IS.MY.IP', 'localhost', '127.0.0.1'] Performing system checks... # ... Django version 1.10.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. If I go to this address http://HERE.IS.MY.IP:8000 it works. But of course I'd like to open it using a local IP such as http://localhost:8000 or http://127.0.0.1:8000. But this does not work. What am I missing? -
DRF Serializer readable - writeable non-model field
On a project with Django / DRF; I have the following model structure: class City(models.Model): name = models.CharField(max_length=100) class Company(models.Model): city = models.ForeignKey(City) . . And following serializer structure for Company model: class CompanySerializer(serializers.ModelSerializer): city_name = serializers.CharField(write_only=True) . . class Meta: model = Company fields = ('city_name',) While creating a company through the serializer, user provides a city_name, I create a new city with that name if not exists or use an existing entry if exists. In this structure, I want to be able to return city_name field while returning companies. It is not a field on the model, so I could use SerializerMethodField normally, but I also want this field to be writable as well. Do I have any options here? -
VariableDoesNotExist inplaceeditform on Django
so, basically I have this player_list.html {% extends 'football/base.html' %} {% load inplace_edit %} {% inplace_static %} {% block content %} <div class="body"> <h3>Player list</h3> <table style="width:100%"> <tr> <th>No.</th> <th>Name</th> <th>1st position</th> <th>2nd position</th> <th>3rd position</th> <th>Age</th> {% if user.is_authenticated %} <th>Remove</th> {% endif %} </tr> {% for player in players %} <tr> {% if user.is_authenticated %} <td>{{ forloop.counter }}</td> <td>{% inplace_edit "player.name" %}</td> <td>{% inplace_edit "player.first_Pos" %}</td> <td>{% inplace_edit "player.second_Pos" %}</td> <td>{% inplace_edit "player.third_Pos" %}</td> <td>{% inplace_edit "player.age" %}</td> <td><a href="{% url 'player_remove' pk=player.pk %}" onclick="return confirm('Are you sure you want to remove this player?')">remove</a></td> {% else %} <td>{{ forloop.counter }}</td> <td>{{ player.name }}</td> <td>{{ player.first_Pos }}</td> <td>{{ player.second_Pos }}</td> <td>{{ player.third_Pos }}</td> <td>{{ player.age }}</td> {% endif %} </tr> {% endfor %} </table> </div> {% endblock %} and I get this error Failed lookup for key [ "player] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, {u'players': <QuerySet [<Player: Juara>, <Player: Teguh>, <Player: Champion>, <Player: Jaguh>]>}]" and this is my views for the player_list #football_player def player_list(request): players = Player.objects.all().order_by('first_Pos_id') return render(request, 'football/player_list.html',{'players':players}) Do I need to do any modification in inplace_edit.py or else? I did refer to this and this. -
Update a field on a different model using django signals and GenericForeignKey
Using Django 1.11 and Python 3.5 I am working on a points app where a source user assigns points to a target user for completing tasks. In the end, I want to keep a total points count in the User profile. That total has to update via a post_save signal from the points app. I have the models and signal set up. But the points being assigned in the points app are not being updated in and totaled in the points app. Can someone help me make this work? User model from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) image = models.ImageField(upload_to='user/%Y/%m/%d', default='') point_total = models.IntegerField(default=1) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) Points models import datetime from django.db import models from django.db.models import Count, Min, Sum, Avg from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model User = get_user_model() class PointValue(models.Model): """ Stores an action and … -
Django: DateTimeField is off by an hour when passed to strftime method
I am trying to get a DateTimeField element to render appropriately. Updating the timezone field in my settings.py file allowed me to display the correct time, I did so by simply modifying one field in said file: TIME_ZONE = 'Europe/Berlin' But I am using this method in order to format it: def displayTime(self): return self.added.strftime('%a %H:%M:%S %d/%m/%y') The problem is that when I use this method, the time is off by an hour again, as if I never edited the timezone field inside settings.py.