I am having trouble finding out my mistake. In my app I am creating a user that is set as inactive and then sending to those users a mail invitation to join my app. I set it up to be able to send multiple invitations but it only send one on the X invitations. So if I invite 5 users, only on mail is sent and 1 user created instead of 5. I guess there is something wrong with my loop but cannot find what..
here is my code
views.py:
def TeamRegister2(request):
InviteFormSet = formset_factory(InviteForm2)
if request.method == 'POST':
formset = InviteFormSet(request.POST, prefix = 'pfix')
if(formset.is_valid()):
for i in formset:
mail = i.cleaned_data['Email']
user = MyUser(email = mail)
password = MyUser.objects.make_random_password()
user.set_password(password)
user.is_active = False
user.is_employee = True
user.save()
u1 = user.id
a1 = MyUser.objects.get(email = request.user.email)
a2 = Project.objects.filter(project_hr_admin = a1)
a3 = a2.latest('id')
a4 = a3.team_id
a4.members.add(u1)
current_site = get_current_site(request)
message = render_to_string('acc_active_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
to_email = user.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
return HttpResponse('An email have been sent to each Team member asking them to join in')
else:
print("The entered form is not valid")
else:
formset = InviteFormSet(prefix= 'pfix')
return render(request,'team_register.html', {'formset':formset})
form.py:
class InviteForm2(forms.Form):
"""
Form for member email invite
"""
Email = forms.EmailField(
widget=forms.EmailInput(attrs={
'placeholder': "Member's mail",
}),
required=False)
team_register.html:
{% extends 'base.html' %}
{% load static %}
{% block body %}
<div class="container">
<div class="jumbotron">
<div class="title">
<h2>Invite your Team members</h2>
<h3>You can choose up to 7 team members</h3>
</div>
</div>
<div class="form-style">
<form method="post" class="form-inline">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="link-formset">
{{ form.label_tag }} {{ form }}
{% if field.help_text %}
<small style="display: none">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<div>
<input type="submit" value="Send Invitations" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
<!-- Include formset plugin - including jQuery dependency -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script>
$('.link-formset').formset({
addText: 'add member',
deleteText: 'remove'
});
</script>
{% endblock %}
Related
I'm only new to django & this is my first time posting on stack overflow so appologies if I havent done this right.
My problem is that when I use my login function, it only seems to work with those created with the createsuperuser command in the terminal. Those created within the website just dont work.
The users show within the admin panel and have a password within them.
models.py
class Trickster_User(AbstractBaseUser, PermissionsMixin):
UserID = models.AutoField(primary_key=True)
Email = models.EmailField(('Email Address'), unique=True)
Username = models.CharField(('Username'),max_length=25, unique=True)
FirstName = models.CharField(('First Name'),max_length=25)
LastName = models.CharField(('Last Name'),max_length=25)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = CustomUserManager()
USERNAME_FIELD = 'Email'
REQUIRED_FIELDS = ['Username', 'FirstName', 'LastName']
def __str__(self):
return self.FirstName + ' ' + self.LastName
views.py
def user_login(request):
context = {}
user = request.user
if user.is_authenticated:
return redirect('home')
if request.method == "POST":
form = UserAuthenticationForm(request.POST)
if form.is_valid():
Email = request.POST['Email']
password = request.POST['password']
user = authenticate(Email=Email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = UserAuthenticationForm()
context['user_login'] = form
return render(request, 'authentication/login.html', context)
forms.py
class UserAuthenticationForm(forms.ModelForm):
Email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
password = forms.CharField(label='password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model = Trickster_User
fields = ('Email', 'password')
def clean(self):
Email = self.cleaned_data['Email']
password = self.cleaned_data['password']
if not authenticate(Email=Email, password=password):
raise forms.ValidationError("Invalid Login")
login.html
{% block content %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Login </h1>
<br/><br/>
<form action="" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in user_login %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
{% if user_login.non_feild_errors %}
<div style="color:red";>
<p>{{ user_login.non_feild_errors }}</p>
</div>
{% endif %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
{% endblock %}
Code to register users:
views.py
def register_user(request):
context = {}
if request.method == "POST":
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
Email = form.cleaned_data.get('Email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(Email=Email, password=raw_password)
login(request, user)
messages.success(request, ("Registration Successful! Password"))
return redirect('home')
else:
context['UserRegistrationForm'] = form
else:
form = UserRegistrationForm()
context['UserRegistrationForm'] = form
return render(request, 'authentication/register_user.html', context)
register_user.html
{% block content %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
There was an error with your form!
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Register </h1>
<br/><br/>
<form action="{% url 'register_user' %}" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in UserRegistrationForm %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
Ive seen one other post on something simmilar to this but the only solution posted was to change the 'is_active' status to True by default.
I tried this and am still running into same issue.
New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got?
HTML:
<h1>This is the register.html</h1>
<div class="col-md-4 offset-md-4">
<form method="post">
{% csrf_token %}
{% for field in registration_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color: grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: grey;">{{error}}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Register</button>
</form>
</div>
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
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)
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
print(context)
return render(request, 'accounts/register.html', context)
forms.py
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address')
class Meta:
model = Account
fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name')
the form renders and works fine with registration, just looks kinda crappy. thanks!
You could render each field individually and take advantage of bootstrap styling as well. For example for the email field, you could have something like below
<div class="form-group">
{{ registration_form.email.label_tag }}
{{ registration_form.email }}
</div>
You can also have a div below it to display its errors on post
<div class="errors">
{% if registration_form.email.errors %}
{% for error in registration_form.email.errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endif %}
</div>
I'm trying to check if the user is logged into firebase in Django by requesting the session_uid in the home.html file. Which seems not to be working. How can I check if the firebase user is logged in?
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
# form.save()
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = auth.sign_in_with_email_and_password(email, password)
session_id = user['idToken']
request.session['uid'] = str(session_id)
messages.success(request, f'Account created for {email}!')
return redirect(request, 'blog-home')
else:
form = UserLoginForm()
return render(request, 'users/login.html', {'form': form, 'title': 'Login'})
home.html
{% extends "home/base.html" %} -->
{% block content %}
{% if request.session.session_id %}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<h2><a class="article-title" href="#">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% else %}
<h2>You need to login</h2>
{% endif %}
{% endblock content %}
You do the following in the view
session_id = user['idToken']
request.session['uid'] = str(session_id)
yet access like request.session.session_id in the template. You should be doing request.session.uid.
When i click on the sell product link from homepage it redirects to the login page and after login done it redirects to the homepage and i have to again click on the sell product link to fill the form.I want to redirect to the sell_product page after login instead of homepage.How can i do that ?? How can i redirect to the different pages from one signin url.
urls.py
path('signin/user/',views.users_signin,name='users_signin'),
path('sell/product/',views.sell_product,name='sell_product'),
views.py
def users_signin(request):
if request.method == "POST":
form = UserSigninForm(request.POST)
username = form['username'].value()
password = form['password'].value()
user = authenticate(username=username,password=password)
login(request,user)
return redirect('shop:home')
else:
form = UserSigninForm()
return render(request,'shop/users_signin.html',{'form':form})
def sell_product(request):
if request.user.is_authenticated:
if request.method == "POST":
form = SellProductForm(request.POST,request.FILES)
if form.is_valid():
myproduct = form.save(commit=False)
myproduct.seller = request.user
myproduct.save()
messages.success(request,'Your Product has been posted successfully.!!')
return redirect("shop:home")
else:
form = SellProductForm()
return render(request,'shop/sell_product.html',{'form':form})
else:
messages.error(request,'please login first')
return redirect('shop:users_signin')
sell_product.html
{% extends "shop/base.html" %}
{% load bootstrap4 %}
<title>{% block title %}Sell a Product{% endblock %}</title>
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-6 offset-lg-3 col-sm-10 offset-sm-1">
<div class="card my-5">
<div class="card-header text-center">
Sell Your Product
</div>
<div class="card-body">
<form action="{% url 'shop:sell_product' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-success text-center w-100 mb-3" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
base.html
<li class="nav-item">
<a class="nav-link" href="{% url 'shop:sell_product' %}">Sell a Product</a>
</li>
forms.py
class SellProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name','image','category', 'description', 'brand', 'quantity', 'price', 'shipping_fee']
class UserSigninForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
You may specify the next parameter in the url to set the redirect page after login.
Try
return redirect('%s?next=%s' % (reverse('shop:users_signin'), request.path))
See https://docs.djangoproject.com/en/2.2/topics/auth/default/#limiting-access-to-logged-in-users-that-pass-a-test
You may also use a #login_required decorator so as to omit the 'if-else` block that ensures the authentication.
I try to add follow button in django with Getstream.io app.
Following the getstream tutorial, django twitter, I managed to create a list of users with a functioning follow button as well as active activity feed. But when i try add follow button on user profile page, form send POST but nothing happends later.
I spend lot of time trying resolve this, but i'm still begginer in Django.
Code:
Follow model:
class Follow(models.Model):
user = models.ForeignKey('auth.User', related_name = 'follow', on_delete = models.CASCADE)
target = models.ForeignKey('auth.User', related_name ='followers', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add = True)
class Meta:
unique_together = ('user', 'target')
def unfollow_feed(sender, instance, **kwargs):
feed_manager.unfollow_user(instance.user_id, instance.target_id)
def follow_feed(sender, instance, **kwargs):
feed_manager.follow_user(instance.user_id, instance.target_id)
signals.post_delete.connect(unfollow_feed, sender=Follow)
signals.post_save.connect(follow_feed, sender=Follow)
Views:
def user(request, username):
user = get_object_or_404(User, username=username)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get()['results']
activities = enricher.enrich_activities(activities)
context = {
'user': user,
'form': FollowForm(),
'login_user': request.user,
'activities': activities,
}
return render(request, 'profile/user.html', context)
def follow(request):
form = FollowForm(request.POST)
if form.is_valid():
follow = form.instance
follow.user = request.user
follow.save()
return redirect("/timeline/")
def unfollow(request, target_id):
follow = Follow.objects.filter(user=request.user, target_id=target_id).first()
if follow is not None:
follow.delete()
return redirect("/timeline/")
Forms:
class FollowForm(ModelForm):
class Meta:
exclude = set()
model = Follow
Urls:
path('follow/', login_required(views.follow), name='follow'),
path('unfollow/<target_id>/', login_required(views.unfollow), name='unfollow'),
And user.html
<form action="{% if request.user in User.followers.all %}{% url 'unfollow' target.id %}{% else %}{% url 'follow' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" id="id_target" name="target" value="{{target.id}}">
<input type="hidden" id="id_user" name="user" value="{{user.id}}">
<button type="submit" class="btn btn-primary btn-sm" value="Create" />
{% if request.user in User.followers.all %}
Unfollow
{% else %}
Follow
{% endif %}
</button>
</form>
This form work in list user page:
{% for one, followed in following %}
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="card">
<div class="card-body">
{% include "profile/_user.html" with user=one %}
<form action="{% if followed %}{% url 'unfollow' one.id %}{% else %}{% url 'follow' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" id="id_target" name="target" value="{{one.id}}">
<input type="hidden" id="id_user" name="user" value="{{user.id}}">
<button type="submit" class="btn btn-primary btn-sm" value="Create" />
{% if followed %}
Przestań obserwować
{% else %}
Obserwuj
{% endif %}
</button>
</form>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:'4' %}
<div class="clearfix visible-sm-block visible-md-block visible-lg-block"></div>
{% elif forloop.counter|divisibleby:'2' %}
<div class="clearfix visible-sm-block"></div>
{% endif %}
{% endfor %}
</div>
And user list Views.py
def discover(request):
users = User.objects.order_by('date_joined')[:50]
login_user = User.objects.get(username=request.user)
following = []
for i in users:
if len(i.followers.filter(user=login_user.id)) == 0:
following.append((i, False))
else:
following.append((i, True))
login_user = User.objects.get(username=request.user)
context = {
'users': users,
'form': FollowForm(),
'login_user': request.user,
'following': following
}
return render(request, 'uzytkownicy.html', context)