Django - Allow custom users edit their profile - python

I think I've tried all the solutions from Internet to allow custom users to edit their profile but I still can't manage to do it.
To illustrate my architecture, I have a profile page on which there is an edit button. This button open a modal form to edit the profile. I think I have to do something with my url (to include pk in it) but I don't understand how : if I use a simple path (without pk) I have this error :
Reverse for 'edit_profile_modal' not found. 'edit_profile_modal' is not a valid view function or pattern name and when I try to add pk I have this one : Reverse for 'edit_profile' with no arguments not found. 1 pattern(s) tried: ['accounts/edit_profile/(?P[0-9]+)$']
Here is my code :
accounts/url.py
urlpatterns = [
...
path('profil/', ProfileView.as_view(), name="profil"),
path('edit_profile/',EditProfileView.as_view(),name="edit_profile"),]
views.py
class EditProfileView(BSModalUpdateView):
model = Account
template_name = 'accounts:edit_profile'
form_class = EditProfileForm
success_message = 'Le profil a été modifié avec succès'
success_url = reverse_lazy('accounts:profil')
profil.html
<!--Modal-->
<script type="text/javascript">
$(document).ready(function() {
$("#edit-profile").modalForm({
formURL: "{% url 'accounts:edit_profile' %}"
});
});
</script>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
</div>
</div>
</div>
<button id="edit-profile" class="btn btn-primary" type="button" name="button"><a class="nav-link active" href="{% url 'accounts:edit_profile_modal'%}">Editer »</a></button>
edit_profile_modal.html
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Account</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{% render_field field class="form-control" placeholder=field.label %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div><form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Account</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{% render_field field class="form-control" placeholder=field.label %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
{% endfor %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
forms.py
class EditProfileForm(BSModalModelForm):
class Meta:
model = Account
fields = ['email', 'username','prenom','nom','birthday']
models.py
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
prenom = models.CharField(max_length=30)
nom = models.CharField(max_length=30)
birthday = models.DateField(auto_now=False, auto_now_add=False, default=now)
objects = MyAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['prenom', 'nom']
description = models.CharField(max_length=50, default='')
birthday = models.DateField(auto_now=False, auto_now_add=False, default=now)
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
def getFirstNameAndName(self):
return self.prenom +" "+self.nom

In your html you have:
href="{% url 'accounts:edit_profile_modal'%}
But in your urls you call it edit_profile
So changing that plus adding the pk would give:
href="{% url 'accounts:edit_profile' pk=object_pk %}
And change your url to:
path('edit_profile/<int:pk>',EditProfileView.as_view(),name="edit_profile")

Related

How can I get this form to work and save the updated information?

I was successful at getting the form to appear on the modal which was an issue I had earlier, now I'm struggling to make this work. Any way to work my way around this?? Also I wanna check if method == 'POST' before checking if the form is valid but can't seem to find a solution..
views:
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'network/profile.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get(username__iexact=self.request.user)
profile = Profile.objects.get(user=user)
form = ProfileModelForm(instance=profile)
confirm = False
rel_r = Relationship.objects.filter(sender=profile)
rel_s = Relationship.objects.filter(receiver=profile)
rel_receiver = []
rel_sender = []
for item in rel_r:
rel_receiver.append(item.receiver.user)
for item in rel_s:
rel_sender.append(item.sender.user)
if form.is_valid():
form.save()
confirm = True
context["rel_receiver"] = rel_receiver
context["rel_sender"] = rel_sender
context["posts"] = self.get_object().get_all_authors_posts()
context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False
context["form"] = form
context["confirm"] = confirm
context["profile"] = profile
return context
Form:
class ProfileModelForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio', 'avatar')
Model:
class Profile(models.Model):
first_name = models.CharField(max_length=64, blank=True)
last_name = models.CharField(max_length=64, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=64, blank=True)
avatar = models.ImageField(upload_to='avatars', default='avatar.png')
background = models.ImageField(upload_to='backgrounds', default='background.png')
following = models.ManyToManyField(User, related_name='following', blank=True)
bio = models.TextField(default="No Bio..")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True, blank=True)
objects = ProfileManager()
def __str__(self):
return f"{self.user.username}"
def get_absolute_url(self):
return reverse("profile-view", kwargs={"slug": self.slug})
HTML:
{% extends "network/layout.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
My Profile
{% endblock title %}
{% block body %}
<!--Modal-->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Your Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img width="100px" src="{{profile.avatar.url}}">
<form action="", method="POST", enctype="multipart/form-data" class="form">
{% csrf_token %}
{{form}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
</div>
<div>
{% if confirm %}
<div class="alert alert-info" role="alert">Your profile has been updated!</div>
{% endif %}
</div>
<div class="row py-5 px-4">
<div class="col-md-5 mx-auto">
<!-- Profile widget -->
<div class="bg-white shadow rounded overflow-hidden">
<div class="px-4 pt-0 pb-4 cover">
<div class="media align-items-end profile-head">
<div class="profile mr-3"><img src="{{object.avatar.url}}" width="130" class="rounded mb-2 img-thumbnail"></div>
<div class="media-body mb-5 text-white">
<h4 class="mt-0 mb-3">{{profile.first_name}} {{profile.last_name}}</h4>
<p style="color: black;" class="small mb-4"> <i class="fas fa-map-marker-alt mr-2"></i>{{profile.country}}</p>
</div>
</div>
</div>
<div class="bg-light p-5 d-flex justify-content-end text-center">
<ul class="list-inline mb-0">
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_posts_num}}</h5><small class="text-muted"> <i class="fas fa-image mr-1"></i>Posts</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_followers_num}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Followers</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">340</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Following</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_liked}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Likes</small>
</li>
</ul>
</div>
<div class="ml-2">
{% if object.user and object.user not in rel_receiver and object.user not in rel_sender %}
<form action="{% url 'send-invite' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-success w-btn"><i class="bi-plus-lg"></i> Follow</button>
</form>
{% endif %}
{% if object.user in rel_receiver and request.user not in object.following.all %}
<button class="btn btn-sm disabled "><i class="bi-three-dots"></i> Waiting aprroval</button>
{% endif %}
{% if request.user in object.following.all %}
<form action="{% url 'remove-friend' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-dark w-btn"><i class="bi-dash-lg"></i> Unfollow</button>
</form>
{% endif %}
</div>
<div class="px-4 py-3">
<h5 class="mb-0">About</h5>
<button class="btn btn-sm btn-secondary float-right" id="modal-btn" data-toggle="modal" data-target="#profileModal">Edit Profile</button>
<div class="p-4 rounded shadow-sm bg-light">
<p class="font-italic mb-0">{{profile.bio}}</p>
</div>
</div>
<div class="py-4 px-4">
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="mb-0">Recent posts</h5>Show all
</div>
{% if len_posts %}
<div class="row">
{% for post in posts %}
<div class="col-lg-6 mb-2 pr-lg-1 fluid">
{% if post.picture %}
<img class="card-img-profile" src="{{post.picture.url}}">
{% endif %}
{{post.content}}
</div>
{% endfor %}
{% else %}
<h1>This user didn't post anything yet..</h1>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Not sure if you have tried this:
In your view you should write a function called post.
def post(self, request):
if request.method == 'POST':
form = self.form(request.POST)
if form.is_valid():
*whatever you need to do after you've validated the from*

Can not save form with CreateView (Django, Python)

I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
model = HotelBookingAd
form_class = HotelBookingAdForm
template_name = "account/article-create-update.html"
def form_valid(self,form):
form.save()
return super(HotelAdCreate).form_valid(form)
Forms.py
class HotelBookingAdForm(forms.ModelForm):
class Meta:
model = HotelBookingAd
fields = '__all__'
def clean_sales_price(self):
sales_price = self.cleaned_data["sales_price"]
purchase_price = self.cleaned_data["purchase_price"]
if sales_price > purchase_price:
raise forms.ValidationError("error.")
print("error")
return sales_price
Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title- mb-0">ایجاد آگهی </h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div class="col-6">
{{form.title|as_crispy_field}}
</div>
<div class="col-6">
{{form.hotel_name|as_crispy_field}}
</div>
<div class="col-12">
{{form.sale_reason|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_in_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_out_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.purchase_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.sales_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.city_name|as_crispy_field}}
</div>
<div class="col-6">
{{form.room_type|as_crispy_field}}
</div>
<div class="col-6">
{{form.confirm|as_crispy_field}}
</div>
{% if user.is_superuser %}
<div class="col-6">
{{form.slug_generator|as_crispy_field}}
</div>
{% endif %}
</div>
<button class="btn btn-success">ارسال مقاله</button>
{% if user.is_superuser and request.resolver_match.kwargs.pk %}
<a class="btn btn-danger "href="{% url 'account:hotelad-delete' request.resolver_match.kwargs.pk %}">
حذف مقاله
</a>
<a target="_blank" class="btn btn-dark "href="{% url 'primary:preview' request.resolver_match.kwargs.pk %}">
پیش نمایش
</a>
{% endif %}
</form>
</div>
</div>
</div>
{% endblock %}
I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)

