Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can two Django Objects have multiple intermediate models between them?
In Django, is it possible to create multiple many to many relationships via multiple intermediate models between two models? For example, I have an object user and an object stock_position, and every time the user makes a trade, I want to make an intermediate model (transaction) that has user and stock_position as foreign keys. -
URL is not jumping to right number in Django
models.py from django.db import models class Profile(models.Model): name=models.CharField(max_length=20 ) age=models.IntegerField() def __str__(self): return self.name class Like(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) like=models.IntegerField(default=0) def __str__(self): return self.choice_text views.py from django.shortcuts import render from .models import Profile, Like # Create your views here. def index(request): all_name=Profile.objects.all() context={'all_name':all_name} return render(request, 'database/index.html',context) def detail(request, profile_id): all_likes=Like.objects.get(pk=profile_id) return render(request, 'database/detail.html', {'all_likes':all_likes}) index.html <h1>hey</h1> {% for name in all_name %} <li><a href="{% url 'database:detail' user.id %}">{{ name.name }}</a></li> {% endfor %} detail.html {{all_likes}} urls.py from django.urls import path from . import views app_name='database' urlpatterns = [ path('index/', views.index, name='index'), path('<int:profile_id>/', views.detail, name='detail'), ] now http://127.0.0.1:8000/database/index/ produces two list item, but when I click on both, i am redirecting to http://127.0.0.1:8000/database/1/ . http://127.0.0.1:8000/database/2/ is working manually but not when I click. Couldn't figure out the error in the code. -
Using related_name to return queryset not working in django?
Here I am working with two models.Both models have ForeignKey relation to the User model. Here I wanted to query staffs, is_reviewed_by and sent_by and I tried like this. When I do filter it returns the queryset but when I used related_name to query then it throws AttributeError. How can i do this? `Exception Value: 'Leave' object has no attribute 'reviewed_by models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateField() end_day = models.DateField() is_reviewed_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='reviewed_by',blank=True,null=True) class LeaveReply(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='leave_status') leave = models.ForeignKey(Leave,on_delete=models.CASCADE,related_name='leave_status') sub = models.CharField(max_length=300,blank=True,null=True) msg = models.TextField(blank=True,null=True) sent_on = models.DateTimeField(auto_now_add=True) sent_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='sent_by') views.py def leave_detail(request, pk): leave = get_object_or_404(Leave, pk=pk) reviewers = leave.reviewed_by.all() # not working staffs = leave.staff_leave.all() # does not works staffs = Leave.objects.filter(staff=leave.staff) # this works reviewers = Leave.objects.filter(is_reviewed_by=leave.is_reviewed_by) # works reply_sender = LeaveReply.objects.filter(sent_by=leave.is_reviewed_by) #works reply_sender = leave.sent_by.all() # doesn't works -
how to make a website share some part of its database to other website?
i have a search website that show products and i'm creating e-commerce website for every customer so i want to give them an option so they can choose which product to be shown in my website search result for example : mysite.com, customer1.com, customer2.com so each customer has it's own database and its own website including item1 in their database customer1 and customer2 choose to show item1 in my search result when i search item1 in mysite.com i can see item1 as result is this possible? and how can i do that?(am i good with django or i should go with php or else ) -
adding country and cities django
i want to add country and cities in forms currently i'm using django-countries for country but i'm gettings this error: django.core.exceptions.FieldError: Unknown field(s) (country) specified for CustomUser forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from bootstrap_datepicker_plus import DatePickerInput from tempus_dominus.widgets import DatePicker from .models import CustomUser from django_countries.fields import CountryField class RegistrationForm(UserCreationForm): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) Mobile_Number = forms.CharField(label='Mobile Number', widget= forms.NumberInput) Artist_Category = forms.ChoiceField(choices=CHOICES) bio = forms.CharField(widget=forms.Textarea,label = 'something about yourself') portfolio = forms.URLField(label = 'enter your portfolio') country = CountryField(blank_label = '(select_country)') # country = forms.co class Meta: model = CustomUser fields = ('email','password','Mobile_Number','Artist_Category','portfolio','country','bio',) .......................... -
Django CMS Plugin not loading CSS
I made a django CMS plugin for my news website, from the "article" model. The plugin is "working" in the way that I see all the raw HTML with the data that I want displayed, but It does not apply CSS to my article and I got no clue why. any idea ? My code : plugin: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from news_cms_integration.models import ArticlePluginModel from django.utils.translation import ugettext as _ @plugin_pool.register_plugin # register the plugin class ArticlePluginPublisher(CMSPluginBase): model = ArticlePluginModel # model where plugin data are saved module = _("Article") name = _("Article Plugin") # name of the plugin in the interface render_template = "news_cms_integration/article_plugin.html" def render(self, context, instance, placeholder): context.update({'instance': instance}) return context my plugin html : {% load sekizai_tags %} {% render_block "css" %} <h1>{{ instance.article.title }}</h1> <section class="container post-details-area"> <div class="container single-article-div"> <hr class="hr-single hr-top"> <h2 id="article-title" class="single-article-titles">{{ article.title }}</h2> <hr class="hr-single"> <img class="single-article-img" src="{{ article.article_image.url }}" alt=""> <!-- *********************************** --> <hr class="hr-single"> <p>Category: {{ article.article_category }}</p> <hr class="hr-single"> <div class="row justify-content-center"> <!-- Post Details Content Area --> <div class="col-12 col-xl-8"> <div class="post-details-content bg-white box-shadow"> <div class="blog-thumb"> </div> <div class="blog-content"> <div class="post-meta"> <a href="#">{{ article.pub_date }}</a> </div> <h3 class="single-article-titles post-title"> {{ article.description … -
How can I direct to different apps with different logins in Django project?
I have different apps for different clients in a Django project. And I have a login page. A client can log in and the login credentials will direct to the respective app. Something like the app is created for a particular client and other clients can't access to that particular app. How can I do that? I am confused in redirecting to the particular app in urls.py in Django main project folder (not in urls.py of each app). -
How to trace permission denied 403 error in Django
I am having trouble tracing down a 403 error since I don't get the debug log. On sign up my users select the type of user that they are using a model.CharField: class User(AbstractUser): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'),) employee_type = models.CharField(max_length=30, choices=EMPLOYEE_CHOICES, default='dealer') During registration I use the users previous selection to assign them to a group: # Register page view def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() emp_type = form.cleaned_data.get('employee_type') group = Group.objects.get(name=emp_type) user.groups.add(group) username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I have a view which is filtered by a PermissionRequiredMixin: # View to create a memo class MemoCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): permission_required = 'memos.can_change_memo' model = Memo fields = ['title', 'content'] All my users which were assigned to the groups which could access this page used to be able to access this page. Nothing should have changed but I seem to only be able to get superusers to be able to access this page. Even when I manually add 100% permissions in the admin panel to a user it … -
How to accept payment in django rest framework based Application?
I am going to start making my first production level API based website. It being my first attempt, I am confused with some of the things: 1> How to accept payments in a rest API based application? 2> As I need to make different UI for accessing the data of my application, does payment now becomes a part of my frontend only? I want to integrate a payments Gateway with my application. I am starting with developing API for my application first. Also suggest, should I use different UI (react/ angular / etc.) or should I use django templates at the starting. -
How to scroll to specific element using the Infinite Scroll With Django?
When I initially load the page, It loads 10 items(1,2,3...10) and after scrolling down I am getting another 10 items(11,12,13,...20). But I need to directly scroll to the 12th element. I am using the Waypoint infinite scrolling(JQuery) and Django pagination. Jquery : $(document).ready(function() { $('html, body').animate({ scrollTop: $("#2").offset().top }, 'slow'); }); // waypoint code: var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], context: document.getElementById('#16'), onBeforePageLoad: function() { $('.loading').show(); }, onAfterPageLoad: function($items) { $('.loading').hide(); } }); While scrolling down the data coming from the Django pagination by triggering the call : http://localhost:8000/polls/?page=2&type=testpoll I need to scroll to an element in the 'page=2' while loading the page initially. How can I do this? -
Django how to display in template a list of distinct value from one column
I try to display a list (in a select) of distinct value of a specific column from a table. The table name is : RankingHasEntreprise and the column name is : risk I did this in my view: risks = RankingHasEntreprise.objects.values_list('risk', flat=True).distinct() risk = "a" # to simplify my code print(risks.count()) # this return 5 return render(request, 'testFiltre.html',{'risk': risk,'risks': risks,}) This is my template: <div class="form-group col-md-2 col-lg-2"> <label for="Risk">Risk</label> <p>{{ risks.count }}</p> <select id="Risk" class="form-control" name="Risk"> {% for risksloop in risks %} {% if risk|add:"0" != risksloop %} <option value="{{ risksloop }}">{{ risksloop}}</option> {% else %} <option selected value="{{ risksloop }}">{{ risksloop }}</option> {% endif %} {% endfor %} </select> </div> And this is the result I get : visual result \n As you can see my select get a value for each tuple of my table "RankingHasEntreprise". This select should only have 5 distinct values a-b-c-d-e. What is disturbing is that when I do a count on my list in my view or template it display me 5. Thanks for reading ! I hope you can solve it =) Cordially -
index.html file for GitHub repository website
I am attempting to publish my website that I have uploaded into a github repository. When I run the website locally (using django) I can see it working perfectly with all of my backgrounds and animations from the css files. This was using the index.html file in the templates folder. When I attempted to run using the github pages, I had to create an index.html file in the main folder so that it can be run from the start. However, this causes my website to include only text files and images, no animations, backgrounds, or colors from my css files. The settings.py has STATIC_URL = '/static/' How can I use the new index.html to call all of my css files? Folder static (folder) css js scss img _init__.py settings.py urls.py Other Folder migrations (folder) templates (folder) index.html views.py admin.py init.py index.py (new for github) -
autocomplete enables for username and password when adding custom fields to django usercreateform
I am using AbstractUser to extend the built in User model. I then Use the UserCreateForm to create add users to the application. When i add my custom fields that I created to the "fields = []" the built in username and password fields in the rendered form starts to autocomplete like its a login, when i remove my custom fields it goes back to normal Link to image with no custom fields rendering as desired https://imgur.com/JFGswFN link to image with custom fields rendering with problem https://imgur.com/rlZI032 may have to copy paste images in web browser first time posting here and could not figure out how to upload an image or get a link to work. I have tried the following and none of it works: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'autocomplete': 'off'}) <form method="POST" autocomplete='off' novalidate> and also tried adding it to the widget section in the Meta class for username and password1 fields. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.text import slugify import string class Department(models.Model): department = models.CharField(max_length=30, unique=True) slug = models.SlugField(unique=True) class Meta: ordering = ['department'] def save(self, *args, **kwargs): self.slug = slugify(self.department) self.department = self.department.title() super(Department, self).save() def __str__(self): … -
Django+Heroku : 500 error when debug=False
This question has been asked before, and I have read all of the solutions that I could find so far. I have a django site hosted on a Heroku free account. It works perfectly when debug is set to true, but when debug is set to false, I receive a 500 server error when trying to access the site on myapp.herokuapp.com . manage.py runserver works perfectly fine I have tried all of the following suggestions, all of which either fail or change the error from 500 to Internal Server Error: commenting out the line STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' creating a custom 500 error page (I don't understand how this would fix the error anyways, but I gave it a shot) Changing allowed hosts to ['*', '.***.com', '.herokuapp.com', 'localhost', '127.0.0.1'] Adding the line COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False) Changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my settings.py I can copy any additional code as needed """ Django settings for personal_portfolio project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import dj_database_url import django_heroku # Build paths inside … -
Django render can't locate a template that actually exists
I have the following view in my Django project: import os from django.shortcuts import render from JumboDjango import settings # Create your views here. def index(request): filename = os.path.join(settings.BASE_DIR, 'frontend/source/public/index.html') return render(request, filename) But, when it is called, it raises the following exception: Internal Server Error: / Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/hugovillalobos/anaconda3/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/views.py", line 8, in index return render(request, filename) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html [26/Sep/2019 02:51:04] "GET / HTTP/1.1" 500 79956 You can see in the following image that /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html actually exists: I don't know if I am missing any Django configuration, or something. -
Server closed the connection unexpectedly sometimes
Project background: Django project, I use gunicorn to run the project, in the project, i use python socket io to process some event Postgresql, config like this: DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': xxx, 'USER': xxx, 'PASSWORD': xxx, 'HOST': 'xxx', 'PORT': '5432', 'CONN_MAX_AGE': 60 * 10, # seconds 'OPTIONS': { 'connect_timeout': 20, }, } the python socket io will keep a thread to process some events. so the thread has its own postgresql database connection. sometimes, I find it will throw database connection problem, like this, I don't know why the database connection isn't be closed normally Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/engineio/server.py", line 520, in _trigger_event return self.handlers[event](*args) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 590, in _handle_eio_message self._handle_event(sid, pkt.namespace, pkt.id, pkt.data) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 526, in _handle_event self._handle_event_internal(self, sid, data, namespace, id) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 529, in _handle_event_internal r = server._trigger_event(data[0], namespace, sid, *data[1:]) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 558, in _trigger_event return self.handlers[namespace][event](*args) File "/usr/src/app/async_worker/controllers/server/event_handler.py", line 61, in on_jira_handle_from_client_retrieve ticket = Ticket.get_ticket_by_id(ticket_id) File "/usr/src/app/review/models/ticket.py", line 144, in get_ticket_by_id return Ticket.objects.filter(id=ticket_id).first() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 564, in first objects = list((self if self.ordered else self.order_by('pk'))[:1]) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line … -
Python crashes while closing and open new Keras(tensorflow) session
I'm making a model to service with Keras & Django. The purpose is initializing models with various hyperparams or load models, which are same architecture but, weights(parameters) and hyperparameters are different. Because weights are valid in each session, 'model_init' or 'load_model' method close and open tf.Session() each time it is called. However, After initializing new model or load other models, Python crashes and Django service shuts down. It seems to be related with session & memory. Below is my code: class keras_model: session = None graph = None model = None def model_init(~): # hyper parameter setting tf.reset_default_graph() self.graph = None if self.session is not None: self.session.close() # del self.session self.session = None self.graph = tf.Graph() with self.graph.as_default(): self.session = tf.Session(graph=self.graph) with self.session.as_default(): # model definition self.model = models.Model(~) self.model.compile(~) def train(): with tf.device(self.device): with self.graph.as_default(): with self.session.as_default(): training_log = self.model.fit(~) return training_log def predict(): ~ def load_model(): tf.reset_default_graph() self.graph = None if self.session is not None: self.session.close() self.session = None self.graph = tf.Graph() with self.graph.as_default(): self.session = tf.Session(graph=self.graph) with self.session.as_default(): # load model architecture self.model = model_from_json(~) # load model weight self.model.load_weights(~) def save_model(): ~ Any idea or suggestion would be appreciated. -
Using Django, how to filter from an object based on FK using a column and get distinct values
My DB query is below: select distinct m.topic from education.sessions s, education.modules m where s.subject_id = 'Biology' and s.module_id = m.id and m.status = 'Active' order by m.topic I am trying the equivalent of the above in QuerySet and I do not seem to get it.First off, I do not know where to include the status='active' check and the "Order By". Session and Module are my 2 tables with Session having a FK on module. Module has 2 columns Subject and Topic and I need the unique topics for the given subject if status = 'Active' In Views.py, I have the below: def load_topics(request): subject = request.GET.get('subject') topics = Session.objects.filter(subject=subject).values_list('module__topic', flat=True).distinct() return render(request, 'evaluation/topic_dropdown_list_options.html', {'topics': topics}) -
In the Django, get multiple Counts of various conditions
I am developing "Admin DashBoard" with Django 2.2 I'd count "Objects" of various conditions from one table and send them to the template. My code is below.. # model class User(models.Model): uid = models.AutoField(primary_key=True) status = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) created_at_unix = models.CharField(max_length=100, blank=True, null=True) country_code = models.IntegerField(blank=True, null=True) recommender_id = models.ForeignKey('self', on_delete=models.SET_NULL ,blank=True, null=True, db_column='recommender_id') is_agreement = models.PositiveIntegerField(blank=True, null=True) delete_yn = models.CharField(max_length=1, default='n') is_sms = models.PositiveIntegerField(blank=True, null=True) is_email = models.PositiveIntegerField(blank=True, null=True) is_push = models.PositiveIntegerField(blank=True, null=True) def index(request): # New User user_lastweek = User.objects.filter(created_at__gte=last_monday, created_at__lte=last_sunday).count() user_thisweek = User.objects.filter(created_at__gte=this_monday, created_at__lte=tomorrow).count() user_variation = user_thisweek - user_lastweek # User total user_total_lastweek = User.objects.filter(created_at__lte=last_sunday).count() user_total_thisweek = User.objects.filter(created_at__lte=tomorrow).count() user_total_variation = user_total_thisweek - user_total_lastweek context = { 'user_lastweek':user_lastweek, ... } return render(request, 'main/index.html', context) I have written only a few of the many conditions. But my code is causing duplicate query hitting every time. The result I need is like.. 1. user_lastweek : 114 2. user_thisweek : 98 3. user_total_lastweek : 1232 4. user_total_thisweek : 1330 How is it efficient to render to a template with only one query or fewer queries? -
django DB linked with AWS S3 on heroku
Currently I'm trying to make a website for a friend, who will have ability to save Models in django admin panel. I have already realased it on Heroku however due to the problem that any changes to the heroku filesystem whilst the dyno is running only last untill that dyno is shut down or restarted and what it means that the data which is created by my friend will be gone. In order to solve this problem I decided to connect it with AWS S3 and save there whole data. I found some answers about uploading media files like photos, but neither of them is about saving the whole model. It's like saving database there. Am I thinking wrong? How can I do this? I have already done things like creating bucket and connecting it with django with secret keys etc. -
Does Django cache a POST request (and it's parameters)?
I have a DRF API that implements views that allow GET and POST calls: @api_view([ 'GET', 'POST', ]) @cache_page(timeout=60 * 10) def my_view(request): # do stuff I noticed that: GET requests get cached as expected. POST requests do NOT get cached at all. Questions: Is this intended or am I doing something wrong? If this is working as intended...how can I get Django to cache POST requests as well? -
Unique URL generator for Object Items or hiding ID from URL parameter
I am working on an application built using Python3 and Django that generates PDFs (via HTML) using filled fields from a data model. I've created a URL function that takes a value of document ID and type, and then generates a PDF of that document. What I want to do is to email clients a link that contains that URL function with a specific document ID, however, the problem that I'm facing is that the generated URL has the document ID in the URL parameter, and this is terrible for security purposes as all they can do is change ID number on URL and get access to a different document (that they are not supposed to see) My questions are: A- Is there a way to create a unique link for every generated PDF that I can send to clients? B- Would it be better to create another field in the model of a randomly generated 15 character value, that I use instead of the ID in the parameter? -
How to implement a sequence of forms
New to Django here. I want to implement two forms in a sequence, where the second form depends on the saving of the first form. For example: View_A implements GET / POST methods of form A. Once Form A is submitted and saved, it will generate a unique ID. Form A also has a radio button with two choices (B and C). Depending on the choice made, I need to present the user with a second form B or a form C, where the unique ID from form A is filled automatically. The prerequisite for forms B and C is that the unique ID on form A is present. I can't use AJAX, because the form A needs to be saved first. My problem is, as soon as I hit the submit button of form A, it becomes a POST request. I can generate the unique ID and display it in the returned html template. However, it's still the same view and I don't know how the display of next form. The display of form B/C should ideally be a GET request. But I am in the POST request. I hope this is a clear enough question. Thanks -
Updating user profile - Django
I've created a template for updating account profiles using a Bootstrap snippet (from https://www.bootdey.com). With the django default format (like {{ form.as_p }}), updating accounts works (for example, when I modify the first name, it changes in the database). When I use the bootstrapp snippet, it doesn't update: it goes straight to 'homepage' without updating (as explained in views.py). In forms.py class EditAccountForm(UserChangeForm): class Meta: model = Account fields = ('email','first_name','last_name') In views.py def EditProfile(request): context= {} if request.POST: form = EditAccountForm(request.POST, instance=request.user) if form.is_valid(): form.save() email = form.cleaned_data.get("email") raw_password = form.cleaned_data.get("password1") account = authenticate(email=email,password=raw_password) return redirect('profile_page') else: context['edit_form'] = form return redirect('homepage') else: form = EditAccountForm(instance=request.user) context['edit_form'] = form return render(request,'Account/edit_page.html',context) the template: edit_profile.html (I only show the first_name part as example) <form method = "POST" class="form" novalidate=""> {% csrf_token %} <div class="row"> <div class="col"> <div class="row"> <div class="col"> <div class="form-group"> <label>First name</label> <input class="form-control" type="text" name="firstna" value={{ edit_form.first_name.value }}> </div> </div> </div> </div> <div class="row"> <div class="col d-flex justify-content-end"> <button class="btn btn-primary" type="submit">Save Changes</button> PS: I've preferred to use those snippets instead of the Django style since I find them more attractive and offer more freedom. -
In Django, why does the reverse fucntion passes a tuple as argument?
The Django tutorial uses the reverse function as HttpResponseRedirect(reverse('polls:results', args=(question.id,))). The 'results' view is defined as results(request, question_id). I understand that (question.id,) is a single element tuple but, why do we even pass a tuple instead of just question.id?