Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get the highlight tag to dynamically detect and display the field(s) which contains a query match in Haystack?
I'm trying to create a search results page with django-haystack and elasticsearch backend, and it's working just fine in most cases, but I'm trying to account for the following edge case in a way that respects DRY. Let's suppose I have the following setup: apps/myapp/models.py from django.db import models class MyModel(models.Model): title = models.CharField() fieldA = models.Charfield() fieldB = models.Charfield() fieldC = models.Charfield() apps/myapp/search_indexes.py from haystack import indexes from .models import MyModel class MyModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') fieldA = indexes.CharField(model_attr='fieldA') fieldB = indexes.CharField(model_attr='fieldB') fieldC = indexes.CharField(model_attr='fieldC') def get_model(self): return MyModel templates/search/includes/myapp/mymodel.html {% load highlight %} <div class="result"> <h3><a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a></h3> <p>{% highlight result.object.fieldA with query max_length 200 %}</p> </div> templates/search/indexes/myapp/mymodel_text.txt {{ object.title }} {{ object.fieldA }} {{ object.fieldB }} {{ object.fieldC }} As you can see in my mymodel.html template, I'm assuming that my query matched the contents of fieldA because I'm passing fieldA to the highlight tag. What if my query matched the contents of fieldB, but not fieldA? How do I get the highlight tag to dynamically detect and display the field that contains a match for my query? -
Django Ajax Form Works but Throws 500 (Internal Server Error)
I've researched this to death, but have not found exactly what I need to get the last part of my form completed. I have a simple 2-field form in my footer for newsletter signup. I am utilizing an inclusion_tag since I need to include the form on every page. The form works; with a couple of hitches, for arguments sake, it works, I hit submit and the email is sent to me. The problem is that I am getting a 500(internal server error) in console on the ajax url. I am assuming that its not really supposed to redirect to the url, but rather just process the form. Below is my code; I hope someone can easily point out my issues. Thanks. Inclusion Tag @register.inclusion_tag('includes/cta_form.html', takes_context=True) def footer_newsletter_signup(context): title = 'Newsletter Signup' form = CTASignupForm() context = { 'form': form, 'title': title, } return context Ajax $('#sendSignupForm').click(function (e) { e.preventDefault(); var mForm = $('#signupForm').serialize(); console.log(mForm); $.ajax({ type: 'POST', url: '{% url 'pages:cta_signup' %}', data: mForm, success: function (data) { $("input").val('') }, error: function (data) { $("input").addClass('error') } }) }) cta_form.html <form action="{% url 'pages:cta_signup' %}" method="POST" id="signupForm"> {% csrf_token %} {{ form.name }} {{ form.email }} <button class="btn btn-black no-margin-bottom … -
Templates not loading in Django
I've been following a django tutorial, hoping to get some templates working that I created. It looks like this. app/templates └── app └── profile.html Settings file looks like this: """ Django settings for demonstration project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SOME_KEY_NON_PROD_TESTING_LOCALLY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ] 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', ] ROOT_URLCONF = 'demonstration.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'demonstration.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = … -
Using dokku run to dump data from Django
I'm trying to run python manage.py dumpdata ... within a Dokku app, but have not been able to get things to work. I'd like to occasionally dump the database so that I can replicate it on a development machine. Here is what I've tried so far: # Creates 20161207.json with 'python manage.py dumpdata app1 app2 app3' as the first line $> dokku run myapp 'python manage.py dumpdata app1 app2 app3 > /app/storage/db_dumps/20161207.json' # Dumps a bunch of json to the terminal $> dokku run myapp 'python manage.py dumpdata app1 app2 app3' # Of course, I can then save the output... $> dokku run myapp 'python manage.py dumpdata app1 app2 app3' > ~/db_dump.json # but I'd rather put this in shared storage for the sake of staying organized Any thoughts on why the first command doesn't work? EDIT: Resolved with: $> dokku run myapp '`python manage.py dumpdata app1 app2 app3` > /app/storage/db_dumps/20161207.json' -
How do I control the order of form fields in Django?
Given that I have a generic form like this: from django import forms class TimesForm(forms.Form): hours = forms.DecimalField() description = forms.CharField() topic = forms.CharField() And I want to render this form in html, what is the best way to dynamically control the order of appearance? In other words, the user should be able to control the order in which those input fields are displayed on the screen. While I was able to iterate through the fields like this: {% for field in form %} {{field}} {% endfor %} I did not find a proper way to control the order of appearance of the input fields. How do I best do that? -
Django/Sendgrid Form HTTP Error 400: Bad Request
I'm getting an HTTPError: HTTP Error 400: Bad Request error when I try to send my Django form using Sendgrid. I have confirmed that there is a Sendgrid key in the envvars. Here is my code: settings.py # sendgrid EMAIL_BACKEND = "sgbackend.SendGridBackend" SENDGRID_API_KEY = get_env_variable('SENDGRID_KEY') contact_form.html {% load static %} {% load app_tags %} <div id="contact-form"> <p class="thank-you" style='display:none;color:#ee9836;'>Thank you for your message. We'll be in contact with you soon.</p> <form role="form" action="" method="post" class="form panel-body"> {% csrf_token %} {{ form }} <button class="btn btn-primary pull-right" type="submit">Submit</button> </form> </div> My form view is in a template tag: app_tags.py from django import template from django.shortcuts import render, redirect from django.template.loader import get_template from django.core.mail import EmailMessage from django.template import Context from .forms import ContactForm register = template.Library() # contact form for footer @register.inclusion_tag('contact_form.html') def contact(request): form = ContactForm if request.method == 'POST': contact_form = form(data=request.POST) if contact_form.is_valid(): contact_name = request.POST.get('name', '') contact_email = request.POST.get('email', '') contact_message = request.POST.get('message', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'contact_message': contact_message, }) content = template.render(context) print content email = EmailMessage( "Contact Form", content, "contact@site.com" +'', ['email@sample.com'], headers = {'Reply-To': contact_email } ) … -
How can I safely look at the request body in a Django REST framework Authentication?
I've implemented a webhook. The caller provides a shared secret. They concatenate the request URL and body, sign it with the secret, and provide the signature in a header. To validate the signature, I need to repeat the process and compare the signature that I get to the one that the caller got. I'm using Django REST framework. I'm checking the signature in a custom Authenticator. The framework calls the Authenticator's authenticate method with the request as a parameter. I can get the request body from request.stream.read(). However, that consumes the stream, which prevents the framework from parsing it for me: when the framework calls the view the request has no data attribute as it normally would. request.stream doesn't allow me to seek(0). The request doesn't allow me to replace the stream with a rewound one such as a StringIO. My current workaround is to store the body in request.auth and parse it myself in the view, which works but is ugly. Is there a way to access the request body safely in an Authenticator? -
Django native query v "homemade" sql query to json
The following code works nicely: def jsonLiveLeaderboard(request): data = StraightredFixture.objects.filter(fixturematchday=12) json_data = serializers.serialize('json', data) return HttpResponse(json_data, content_type='application/json') However, if I try to do the same with a homemade query like so: def jsonLiveLeaderboard(request): cursor = connection.cursor() cursor.execute( """ select username as User, floor((count(Goals)/2)-(if(sum(Loss)>0,1,0))) as Round, sum(Win) as Wins, sum(Goals) as Goals, sum(Loss) as Losses from (select u.username as username, s.campaignno as campaign, if(f.hometeamscore>f.awayteamscore,1,0) as Win, if(f.hometeamscore<f.awayteamscore,1,0) as Loss, f.hometeamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.hometeamid and s.user_id = u.id union all select u.username as username, s.campaignno as campaign, if(f.awayteamscore>f.hometeamscore,1,0) as Win, if(f.awayteamscore<f.hometeamscore,1,0) as Loss, f.awayteamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.awayteamid and s.user_id = u.id) t group by username, campaign having Losses = 0 order by Round DESC, Wins DESC, Goals DESC """) pointsCurrentSeasonLive = cursor.fetchmany(size=8) json_data = serializers.serialize('json', pointsCurrentSeasonLive) return HttpResponse(json_data, content_type='application/json') I get the following error: AttributeError at /jsonLiveLeaderboard/ 'tuple' object has no attribute '_meta' Is there an easy way to convert a "homemade" query to json in much the same way you can with a native Django query? Many thanks in advance, Alan. -
Django 1.10: Setting admin.site.site_header and using default admin login view
I'm trying to: Use the default admin view (auth.views.login) as my login view Set the admin.site.site_header within ulrs.py so that it appears on the both the login and admin pages First, doing this does update the site_header on the admin page... # urls.py admin.site.site_header = "my header name" urlpatterns = [ url(r'^admin/?', admin.site.urls), url(r'^', include('django.contrib.auth.urls')), ... ] From here it would appear I should be able to either do this: # registration/login.html {% extends "admin/login.html" %} Or this (copy/paste from django/admin/templates/login.html): # registration/login.html {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/login.css" %}" /> {{ form.media }} {% endblock %} ... Neither employ the header with "my header name" like the admin view does. Thanks. -
Django. Saving session data for unauthenticated (annonymous) user
Django isn't saving session data from an anonymous (unauthenticated) user. Should this not work? Unauthenticated user goes to URL. Server-side a session variable is set. User clicks on link and another page loads. Server-side it checks for existence of session variable. I expect the previous session variable to be available, but it's not. If the user is authenticated then it works OK. if is_starting_url(): # user does get here the first time. request.session["my_param"] = "1" elif "my_param" in request.session: # user not getting here -
Django Objects of Objects
So, I am trying to pull data into a form. Right now I have a Class set up like this: class Player(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) #some other variables that do stuff and are just static types. I am trying to create a form that enables the updating of data in the "user" variable of my Player class but I can't figure out how to even get to that data. Any help would be greatly appreciated. -
Django server-sent events in 2016
I'm trying to set up a multi user edit session, using server-sent events to warn the user that someone else is also editing that object (like in google docs) class Edit_Session(models.Model): #uuid is a global unique field for all models object_uuid = models.UUIDField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) So all I need is to send a message to the client if there is someone else editing the same uuid as him. I've read about websockets, tornado, twisted and all that, but is there a simpler way to achieve this in Django that doesn't involve having to learn another library and figure out how to integrate them with Django? -
django-pyodbc bulk_create is broken
When calling bulk_create() using django-pyodbc backend, an insert statement is run for each object in the batch. The behavior should be to run a single insert statement per batch. Is this a bug, or is there a way to alter this behavior? Versions: django==1.7 pyodbc==3.0.10 django-pyodbc==1.0.1 FreeTDS v1.00.21 unixODBC v2.3.4 -
Setattr for queryset from input fields
Bump into with problem cant resolve. May be I choose whole wrong way, or that simplier that I think )) So, my view: def paid_engineer(request): repairs = Kvant.objects.filter(cost_repair__gt=0, is_paid=False, engineer_id=1, kind_repair__paid_engineer__gt=0) if request.method == "POST": if request.POST.get('save_button') is not None: inputs = request.POST.getlist('paid_engineer') try: inputs = [Decimal(i) for i in inputs] except: ValueError for repair in repairs: for input in inputs: setattr(repair.kind_repair, 'paid_engineer',input) repair.kind_repair.save() return HttpResponse('ok') return render(request, 'paid.html', {'repairs': repairs}) I need Setattr for queryset from input fields, but that wrong, and I dont have any ideas. HTML: <form action='{% url "paid_engineer"%}' method="post" enctype="multipart/form-data" class="close-form" name="myform" role="form"> {% csrf_token%} {% for repair in repairs %} <tr > <td>{{repair.pk}}</td> <td>{{repair.date_now|date:"d.m.Y H:i"}}</td> <td>{{repair.brand}}</td> <td>{{repair.model_item}}</td> <td>{{repair.cost_repair}}</td> <td>{{repair.engineer}}</td> <td>{{repair.kind_repair.name}}</td> <td>{{repair.kind_repair.paid_customer}}</td> <td><label ><input class="form-control" type="text" value="{{repair.kind_repair.paid_engineer}}" name="paid_engineer" id="paid_engineer" /></label></td> </tr> {% endfor %} Please, help! -
How to enable a user to view the django admin home page if nothing but a custom view permission in given to the user?
By adding the following code in one of my models, I was able to add a view permission to the model. class Meta: default_permissions = ('add', 'change', 'delete', 'view') I have created a user in django-admin and given only view permission. I want that the user should be able to only view the values of this particular model. But after logging in with the user I am getting an error that the user dont have the permission to edit anything.(refer screenshot). Is there any way that I can allow the user to view a particular model only by giving the VIEW permission only? Any help would be greatly appreciated. Thanks in advance. -
Django Model Not Updating
I'm trying to count the amount of times a user visits a page: models.py: class Request(models.Model): user = models.ForeignKey(User) view = models.CharField(max_length = 250) visits = models.PositiveIntegerField() views.py def daygaps(request,*a, **kw): request_counter = Request.objects.filter( user__username = request.user.username, view = 'daygaps') if request_counter: request_counter[0].visits += 1 request_counter.update() else: Request.objects.create( user = request.user, visits = 1, view = 'daygaps') When a new user visits the page for the first time, 'visits' gets set to = 1. Each subsequent visit should iterate the count. The "else" block works fine, however "visits" stays at 1 and does not change with each new request a user makes. I've tried the ".save()" method, but that throws an error because "request_counter" is a queryset. -
Django alter model data before rendering ModelForm
I'm trying to generate an object that allows values to be stored in a standard unit, but displayed in different units based on the settings for the project. Below is an example where I need to be able to store the temperature of a room. I want the database value to be in Kelvin for ease of calulations, but want the users to be able to view/enter in F or C as the project requires. The model can take the values from a form and convert them to Kelvin on save. I know this can be done in the form, but I have it here for other data entry methods. A striped down version of the model is as follows: class Room(models.Model): name = models.CharField(max_length=255) temperature = models.FloatField(default=293.15) def save(self, *args, **kwargs): self.temperature = convert.temperature(self.temperature, from_unit=self.plant.temperature_scale) super(Room, self).save(*args, **kwargs) I created a ModelForm to use in CreateView and UpdateView. I needed the ModelForm to limit the queryset for other fields (which works fine). Here I was able to convert the temperature field to the desired units for a new object in CreateView, but I can not seem to find the way to pull this off for an existing record class … -
Django : Extends User model - Application Management
I want to create a projet for online courses, with professors and students. A professor can : Login, logout... Complete his informations (profil page) Accept a course requested by a student A student can : Login, logout... Complete his informations Request a course to a professor It's a good way to doing that like this : Create a first app named 'professors' with professor model (extends User) and views for : complete profil, login, logout A second app named 'students' with students model and views for : complete profile, login, logout A third app named 'courses', with course model, views for professor (accept a course) and views for student (request a course) i want to doing that because in my project, I risk to have big differences between professors and students possibilities... Thank you -
django-admin unable to create project
I am trying to create a project in django using django-admin startproject myproj command. However, I keep seeing this error even though my directory has nothing in it. I did have myproj earlier which I simply removed by delete the dir. Error: CommandError: 'myproj' conflicts with the name of an existing Python module a nd cannot be used as a project name. Please try another name. -
How to call a specific url froom Django Views?
I want to make a call to specific url pattern from Django Views. The call should be inside first IF conditional and outside the inner if. Is the any function which provides redirection? Or something like redirect(map_vertical_crawl)? The code portion for Django Views: def add_vertical(request): if request.method == 'POST': form = VerticalForm(request.POST) if form.is_valid(): form.save() #I WANT TO CALL URL EXACTLY AT THIS POINT, INSIDE OUTER IF. verticals = Verticals.objects.all() return render(request, 'cfman/add_vertical.html', {'form': VerticalForm(), 'verticals': verticals} ) Django URLS: from django.conf.urls import url from . import views, apps urlpatterns = [ #Generates Login Screen url(r'^$', views.LoginView.as_view(), name="login"), #Directs to manager view level 1 url(r'^manager/$', views.verticals_view, name="manager"), #Directs to manager view level 2 url(r'^manager/(?P<verticalid>\d+)/$', views.source_list, name='source_list'), #Add Vertical url(r'^verticals/add_vertical/$', views.add_vertical, name="add_vertical"), #Add Source url(r'^sources/add_source/$', views.add_source, name="add_source"), #Add Crawl Type url(r'^crawls/add_crawl/$', views.add_crawl, name="add_crawl"), #Map verticals and crawl types url(r'^vertical_crawl/$', views.map_vertical_crawl, name="map_vertical_crawl"), ] I want to call the last url pattern , 'map_vertical_crawl' from views. -
Angular2 and Django REST Framework: 500 Internal Server Error for URL: null
Aahhh... Help me out. I'd spent hours on this, without success. I'm trying to consume Django REST framework api. DJANGO: added 'corsheaders' to INSTALLED APPS added 'corsheaders.middleware.CorsMiddleware' to MIDDLEWARE, and some more set CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = [*] able to access api at http://localhost:8000/rest.samples/ from browser Angular2 created an Injectable: getEvents() { return this.http.get('http://localhost:8000/rest.samples') .toPromise().then(rp => rp.json()); } called this service from ngOnInit() method of component implementing OnInit Error: EXCEPTION: Uncaught (in promise): Response with status: 500 Internal Server Error for URL: null Unhandled Promise rejection: Response {_body: Object, status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…} Response _body : Object error : "unable to parse url 'http://localhost:8000/rest.samples'; original error: Cannot read property 'split' of undefined" __proto__ : Object headers : Headers ok : false status : 500 statusText : "Internal Server Error" type : null url : null -
Django - extend user profile error user has no attribute userprofile
Im following this link here https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone I didnt need the user section only the profile. the error im currently getting is 'User' object has no attribute 'UserProfile' line 45: profile_form = ProfileForm(instance=request.user.UserProfile) Which i understand is because the user model does not have a UserProfile. Im not sure how to get the UserProfile into the request so the form will work? model from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings # Create your models here. class UserProfile(models.Model): mpls_m_subscriptions = models.CharField(max_length=50,verbose_name="MPLS Maintenance Subscription",choices=settings.SUBSCRIPTION_TYPE,blank=True,null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.UserProfile.save() forms.py from django import forms from home.models import UserProfile class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('mpls_m_subscriptions',) views.py from django.shortcuts import get_object_or_404, render, render_to_response from django.contrib.auth.decorators import login_required from django.db import transaction from django.http import HttpResponse from home.forms import ProfileForm @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.UserProfile) if profile_form.is_valid(): profile_form.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('settings:profile') else: messages.error(request, _('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.UserProfile) return render(request, 'home/profile.html', { 'profile_form': … -
How to update manytomany field in ModelForm from comma separated CharField for use in CBV and ModelAdmin
Using django 1.10 and py3.5, I was able to create new models with this in the admin and elsewere but whenever I try to update the tags part of the model, I get error "IntegrityError at /admin/blog/post/6/change/ UNIQUE constraint failed: webcore_tag.slug" Below is a model form with a custom form_field The form_field is uses a CharField to collect data for a manytomanyfield on the modelform. The strings entered into the charfield are in comma-separated values. The init constuctor gets the values on the manytomanyfield on the model, convert this to comma-separated strings and populates the custom field with this. The clean_tags validates the data entered and then [if valid] creates the tags, appends it to a list after which it returns the list. I use this code with CBVs to create and update the Post model which has this structure Post model: title - Charfield slug - slugfield - unique - default="sample-title" tags - manytomanyfield - Tag Tag model: title - Charfield slug - slugfield - unique - default="sample-title" class PostForm(forms.ModelForm): tags = forms.CharField(max_length='80', help_text = "Enter a maximum of 5 tags separated by ','") class Meta: model = Post fields = ('title', 'tagline', 'category', 'content') def __init__(self, *args, **kwargs): … -
How to pass multiple app's models in one views? [django]
Hei there, I'm having difficulties passing two app models in one views. I have 2 apps : Post Author What I expect is, I want to display Author's avatar in the Post views, so I can include it in posts loop. Author models.py : class Author(models.Model): avatar = models.ImageField(upload_to='images/%Y/%m/%d', verbose_name=u'Author Avatar', validators=[validate_image], blank=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) ... Post views.py : from app_author.models import Author class PostList(ListView): model = Post template_name = 'app_blog/blog_homepage.html' context_object_name = 'post_list' paginate_by = 9 def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data(**kwargs) context['post_hot'] = Post.objects.filter(misc_hot_post = True).order_by('-misc_created')[:1] context['post_list'] = Post.objects.filter(misc_published = True).order_by('-misc_created') context['author'] = Author.objects.all() # This is where I expect the magic is return context When I called something like this in templates, it doesn't work. The {{ author.avatar }} not showing : {% for post in post_list %} <ul> <li>{{ post.title }}</li> # This is works just fine <li>{{ author.avatar }}</li> # This does not work at all <ul> {% endfor %} My Posts app urls.py : from . import views from django.conf import settings from app_blog.views import PostList, PostDetailView from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.PostList.as_view(), name='post-list'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
Django expiring "password reset" model
Let's say my website will have a "reset password" button for when the user forgets his password, it will generate a link with a hash based on url_token field from Password_Reset_Token and email it to the user. If the user access the url, the view can then reset his password and delete the Password_Reset_Token object. But what if it expires and the link isn't accessed? Is there a way to add a daily task to clean expired objects? Or is there a more clever way to do this? Worth nothing that my application is entirely AJAX based and has no url redirecting class Password_Reset_Token(models.Model): url_token = models.AutoField(primary_key = True) created_date = models.DateTimeField(auto_now_add=True) user = models.OneToOneField(User, on_delete=models.CASCADE) expiringdays = models.IntegerField(default = 12)