Django - External URL Link

I am new to Python and Django, and I have just created a website.
Basically I would like to have a page on the website that displays our company partners.
I have created an app 'partners' and in the model, I have 'website' as one of the fields.
On the partners html file, I have a button that users can click and this will take them to the partner's website in a new tab.
I tried to link the website in the following way:
{{ partner.website }}
However this ends up like:
www.mydomain.com/partners/www.partnerwebsite.com
I just want the partner website (www.partnerwebsite.com) to open in a new tab.
Any help appreciated. If there is already another post on this, please redirect me.
views.py
from django.shortcuts import render, redirect
from .models import Partner
def index(request):
partners = Partner.objects.order_by('-date_added').filter(is_published=True)
context = {
'partners': partners,
}
return render(request, 'partners/partners.html', context)
models.py
from django.db import models
from datetime import datetime
class Partner(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
website = models.CharField(max_length=100)
email = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
phone = models.CharField(max_length=100)
mobile = models.CharField(max_length=100)
address = models.CharField(max_length=200)
photo_main = models.ImageField(upload_to='photos/partners/%Y/%m/%d/')
promo_code = models.CharField(max_length=20, blank=True)
is_published = models.BooleanField(default=True)
date_added = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name
partners.html
{% extends 'base.html' %}
{% block title %} | Partners {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Partners</h1>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Partners</li>
</ol>
</nav>
</div>
</section>
<!-- Partners -->
<section id="partners" class="py-4">
<div class="container">
<div class="row">
{% if partners %}
{% for partner in partners %}
<!-- Partner 1 -->
<div class="col-md-6 col-lg-6 mb-4">
<div class="card listing-preview">
<img class="card-img-top-project" src="{{ partner.photo_main.url }}" alt="">
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ partner.name | title }}</h4>
<p><i class="fas fa-map-marker text-secondary"></i>   {{ partner.address }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12 text-center">
{{ partner.description }}
</div>
</div>
{% if partner.promo_code %}
<hr>
<div class="row py-2 text">
<div class="col-12 text-center">
Use the following code to obtain 10% discount: {{ partner.promo_code }}
</div>
</div>
{% endif %}
<div class="container">
<hr>
<button class="btn btn-secondary btn-block">Visit Website</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="container">
<p><h5 class="text-center">No Partners Available</h5></p>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='partners'),
]
I was able to deduce the below solution from your views file. Add the below code in your template "partners.html"
{% for value in partners %}
<button>my button </button>
{% endfor%}

