Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I customize a column based on its value?
Using django-tables2 is very easy from your model to get a table. In my case I need one of my table columns to be formated based on its value. In my current html table it would look like below: {% if record.status|stringformat:"s" == "New" %} <td class="bg-success></td> If the value is New the cell background should be green. From what I could find there are maybe 3 ways to do something like this: 1.Create a class and a css rule with the appropriate background color and add it to the column: class MyTable(tables.Table): status = tables.Column(attrs={"class": "{{ record.value }}"}) .New { background-color: green } I have not found the right way to pass the column value as a class. 2.You can specify how to render a column: class MyTable(tables.Table): status = tables.Column() def render_status(self, value): if value.name == "New": change class accordingly The change class accordingly part eludes me. Also you can create a custom column: class StatusColumn(tables.Column): def render(self, value): change class accordingly 3.Use a TemplateColumn and pass html: class MyTable(tables.Table): status = tables.TemplateColumn(""" {% if record.status|stringformat:"s" == "New" %} <td class="bg-success"></th> {% else %} <td class="bg-danger"></th> {% endif %} """) This way a new column is created formated … -
Django: Combining forms & models to generate form
I have an issue with my Django forms and combining it with data from my database. I need to get data about tickets to generate the form via {% for ticket in tickets %} Once the user chose the ticket(s) and quantity, the form will check this request. I wanted to use Form.is_valid() and cleaned_data, however, I couldn't manage to combine this with step 1. Do you guys have any tips or input how I can make my code more "safe"? Currently, I am skipping all the provided security Django provides with cleaned_data and is_valid(). The reason why is that I don't know how to do it. views.py from django.shortcuts import render from .models import Ticket from tickets.models import Order, Entry # Create your views here. def choose_ticket_and_quantity(request): tickets = Ticket.objects.all() if request.POST: o = Order.objects.create() request.session['order_id'] = o.order_id ticket_id = request.POST.getlist('ticket_id') ticket_quantity = request.POST.getlist('ticket_quantity') for x in range(len(ticket_id)): if int(ticket_quantity[x]) > 0: e = Entry( order=Order.objects.get(order_id = o.order_id), ticket=Ticket.objects.get(id = ticket_id[x]), quantity=ticket_quantity[x] ).save() return render(request, "tickets/choose_ticket_and_quantity.html", {"tickets": tickets}) models.py class Ticket(models.Model): description = models.TextField() name = models.CharField(max_length=120) price_gross = models.DecimalField(max_digits=19, decimal_places=2) quantity = models.IntegerField() choose_ticket_and_quantity.html <form action="" method="post"> {% csrf_token %} {% for ticket in tickets %} <input type="hidden" … -
Where to clear unused fields: in model or in form?
Where should I clear unused data fields (for example set organization_name to empty string if the Contract model is not related to an organization but is a personal contract)? Should I do it in model or in form/modelform? I want to clear unused data fields, among other to ease comparison of equality of two model instances (so that erased field would be always compare equal). Which method(s) should I override to do clearing unused data in it? Should I override Model.save() method? -
Django, passing data through a view context, preferred storage method
I'm trying to pass some data through a django context and am finding it kind of cumbersome. I'm very new to Python and a bit unfamiliar with storing data, I have a few suggestions here shown in the code: 1. A form to pass data: def formview(request): if request.method == 'POST': form=LogonForm(request.POST) if form.is_valid(): request.session['firstname']=form.cleaned_data['entrykey'] request.session['lastname']=form.cleaned_data['firstfield'] request.session['age']=form.cleaned_data['secondfield'] request.session['location']=form.cleaned_data['thirdfield'] return HttpResponseRedirect('thanks') else: form=LogonForm() return render(request, 'logon/form.html', {'form': form}) A view which reacts to the submitted data, but not from database: def thanksforform(request): try: #Using class class thanksclass(): firstname=request.session['firstname'] lastname=request.session['lastname'] age=request.session['age'] location=request.session['location'] under18='Come back in %s years' % str(18-age) over18='Step right up!' #Using array data=np.empty(6, dtype=object) data[0]=request.session['firstname'] #etc. etc. ect. #using list listdata=[request.session['firstname']] #etc etc etc except KeyError: return HttpResponseRedirect('/logon/') request.session.flush() return render(request, 'logon/thanks.html', {'thanksclass': thanksclass}) Which type of object is preferred in Django for this kind of purpose, is there a better way to pass data through the view context? PS. Please disregard the source being session data, It's just an example as I was messing around, I'm aware that you can call session data directly from the template aswell. -
How do i implement pdf or doc file upload and downloads on a django project?
I'm creating a website where i can upload catalogues on a downloads page and users can download them, i can achieve this for a single file by using the following code in the view, but i need a simpler way i can do this on the admin or on a template. def brochure(request): fs = FileSystemStorage() filename = 'kastom_profile.pdf' if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline;filename="kastom_profile.pdf"' return response else: return HttpResponseNotFound('The requested pdf was not found in our server.') -
Realtime output from subprocess in Python
I am running a Django webserver, and am trying to print the output of a subprocess in real-time to the log. If I commend out the readline line and uncomment the yowzer line, I get the desired stream of logged output, but as soon as I try to run this as-is I get no output. What am I doing wrong? All the results I can find seem to suggest that this would work as-is. sp = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) while sp.poll() is None: logging.critical(sp.stdout.readline()) #logging.critical('yowzer') time.sleep(10) Thank you! -
Best way to modify Django application without affecting production database?
I have a Django application that is successfully being hosted on a remote server using Nginx. The production DB is PostgreSQL. I have a development server where I'd like to change the code for the Django application. When I use python manage.py runserver for testing, I'd ideally prefer to avoid touching the production DB at all. This is my first time crossing this bridge. Can someone shed some light on the best practice for 'stubbing' the entire database for development? Can you do some if/else statement in settings.py to use SQLite? Or is there a better solution? -
CSRF Failed 403 when authenticated to admin, but same works fine when not authenticated
Thank you guys for all the help you provide. Another newbie type of an issue, I guess, looking for your help. AngularJS using PATCH method raises: "CSRF Failed: CSRF token missing or incorrect." Cookies: Cookie:arp_scroll_position=0; sessionid=ix36xi2u9bijih2x1npswjlranfm7wjy; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM But only when I'm authenticated in another tab into Admin panel. Same request works fine if I'm not logged in. Cookie:arp_scroll_position=0; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM This is very simple JSON push: .factory('MyName', function($resource) { return $resource('/api/resource/:pk/', {'pk': '@pk'}, { 'update': { method: 'PATCH' // this method issues a PUT request }, }); }); With JSON content such as {"pk":3,"gt":"angularjs-auth"} At the same time, another "html" with separate AngularJS app defined works fine for both situations when authenticated and when not authenticated, but this time I'm using dropzone which probably does workaround the problem transparently for me. .factory('UploadFile', function($resource) { return $resource('/api/files/:pk', {'pk': '@pk'}, { 'save': { method: 'POST', transformRequest: transformImageRequest, headers: {'Content-Type':undefined} }, }); }); Not Authenticade POST (not PATCH, but probably this doesn't make a difference): Cookie:arp_scroll_position=0; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM What I'm seeing here is that content is multipart/form-data which itself includes also CSRF (is this the trick fixing the issue?) ------WebKitFormBoundaryXUBwTTaSIiKwTvyx Content-Disposition: form-data; name="csrfmiddlewaretoken" And authenticated: Cookie:sessionid=kaw00iaxwpq3puxcc94dy9v8yxf7rfyh; csrftoken=49KSaqsZykxuYRvJsEhpKlCyqP1ZnVQAubO4bPKs0u2qEcm0hpVvutMoIdUW9gV6; arp_scroll_position=0 ------WebKitFormBoundaryelub0ZsHFENNbUmp Content-Disposition: form-data; name="csrfmiddlewaretoken" dqeieK1GdnYD9QTVRbt4ibQ6q0u8o8mkDsiuf9j9FxtzPbKcGW7a2j0WIon5atrQ Looking for … -
How to filter or query using abstract parent class in Django model?
this one is interesting to solve. I am building a module to register address for hospital, medical store and doctors. There is an abstracted model PrimaryAddress and a subclass called MedicalStorePrimaryAddress, and more subclasses will use the same abstracted model. I am using django rest framework to get the listings based on proximity (latitude, longitude and city). Now how could I filter it all using parent class, i.e PrimaryAddress model as I want to filter all the entities, i.e hospital, medical store and doctor nearby. I have looked into django-polymorphic library but it doesnt help with geodjango and abstract class. Any help suggestion is appreciated. Thanks Here is the code sample: # MODELS class PrimaryAddress(gismodels.Model): street = gismodels.CharField(max_length=255) city = gismodels.CharField(max_length=60) state = gismodels.CharField(max_length=100, choices=settings.US_STATES, default="CT") landmark = gismodels.TextField() latitude = gismodels.FloatField(null=True, blank=True) longitude = gismodels.FloatField(null=True, blank=True) location = gismodels.PointField(null=True, blank=True) objects = gismodels.GeoManager() def __unicode__(self): return self.street class Meta: verbose_name = "Address" verbose_name_plural = "Addresses" abstract = True def save(self, *args, **kwargs): if self.latitude and self.longitude: self.location = Point(self.longitude, self.latitude) super(PrimaryAddress, self).save(*args, **kwargs) class MedicalStoreAddress(PrimaryAddress): medical_store = gismodels.OneToOneField(MedicalStore, related_name="medical_store_address", on_delete=gismodels.CASCADE, null=True, blank=True) # objects = gismodels.GeoManager() def __unicode__(self): return self.street class Meta: verbose_name = "Medical Store Address" verbose_name_plural = … -
create new object task for the current logged in user
hi i want to create a new task for the current logged in user so i am using this views this is my views @login_required def ajouter_task(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): task = form.save(commit=False) task.user = request.user task.save() return redirect('home') else: form = TaskForm() return render_to_response('ajouter_task.html', {'form': form}) it dosn't work i don't know where the problem is , please help and thank u in advance -
How to display User Permission in Django template
So I am currently setting some user permissions upon creation to Django user's. I would like to display a table of all the users as well as information about them such as username, password permissions etc.. The code to do this look's similar to this. <table id='usersTable'> <tr> <th></th> <th>Status</th> <th>Username</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Last Login</th> <th>Expiry Date</th> <th>Permission</th> </tr> {% for user in userlist %} <tr id='{{ user.id }}' class='user-row urow'> <td> <input type="checkbox" name="check" class='userSelection'> </td> <td> <div class="status"></div> </td> <td>{{user.username}}</td> <td>{{user.first_name}}</td> <td>{{user.last_name}}</td> <td>{{user.email}}</td> <td>{{user.last_login}}</td> <td>{{user.userprofile.date_expiry}}</td> {% load user_perm %} <td> {% if user|check_permission:'2018_map_view' %} I have 2018 access {% endif %} {% if user|check_permission:'2017_map_view' %} I have 2017 access {% endif %} </td> </tr> {% endfor %} </table> I have on the bottom the attempted code to display each user permission in the table however it does not seem to be working. I have my templatetags code that looks like this from django.template import Library register = Library() @register.filter() def check_permission(user, permission): permission = user.has_perm(permission) print(permission) return user.has_perm(permission) I believe the problem lies within my user in userList and it is having problem looping through all user's but I am unsure how to fix this. … -
Django all-auth - Connect session data to user after login
I'm using django-allauth and django-rest-auth for login and signup. Users can interact with the server as visitors and I'd like to keep those interaction after they signup/login. I'm able to do that after signup using all-auth signal: from allauth.account.signals import user_signed_up However it doesn't work for login, when I'm using the signal from allauth.account.signals import user_logged_in With all-auth only, the signal is emitted but django generates new session before reaching the signal (so I can get the data). With Rest-auth the signal is not emitted at all. Is there a way to solve that? Maybe by overriding django login process? Thanks -
Optimum architecture for webapp
I am a complete novice in programming. So please don't make fun of me. I would like to create a web app using Django. The idea is to let the user generate points on a map through latitude & longitude data entered in a form in the application. The architecture I had in mind is the following : Django form => Django model => MySQL => PHP => XML => Google Map But intuitively I feel this is not the most efficient architecture for my application. Moreover I ain't sure how PHP would dynamically generate an XML every time a user feeds data to the MySQL database. Could someone please guide me on what could be the optimum architecture for my application ? -
adding two filters at django admin and having two query results (for comparison)
This layout is what I want to achieve. e.g I want to compare query results in two date range 1/1 ~ 2/1 and 5/1 ~ 6/1. How can I do this? I am using Django 1.11.4. -
How to combine Django with Flask for streaming files?
I spent whole day researching and trying to figure out the right solution. The fact that Django does not really support file streaming (video streaming, audio streaming) is really bothering me and I don't want to just scrap all of my knowledge and learn other frameworks that support it. I just wonder how big services like Instagram or Pinterest that run on Django made it work. I know that Node.js could handle it really well with its async nature, but I want to use Python. I got an idea that could work. I want Django to handle the whole database, and Flask to handle the file streaming. I know it sounds crazy, but I really want to get it running. Is there a better solution to my problem? And if not, do you know any resources that could help me? -
Scraping view function remembers its previous iterations
I have the following view function used to scrape data: def results(request): if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form_city = form.cleaned_data['city'].title() form_country = form.cleaned_data['country'].title() form_arrival_date = form.cleaned_data['arrival_date'] form_departure_date = form.cleaned_data['departure_date'] form_pages_to_scrape = form.cleaned_data['pages_to_scrape'] #launch scraper scraper = AIRBNB_scraper(city=form_city, country=form_country, arrival_date=str(form_arrival_date), departure_date=str(form_departure_date)) scraped_dataframe = scraper.scrape_multiple_pages(last_page_selector_number=form_pages_to_scrape) scraped_dataframe_sorted = scraped_dataframe.sort_values('prices') print(scraped_dataframe_sorted) #convert scraped dataframe into lists prices = scraped_dataframe_sorted['prices'].tolist() listings_links = scraped_dataframe_sorted['listings_links'].tolist() listings_names = scraped_dataframe_sorted['listings_names'].tolist() photo_links = scraped_dataframe_sorted['photo_links'].tolist() dictionary = zip(prices, listings_links, listings_names, photo_links) context = {'dictionary': dictionary} return render(request, 'javascript/results.html', context) On form submit, a post request is sent to this function using AJAX: var frm = $('#login-form'); frm.submit(function () { $.ajax({ type: "POST", url: "/results", data: frm.serialize(), success: function (data) { $("#table").html(data); $('#go_back').remove(); }, error: function(data) { $("#table").html("Something went wrong!"); } }); return false; }); After that the scraped data is displayed as HTML table on the same page the form is on. The problem is the number of scraped items doubles every time the form submit is done. So for example if the number of scraped items on first button click is sixteen, the output will be 16, but on the second run it will be 32, then 64, and so on. It is like the app … -
Error in Django when using matplotlib examples
I am testing several cases of Django and matplotlib such as this question or in french. Each time, it works on my mac, but does not on my server, where I receive the following error: Internal Server Error: /mj/charts/mplimage.png Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/src/jm/majority_judgment/views.py", line 39, in mplimage canvas.print_png(response) File "/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py", line 526, in print_png with cbook.open_file_cm(filename_or_obj, "wb") as fh: File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 624, in open_file_cm fh, opened = to_filehandle(path_or_file, mode, True, encoding) File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 615, in to_filehandle raise ValueError('fname must be a PathLike or file handle') ValueError: fname must be a PathLike or file handle [28/Mar/2018 19:09:11] "GET /mj/charts/mplimage.png HTTP/1.1" 500 82804 I have tried to update matplotlib, django and so on, but it did nothing... -
Django messages repeating itself instead of updating
classinfo = EventType.objects.all() length = EventType.objects.all().count() for i in range(length): messages.success(request, classinfo[i]) So I'm using this to print out a list of all events that are located in EventType. Image This is what it looks like. However, when I add another item to the list using the Class Add feature, it repeats the original list again and then adds the additional event. But if I add an additional another event after this it will add it to the list properly. How can I go about fixing this so it doesn't repeat the initial list when I add an event? How it looks right now when I add an event This is what the HTML looks like: {% for message in messages %} <li> {{ message }} </li> {% endfor %} -
TypeError: hasattr(): attribute name must be string
I tried different ways to trace error but not able trace plz help. i didn't find any reference regarding the error This is my custom user model required to add extra phonenumber field and login through email, so i created custom model and stuck in this error from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class User(AbstractBaseUser): first_name=models.CharField(max_length=20,blank=True) last_name=models.CharField(max_length=20,blank=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) phone_number = models.CharField(max_length=17, blank=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that's built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [phone_number] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.first_name+self.last_name def get_short_name(self): # The user is identified by their email address return self.email def get_phone_number(self): return self.phone_number def __str__(self): # __unicode__ on Python 2 return self.email class UserManager(BaseUserManager): def create_user(self, email,phone_number,first_name,last_name,password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') if not phone_number: raise ValueError('phone number required') user = self.model( def create_superuser(self, email, password): """ Creates and saves … -
Issue with loading template in django framework
I am new to Django framework.I was trying to integrate Braintree payment gateway in my Django project.In view.py i created a class for creating a view.Then created a url in urls.py. In View.py class CheckoutView(generic.FormView): form_class = forms.CheckoutForm template_name = 'demographics/checkout.html' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.user = request.user if settings.BRAINTREE_PRODUCTION: braintree_env = braintree.Environment.Production else: braintree_env = braintree.Environment.Sandbox # Configure Braintree braintree.Configuration.configure( braintree_env, merchant_id=settings.BRAINTREE_MERCHANT_ID, public_key=settings.BRAINTREE_PUBLIC_KEY, private_key=settings.BRAINTREE_PRIVATE_KEY, ) self.braintree_client_token = braintree.ClientToken.generate({}) return super(CheckoutView, self).dispatch(request, *args, **kwargs) In forms.py class CheckoutForm(forms.Form): payment_method_nonce = forms.CharField( max_length=100, widget=forms.widgets.HiddenInput, required=False, ) def clean(self): self.cleaned_data = super(CheckoutForm, self).clean() # Braintree nonce is missing if not self.cleaned_data.get('payment_method_nonce'): raise forms.ValidationError('We couldnt verify your payment. Please try again.') return self.cleaned_data in url.py url(r'^checkout$',views.CheckoutView.as_view(),name='checkout'), And i tried to call this class in my template <div class="module"> <form action="{% url "checkout" %}" method="POST"> {% csrf_token %} {{ form.errors }} {{ form.as_p }} <input type="submit" name="submit" value="Checkout2" /> But the template is not loading..How can i load my template.. -
django/ajax CSRF token missing
I have the following ajax function which is giving me a cross site forgery request token error once I get past the minimumlengthinput of 3 with the select2 control. Knowing this I attempted to add { csrfmiddlewaretoken: '{{ csrf_token }}' }, to my data:. After adding the csrfmiddlewaretoken I'm still getting the CSRF token missing or incorrect error. I believe it has something to do with the way I nested the searchFilter and searchPage function. What is the proper way to do this? $(document).ready(function () { $('.selectuserlist').select2({ minimumInputLength: 3, allowClear: true, placeholder: { id: -1, text: 'Enter the Student id.', }, ajax: { type: 'POST', url: '', contentType: 'application/json; charset=utf-8', async: false, dataType: 'json', data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, function(params) { return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}"; }, processResults: function (res, params) { var jsonData = JSON.parse(res.d); params.page = params.page || 1; var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i; for (i = 0; i < jsonData.length; i++) { data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value }); } return { results: data.results, pagination: { more: data.more, }, }; }, }, }); }); -
ImportError: No module named 'decouple' while deploying on Heroku
I was trying to deploy my django project on heroku from heroku cli. So I created an app and then I ran git push heroku master from the project directory. Then I got the errors: > remote: -----> $ python manage.py collectstatic --noinput remote: > Traceback (most recent call last): remote: File "manage.py", > line 15, in <module> remote: > execute_from_command_line(sys.argv) remote: File > "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", > line 371, in execute_from_command_line remote: > utility.execute() remote: File > "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", > line 317, in execute remote: settings.INSTALLED_APPS > remote: File > "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", > line 56, in __getattr__ remote: self._setup(name) remote: > File > "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", > line 43, in _setup remote: self._wrapped = > Settings(settings_module) remote: File > "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", > line 106, in __init__ remote: mod = > importlib.import_module(self.SETTINGS_MODULE) remote: File > "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, > in import_module remote: return > _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 986, in _gcd_import remote: > File "<frozen importlib._bootstrap>", line 969, in _find_and_load > remote: File "<frozen importlib._bootstrap>", line 958, in > _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 673, in _load_unlocked remote: > File "<frozen importlib._bootstrap_external>", line 665, in > exec_module remote: File "<frozen importlib._bootstrap>", > line 222, in _call_with_frames_removed remote: File > "/tmp/build_93c58c906371cd0110470b6bb3ccecc1/funderpreneur/settings.py", > line … -
Custom `password_reset_confirm.html` template won't redirect to `password_reset_complete` view
I made a custom password_reset_confirm.html template. But when a user enters a new password and hits submit, the browser does not redirect to the admin view password_reset_complete. Here's the form I made in the custom password_reset_confirm.html template: <div ng-app="app" ng-controller="Ctrl"> <form id="reset-pw-confirm-form" name="newPWForm" method="post" action=""> {% csrf_token %} <input id="id_new_password1" type="[[[ newPW.showPW ? 'text' : 'password' ]]]" name="new_password1" ng-model="newPW.pw" ng-minlength="8" ng-maxlength="32" required> <button class="btn btn-primary" type="submit" ng-disabled="!newPW.pw">Submit</button> <input id="id_new_password2" type="hidden" value="[[[ newPW ]]]" name="new_password2" ng-model="newPW" ng-minlength="8" ng-maxlength="32" required> </form> </div> And the JS: var app= angular.module("app",[]); app.config(function($interpolateProvider, $httpProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); $httpProvider.defaults.xsrfCookieName= "csrftoken"; $httpProvider.defaults.xsrfHeaderName= "X-CSRFToken"; }); app.controller("Ctrl", function($scope, $http){}); When I fill out the password and hit submit, the browser sends a POST request to the same URL it landed on, but the page seems to just refresh with nothing changed. The user's password remains unchanged. It seems Django's auth/views.py did not execute properly. In that view, there's this code: if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) When I have the view print post_reset_redirect, it prints None. Could this be the issue? How can I make my custom template compatible with Django's password_reset_confirm view? -
Django - Search last object created for every id and keep sum off other field
I'm doing a query where I want to get the list of all Games, related to an specific Team, but I want the field "date_created", to save only the last date. So here is my query: "games": [ { "id": 3, "first_name": "Odille", "last_name": "Adamovitz", "date_created": "2017-08-24T00:00:00", "points": "10", }, { "id": 3, "first_name": "Odille", "last_name": "Adamovitz", "date_created": "2017-09-18T00:00:00", "points": "10", }, { "donation__sponsor": 3, "first_name": "Odille", "last_name": "Adamovitz", "date_created": "2016-06-20T00:00:00", "points": "10", }, { "id": 5, "first_name": "Bail", "last_name": "Brownbill", "date_created": "2017-11-10T00:00:00", "points": "10", }, { "id": 5, "first_name": "Bail", "last_name": "Brownbill", "date_created": "2018-01-31T00:00:00", "points": "10", } ] And my desire query is: "games": [ { "id": 3, "first_name": "Odille", "last_name": "Adamovitz", "date_created": "2017-09-18T00:00:00", "points": "10", }, { "id": 5, "first_name": "Bail", "last_name": "Brownbill", "date_created": "2018-01-31T00:00:00", "points": "10", } ] My final objective with this is to have a query with another field that sums an attribute inside Something like this: "games": [ { "id": 3, "first_name": "Odille", "last_name": "Adamovitz", "date_created": "2017-08-24T00:00:00", "points": "30", }, { "id": 5, "first_name": "Bail", "last_name": "Brownbill", "date_created": "2018-01-31T00:00:00", "points": "20", } ] Here is my closest idea: #I get the sum of points with the name, but missing last date_created qs = Game.filter(id=1).values('first_name', … -
Django cannot find my templates
I have already tried many ways to "make" Django find my templates, but I cannot figure out what is wrong. How does Django find templates? It is always raising the TemplateDoesNotExist exception. It is managing to get the "base.html" template which is inside the "templates" folder, but it is not managing to get the "list.html" and "detail.html" templates that are inside a "post" folder, which is also inside the "templates" folder. These are the views: def post_list(request): posts = Post.published.all(); # '.published' is a manager. # try: return render(request, "list.html", {"posts": posts}); # except: # return render(request, "base.html", {"posts": posts}); def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status="published", publish_year=year, publish_month=month, publish_day=day); return render(request, "detail.html", {"post": post}); Why doesn't it work if I put "templates/post/list.html" in the second argument of the render function? (That's also another way that I tried to make things work).