Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Clean workaround for Pip issues under PyCharm that won't entail direct CLI access
I'd like to be able to document how to add a package to a VirtualEnv under Python 3.6 in PyCharm. “Unable to locate finder for 'pip._vendor.distlib'” error when using "pip install virtualenv" , for one example, articulates what appears to be the same basic issue, a known issue with current PyCharm, resolved by command line commands. I like the LUM CLI and it is like a native language to me, but I am trying to document things clearly for developers who may or may not be comfortable with any Unix-like CLI, and the instructions in the question above ask people to resolve the matter through the CLI. Is there any way either to fix the Pip issues from within PyCharm as IDE, or to attach a project to a VirtualEnv and install a package represented on PyPI? The error message I'm getting (for the curious) is: Collecting bleach Downloading bleach-2.0.0-py2.py3-none-any.whl Collecting html5lib>=0.99999999 (from bleach) Downloading html5lib-0.999999999-py2.py3-none-any.whl (112kB) Collecting six (from bleach) Downloading six-1.10.0-py2.py3-none-any.whl Collecting setuptools>=18.5 (from html5lib>=0.99999999->bleach) Downloading setuptools-34.3.2-py2.py3-none-any.whl (389kB) Collecting webencodings (from html5lib>=0.99999999->bleach) Downloading webencodings-0.5.tar.gz Collecting appdirs>=1.4.0 (from setuptools>=18.5->html5lib>=0.99999999->bleach) Downloading appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools>=18.5->html5lib>=0.99999999->bleach) Downloading packaging-16.8-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools>=18.5->html5lib>=0.99999999->bleach) Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB) Installing collected packages: six, appdirs, … -
Django Nested Loops
I managed to inherit a website built with spaghetti code and I need some help. The website is used to inventory the servers at the company I am working at. Having picked up all my Django experience as I go, I am still learning and have been stuck for a few days trying to perfect a nested loop. Basically the way I am trying to get it to work is by taking the server id and drive serial numbers. You select the Server ID, then this will generate a table for each drive serial number. Under each table it will list all the drives found with that serial and then move onto the next table & serial number. Now I have managed to get this working but it keeps repeating unnecessary tables (same serial number will have multiple copies of that table) and I can't for the life of me figure it out. I know my loop is probably not great but I am still learning as I go. I think whats happening is the loop is going through every instance of the serial number and creating the table for it. Here is my code. Hopefully it pastes ok. Thanks. … -
Django - option for public or private input
I am developing a django project, and I am trying to give users the choice of making their input public or not, as at the moment they can only see what they create. I was wondering how I would alter my model to give the user the option of choosing and if there is anything else that I need to change to include it in my form (probably forms.py and if so what do I want as the field)? This is my current model for it: class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text And here is forms.py: from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80})} Thanks Milo -
ERR_SSL_PROTOCOL when entering heroku app
I'm trying to deploy a React app to Heroku with a Django backend. In our initial request to check if the client has a session, the request is made to https://<myapp>.herokuapp.com:80/api/v1/auth/status/, causing the error mentioned in the title. Manually requesting this url without the port (i.e. https://<myapp>.herokuapp.com/api/v1/auth/status/) works as expected, so how do I get the requests to go to the correct url? It's very weird that the port is being added, as the url is hardcoded. -
authentication django app with ldap3
I have problem with authentication users in my django app. I am using Python 3.5 and Django 1.10. I wrote simple bind configuration to check if user is realy user from database: username = request.POST['username'] password = request.POST['password'] server = Server(LDAP_AUTH_URL) c = Connection(server, user=LDAP_AUTH_CONNECTION_USERNAME, password=LDAP_AUTH_CONNECTION_PASSWORD) c.open() c.bind() if c.bind(): user_search_filter = '(uid={})'.format(username) c.search(search_base=LDAP_AUTH_SEARCH_BASE, search_filter=user_search_filter, search_scope=SUBTREE) username = c.response[0]['dn'] if c.rebind(user=username, password=password): return HttpResponseRedirect(next) but now I don't know what to do with it, in django we have of course something like this: user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect(next) else: return render(request, 'login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'login.html', {'error_message': 'Invalid login'}) but in this situation we have to have user account in our base not from ldap authorization. so I would like to get authorization from django when I am logging by ldap to have access to any other view with "@login_required" Maybe something is wrong with my thinking about ldap and ldap3 for Python >3. Anybody can help me or give me usefull links? -
Set range in IntegerRangeField
I have a model: from django.contrib.postgres.fields import IntegerRangeField class Album(models.Model): rating = IntegerRangeField(default=0) I want to set maximum and minimum value for default validation purpose. There is already an answer , but that validation will not run automatically. So How to set a min and max value in the rating field ? -
Error with Django Template rendering No Reverse Match
Can anyone help me with this issue? I saw all posts which are similar to my issue, but I can't fix this up. Error: Reverse for 'commit_add' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['git/project/(?P[0-9]+)/add_commit/$'] views.py class CommitCreate(CreateView): template_name = 'layout/project_commit_detail.html' model = Commit fields = ['user', 'project', 'branch', 'commit_title', 'commit_body'] success_url = reverse_lazy('git_project:index') html form <div class="container-fluid"> <a href="#demo1" class="btn btn-info btn-block" data-toggle="collapse">Add New Commit</a> <div id="demo1" class="collapse" > <form class="form-horizontal" action="{% url 'git_project:commit_add' project.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if user.is_authenticated %} <label for="user">Commit created by: "{{ user.username }}"</label><br> <input id="user" type="hidden" name="user" value="{{ user.id }}"> <label for="project">Commit for project: "{{ project.proj_title }}"</label><br> <input id="project" type="hidden" name="project" value="{{ project.id }}"> <label for="branch">Branch: </label> <select> {% for branch in all_branches %} <option id="branch" name="branch">{{branch.branch_name}}</option> {% endfor %} </select><br> <label for="commit_title">Commit Title: </label> <input id="commit_title" type="text" name="commit_title"><br> <textarea id="commit_body" name="commit_body" rows="5" cols="50" placeholder="Commit body..."></textarea><br> <button type="submit" class="btn btn-success">Commit</button> {% endif %} </form> </div> url.py url(r'project/(?P<pk>[0-9]+)/add_commit/$', views.CommitCreate.as_view(), name='commit_add'), model.py class Commit(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) project = models.ForeignKey(Project, on_delete=models.CASCADE, default=0) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, default=0) commit_title = models.CharField(max_length=64) commit_body = models.CharField(max_length=16384) commit_date = models.DateTimeField(default=timezone.now) I don't know why is happening. Can anyone help … -
Django allauth template integration trouble
I'm new to coding, Python and Django, but trying to handle that :) Decided to learn while trying to make a real project. Almost every trouble I get is solvable with the help of Google, but now I'm stucked at one point, and cannot find any information about that. The thing is that I'm using a template from Themeforest called Jango (he-he :)) It can be find here: link. As you can see on that page, it has nice looking 'Sign In' button, and when you click it, sign in form appears. So my question is how could I integrate that kind of form with allauth app. Is it possible? -
Django celery beat error: TypeError('astimezone() argument 1 must be datetime.tzinfo, not tuple',)
I'm using Django 1.8 and celery 4.0.2. When I start celery beat, it throws a TypeError celery beat v4.0.2 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2017-03-13 20:38:22 Configuration -> . broker -> redis://127.0.0.1:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s) [2017-03-13 20:38:23,094: CRITICAL/MainProcess] beat raised exception <type 'exceptions.TypeError'>: TypeError('astimezone() argument 1 must be datetime.tzinfo, not tuple',) Traceback (most recent call last): File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/apps/beat.py", line 107, in start_scheduler service.start() File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/beat.py", line 537, in start interval = self.scheduler.tick() File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/beat.py", line 255, in tick for e in values(self.schedule)] File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/beat.py", line 134, in is_due return self.schedule.is_due(self.last_run_at) File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/schedules.py", line 612, in is_due rem_delta = self.remaining_estimate(last_run_at) File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/schedules.py", line 601, in remaining_estimate return remaining(*self.remaining_delta(last_run_at, ffwd=ffwd)) File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/schedules.py", line 538, in remaining_delta last_run_at = self.maybe_make_aware(last_run_at) File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/schedules.py", line 81, in maybe_make_aware return maybe_make_aware(dt, self.tz) File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/utils/time.py", line 326, in maybe_make_aware dt, timezone.utc if tz is None else timezone.tz_or_local(tz), File "/home/renq/PycharmProjects/Kimi/.pyenv/lib/python2.7/site-packages/celery/utils/time.py", line 301, in localize dt = dt.astimezone(tz) TypeError: astimezone() argument 1 must be datetime.tzinfo, not tuple My celery settings are CELERY_BROKER_URL = 'redis://127.0.0.1:6379', CELERY_TIMEZONE = 'Asia/Shanghai', CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler', CELERY_RESULT_BACKEND = 'django-db' I … -
How to pass <form name> attribute to request.POST in Django 1.10 views?
I have a page with questions list. Every question has radio button form with several answers. To write this answers to db in need id of every question. As I figured out I can pass form="name" into but it makes all the fields and forms as "required" and it's not what I'm seeking for. Now I'm trying to pass attribute to view as it contains question id. Maybe I'm moving in the wrong direction? -
difference between django custom login view and django custom authentication backend?
flow chart of the login process As shown in the diagram i want to redirect the user that has not yet created a fullname to the url('profile:profile_create'). If the user has already created a fullname then redirect to the url('profile:profile_view') What is the better way of handling the process? custom login view or custom authentication backend? -
Choosing file path/url from FileInput form
I want to store a string that stores a file path "C:/myfile.txt". I've tried initially with Django's FileField but that uploads the file to the server which it is not what I want. Right now I am circumventing this by having a textfield and people just copy paste the file URL but I was trying to get it by using forms.FileInput() in order to choose the file, but then I only want to retrieve its path which I haven't been able to. widgets = {'data': forms.DateInput(attrs={'id': 'datepicker'}),'fileloc': forms.FileInput() } By doing I am able to have a Browse input on my form and allows me to select the file but it fails to validate the form. I need to convert the FileInput to string retrieving its File Path. Has anyone encountered this before and has any idea how can I solve it? -
How to login via Splinter?
I have a step that is implemented thus: first, I create a user and a group making sure the user is not in the group -- thus unauthorised. Then, I attempt to log said user in. The code follows. @given(u'an unauthorised user is logged in') def step(context): from django.contrib.auth.models import User from django.contrib.auth.models import Group context.user = User.objects.create_user(username='JaneDoe', email='jane.doe@example.com', password='S3kr3t') context.group = Group.objects.create(name='book keepers') assert context.user.groups.filter(name='book keepers').exists() is False context.browser.visit('/login/') context.browser.fill('username', 'janedoe') context.browser.fill('password', 'S3kr3t') context.browser.find_by_name('login').first.click() # ← the name is correct. The context.browser = Browser('django') is an instance of from splinter.browser import Browser. However, at the end of this step the user is not logged in: How can I assert that the user is indeed logged in? What am I doing wrong for the user not being logged in? -
Is it good to use Angular along with Django
I'm building an application where i'm using Django as my web framework. I'm confused on using Angular along with Django because of the handle bar template syntax. If I go with Verbatim template tag, will it cause any problem in future? -
django tables how to detect if table is empty
I am new to django and web development and based on examples and help on SO, I have pieced together something which takes a model and renders it in a django-table. My template code is basically as follows: {% block content %} {% load static %} {% load render_table from django_tables2 %} <div class="function-page"> <div class="table-form"> <div class="function-container"> {% render_table reviews %} </div> </div> </div> {% endblock %} The view is as follows: @login_required(login_url="login/") def review(request): table = DummyTable(DummyModel.objects.all()) form = DummyForm() RequestConfig(request, paginate={"per_page": 10}).configure(table) return render(request, 'review.html', {'reviews': table, 'DummyForm': form}) This works fine. However, what I would like to do is show a message to the user saying that there are no records when the database table is empty. In the current setting, it shows an empty table with the columns which is probably not the best from a usability point of view. -
Django returns 404 after using restframework into existing project
I have working project ready, I am adding REST API for APIViews for like functionality after adding API into URL it is giving 404 Views.py class PostLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, id=None, format=None): obj = get_object_or_404(Post, id=id) url_ = obj.get_absolute_url() user = self.request.user updated = False liked = False if user.is_authenticated(): if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { "updated" : updated, "liked" : liked } return Response(data) urls.py from django.conf.urls import url from django.contrib import admin from posts import views from rest_framework import routers app_name = 'posts' urlpatterns = [ url(r'^$', views.post_list, name='list'), url(r'^create/$', views.post_create, name='create_post'), url(r'^(?P<id>[\w-]+)/$', views.post_detail, name='detail'), url(r'^(?P<id>[\w-]+)/edit/$', views.post_update, name='post_update'), url(r'^api/(?P<id>[\w-]+)/like/$', views.PostLikeAPIToggle.as_view(), name='like-api-toggle'), url(r'^(?P<id>[\w-]+)/like/$', views.PostLikeToggle.as_view(), name='like-toggle'), url(r'^(?P<id>[\w-]+)/delete/$', views.post_delete),] models.py class Post(models.Model): user = models.ForeignKey(User,default=0) title = models.CharField(max_length=140) image = models.ImageField(upload_to = upload_location, null=True, blank=True, height_field="height_field", width_field = "width_field") likes = models.ManyToManyField(User,blank=True, related_name = 'post_likes') height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) def get_api_like_url(self): return reverse("posts:like-api-toggle", kwargs={"id": self.id}) def get_like_url(self): return reverse("posts:like-toggle", kwargs={"id": self.id}) class Meta: ordering = ["-timestamp" , "-updated" ] … -
Form data not getting saved in django
Since django User model had only few fields in it, I made a custom model and used it's ModelForm to save data to User model and the custom model. The models.py is as shown below from django.db import models from django.contrib.auth.models import User # Create your models here. import datetime class Post(models.Model): Author=models.ForeignKey(User) title=models.CharField(max_length=66) content=models.TextField() created_date=models.DateField(default=datetime.datetime.now()) published_date=models.DateField() def publish(self): self.published_date=datetime.datetime.now() self.save() class UserDetails(models.Model): #the custom model uname=models.CharField(max_length=55) first_name=models.CharField(max_length=55) last_name=models.CharField(max_length=55) age=models.IntegerField() contact=models.CharField(max_length=13) email=models.EmailField() pword=models.CharField(max_length=55) modelform : class RegisterForm(ModelForm): class Meta: model=UserDetails fields=['uname','pword','first_name','last_name','email','contact'] the views.py is like this from django.shortcuts import render from .models import UserDetails # Create your views here. from django.contrib.auth import authenticate,login,logout from .forms import RegisterForm,LoginForm,PostForm from django.contrib.auth.models import User from django.db import IntegrityError def register(request): if request.method=='POST': form=RegisterForm(request.POST) try: if form.is_valid(): form.save() uname=form.cleaned_data['uname'] fname=form.cleaned_data['first_name'] pword=form.cleaned_data['pword'] email=form.cleaned_data['email'] contact=form.cleaned_data['contact'] lname=form.cleaned_data['last_name'] user=User.objects.create_user(uname,password=pword,email=email) user.last_name=lname user.save() #form.save() #stuff after registration message="registration done! login again" return render(request,'register.html',locals()) except IntegrityError: message="username already exists!! try another" else: form=RegisterForm() return render(request,'register.html',locals()) The problem is that even if I make a fresh entry to the RegisterForm, the 'message' I get is, username already exists!! try another. The auth.User model is getting updated but UserDetails is not. What am I doing wrong? (spare me if this is a stupid … -
Django view not updating after changes in model
I am running into a problem with a Django project I am currently working on. I have a view in which I create a model instance via a POST request: class CreatePollView(View): template = "polls/create_poll.html" @method_decorator(login_required) def post(self, request): question_text = request.POST['question'] pub_date = now() new_question = Question(question_text=question_text, pub_date=pub_date) new_question.save() options_list = request.POST.getlist('options') for option in options_list: option_text = option new_option = Option(option_text=option_text, question=new_question) new_option.save() return HttpResponseRedirect(reverse('polls:detail', args=(new_question.id,))) This works fine. I can add the question and its options to the DB and see that it has been added in the admin. But when I then call my index.html, in which I list all the question objects, it doesn't update. class IndexView(View): template = loader.get_template('polls/index.html') questions = Question.objects.all() context = { 'question_list': questions, } def get(self, request): return HttpResponse(self.template.render(self.context, request)) And the template: {% extends 'homepage/base.html' %} {% block content %} <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>All Polls:</h1> <div> {% for question in question_list %} <p><a href="{{ question.pk }}">{{ question }}</a></p> {% endfor %} <a href="new_poll" class="btn btn-primary">New Poll</a> </div> </div> </div> {% endblock %} When I build an error into the view, then fix it and run the code again it updates the list. Question.objects.all() But other than that … -
DeclarativeFieldsMetaclass object argument after ** must be a mapping, not int
I am trying to pass kwargs to my forms.py file, when the form is loaded I get an error saying my car_id is not defined on my forms.py file. I know this is because of the below line of code but I do not know how to fix it. form = SelectCarModelForm() forms.py def __init__(self, *args, **kwargs): self.car_id = kwargs.pop('car_id', None) super(SelectCarModelForm, self).__init__(*args, **kwargs) self.fields['car_model'] = forms.ModelChoiceField( empty_label = "Select a Model", queryset = CarModel.objects.filter(model=car_id), widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}), required=True ) view if request.method == "POST": form = SelectCarModelForm(request.POST) if form.is_valid(): model = form.cleaned_data['car_model'] # Go to the next form in the process. return redirect('view_car') # Initial form else: form = SelectCarModelForm() return render( request, template_name = 'cars/forms/view_car_models.html', dictionary = { 'form':form, } ) -
Diffrance Between {{ }} and {% %}
I am new In Django . and confusing in HTML Template syntax {{ }} And {% %} what is difference between these two tags -
ValidationError raises when updating
I have defined a ValidationError. It works fine but when I try to update my form it raises. Due to this I can not update my form anymore. It is defined as following: def clean_examination(self): new_exa = self.cleaned_data.get('examination') try: old_exa=GeneralData.objects.get(examination=self.cleaned_data.get('examination')) except GeneralData.DoesNotExist: return new_exa if old_exa: raise forms.ValidationError('Object with this examination already exists!') return new_exa Is it possible to "deactivate" my ValidationError if the form should be updated? Additional Information: My Model: class GeneralData(models.Model): examination = models.ForeignKey(Examination, on_delete=models.CASCADE, help_text='This value is pasted in automatically and is not editable!') attr1= models.FloatField() attr2= models.FloatField() My UpdateView: class GeneralDataUpdate(LoginRequiredMixin, generic.UpdateView): model = GeneralData form_class = GeneralDataCreateForm template_name_suffix = '_update_form' login_url = 'member:login' def get_success_url(self): return reverse('member:detail', kwargs={'pk': self.get_object().examination.patient_id}) def get_context_data(self, **kwargs): context = super(GeneralDataUpdate, self).get_context_data(**kwargs) context['action'] = reverse('member:generaldata-update', kwargs={'pk': self.get_object().id}) return context My Update-URL: url(r'examination/(?P<pk>[0-9]+)/generaldata/update/$', views.GeneralDataUpdate.as_view(), name='generaldata-update') -
Simplify multiple optional filters in Django
I posted a question a few hour ago and it was marked as duplicated (it was not) and I couldn't find my answer here so I had to find it in an other place. Here was the question: How to simplify many optional filters in django. For example: model = "some_rare_model" if max_speed: if year: if color: cars = Car.objects.filter(model=model,max_speed=max_speed,year=year,color__icontains=color) else: car = Car.objects.filter(model=model,max_speed=max_speed,year=year) else: if color: cars = Car.objects.filter(model=model,max_speed=max_speed,color__icontains=color) else: cars = Car.objects.filter(model=model,max_speed=max_speed) else: if year: if color: cars = Car.objects.filter(model=model,year=year,color__icontains=color) else: car = Car.objects.filter(model=model,year=year) else: if color: cars = Car.objects.filter(model=model,color__icontains=color) else: cars = Car.objects.filter(model=model) How to simplify that code? -
Get the latest objects and order by a different field
I would like to run a query that : Get from the table "Media" the latest objects and order it based on "likes". example : media_id - created_at - likes media_1 - 11/03/2017 - 12 media_2 - 10/03/2017 - 13 media_1 - 06/03/2017 - 8 media_3 - 02/03/2017 - 6 would return : media_id - created_at - likes media_2 - 10/03/2017 - 13 media_1 - 11/03/2017 - 12 media_3 - 02/03/2017 - 6 I tried to run this, but it throws an error message : MyQuery.order_by('media_id').distinct('media_id').order_by('-likes') -
Django 1.10 NoReverseMatch - exits but does not match?
I wanted to build a 'list' view where all the images in the database will be displayed. This is the template : {% extends "base.html" %} {% block title %}Your images{% endblock %} {% block content %} <ul> {% for picture in images %} <a href="{% url "detail" id=picture.id slug=picture.slug %}"> <img src="{{ picture.image.url }}" class="image-detail"> </a> {% endfor %} </ul> {% endblock %} And the list and detail urls : url(r'^detail/(?P<id>\d+)/(?P<slug>[\w]+)/$',views.image_detail,name='detail') url(r'^list/$', views.image_list, name='list') When the user clicks a picture, he should be redirected to that page 'detail' view . def image_detail(request, id, slug): image = get_object_or_404(Image, id=id, slug=slug) return render(request, 'images/image/detail.html', {'section': 'images', 'image': image}) def image_list(request): images = Image.objects.all() return render(request,'images/image/list.html',{'images':images}) As it can be seen, the 'detail' view has 2 arguments : id and slug. In the template above I get those arguments to the respective picture's id and slug (id=picture.id slug=picture.slug). After I did run the server, when I tried to access the list page on my website, I got an "NoReverseMatch" error : Exception Value: Reverse for 'detail' with arguments '()' and keyword arguments '{'id': 1, 'slug': 'django-and-duke'}' not found. 0 pattern(s) tried:[]. I started up the shell, imported the Image model, and I … -
Django session last_touch
my middleware code is as below: class AutoLogout(object): def init(self, get_response): self.get_response = get_response def __call__(self, request): # if not request.user.is_authenticated(): if (request.COOKIES == None): # Can't log out if not logged in return if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0): try: logout(request) del request.session['last_touch'] except KeyError: pass else: request.session['last_touch'] = datetime.now() return self.get_response(request) The eroor i am getting is KeyError: 'last_touch'