Change button depending on if photo is liked in django

I am adding a functionality in my website, where users can like posts.
I have successfully done this, however I am having trouble adding one functionality.
This is text within a button depending on whether a post is liked or not.
Right now the button stays the same no matter if the post is liked or not.
models.py
class Post(models.Model):
file = models.ImageField(upload_to='images/')
summary = models.TextField(max_length=600)
pub_date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, through='Like', related_name='likes')
def __str__(self):
return self.user.username
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def summary_pretty(self):
return self.summary[:50]
#property
def total_likes(self):
return self.likes.count()
class Like(models.Model):
status = models.BooleanField()
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
def likepost(request, post_id):
if request.method == 'POST':
post = get_object_or_404(Post, pk=post_id)
user = request.user
if post.likes.filter(id=user.id).exists():
post.likes.remove(user)
return redirect('home')
else:
like = Like()
like.post = post
like.user = user
like.status = True
like.save()
post.likes.add(user)
return redirect('home')
my template:
{% if post.likes.status == True %}
<button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button>
{% else %}
<button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }} </button>
{% endif %}
EDIT - HOME VIEW:
#login_required(login_url="/login")
def home(request):
posts = Post.objects.all()
return render(request, 'posts/home.html', {'posts': posts})
EDIT 2:
{% extends 'accounts/base.html' %}
{% block content %}
{% load static %}
{% for post in posts.all %}
<div class="container pl-5">
<div class="row pt-3">
<img src="{% static 'grey.jpg' %}" width="600px" height="60px">
<div class="pt-3 pl-5" style="position: absolute;"> <b> {{ post.user.username }} </b> </div>
</div>
<br>
<div class="card" style="width: 600px; bottom: 24px; right: 15px;">
<img src="{{ post.file.url }}" width="599px">
</div>
<br>
<div class="card" style="width: 600px; bottom: 50px; right: 15px;"> <img src="{% static 'grey.jpg' %}" width="600px" height="150px"> </div>
<div class="col-6" style="bottom:145px; left: 5px;">
<div style="position: absolute;"> <b> {{ post.user.username }} </b> {{ post.summary_pretty }}</div>
</div>
{% for like in post.likes.all %}
{{like.username}}
{% endfor %}
{% if like.status %}
<button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button>
{% else %}
<button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }} </button>
{% endif %}
<form id="likepost{{ post.id }}" method="POST" action="{% url 'likepost' post.id %}">
{% csrf_token%}
<input type="hidden">
</form>
</div>
<br>
<br>
<br>
{% endfor %}
{% endblock %}
In your model you have defined likes as a ManyToManyField field:
class Post(models.Model):
likes = models.ManyToManyField(User, through='Like', related_name='likes')
But in your template you are trying to get a single boolean value from many likes:
{% if post.likes.status == True %}
post.likes will return multiple objects. You need to instead get the like based on the user.
EDIT:
One way you could get the like status is by doing the following in your view:
context['like'] = Like.objects.get(post=post, user=request.user)
Then in your template:
{% if like.status == True %}

Django 2 form in modal

Im tries to open in Django the user edit form in Bootstrap modal. But the form is empty, only the save button is shown. But I don't understand how I can make the connection. If I call the edit page directly, then I can edit the user
127.0.0.1:8000/account/edit/
index.html, includes the referral to the form
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'account:edit_profile' %}">
<input type="submit" value="Edit" />
</form>
<form action="{% url 'account:change_password' %}">
<input type="submit" value="Change Login" />
</form>
<br>
Open Modal
<br>
<div class="control-label col-sm-2">
First name:
</div>
<div class="col-sm-2">
{{ user.first_name }}
</div><br>
<div class="control-label col-sm-2">
Last name:
</div>
<div class="col-sm-2">
{{ user.last_name }}
</div><br>
<div class="control-label col-sm-2">
Email:
</div>
<div class="col-sm-2">
{{ user.email }}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-profile-modal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" align="center">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<div id="div-forms">
{% include "account/edit_profile.html" with form=form %}
</div>
</div>
</div>
</div>
{% endblock %}
edit_profile.html
{% block head %}
{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<h3>Profile</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
<button type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
views.py
def edit_profile(request):
if request.method == 'POST':
user_form = EditUserForm(request.POST, instance=request.user)
if all([user_form.is_valid(), profile_form.is_valid()]):
user_form.save()
return render(request, 'account/index.html')
else:
user_form = EditUserForm(instance=request.user)
args = {'user_form': user_form}
return render(request, 'account/edit_profile.html', args)
urls.py
urlpatterns = [
...
url(r'^edit/$', views.edit_profile, name='edit_profile'),
...
]
forms.py
class EditUserForm(forms.ModelForm):
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name'
)
Im using:
Python 3.6.3
Django 2.0.7
Windows 8.1
Bootstrap 3.3.6
JQuery 1.12.0
I think that variable form doesn't exist and you use in template just user_form not form variable
{% include "account/edit_profile.html" with form=form %}
Try use it:
{% include "account/edit_profile.html" with user_form=user_form %}
Maybe you could try the code I wrote and you can find it at django-bootstrap-modal-forms. You will be able to bind your form to the modal and all of the validation stuff will work out of the box.
You will create a trigger element opening the modal
Your selected form will be appended to the opened modal
On submit the form will be POSTed via AJAX request to form's URL
Unsuccessful POST request will return errors, which will be shown under form fields in modal
Successful POST request will redirects to selected success URL

Categories

Resources