How i can split a Email in Django [duplicate] - django

This question already has answers here:
Split text before # in email in Django
(3 answers)
Closed 3 months ago.
Good morning
I've been sitting for 5 hours on what should be a simple problem. I would be grateful if you could end my suffering.
It is about a dashboard page. I want the user to be greeted with his name (Hello, ....) after he has registered with his email address. When registering, the email address is always the same, name.example#hotmail.de. I want to split the email address and display only the name, but I can only manage to display the whole email address.
view.py
#login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user #current_user.split is not working!
context = {'form': form, "cunrrent_user": current_user}
return render(request, 'example_dashboard.html', context)
html
<p>Welcome, {{ current_user}} </p>
<form action='' method='POST'>
{%csrf_token%}
{{ form }}
models.py
class Members(models.Model):
email = models.CharField(max_length=200, null=True)
passwort = models.CharField(max_length=200, null=True)
forms.py
class MembersForm(ModelForm):
class Meta:
model = Members
fields = ["studiengang", "kategorien"]

current_user = request.user #current_user.split is not working!
It will not work becouse request.user is a User object not a String you can't split user object instead you can do like this to split user's email.
#login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user
name = current_user.email.split('#')[0] # or .split('.example#hotmail.de')[0]
context = {'form': form, "cunrrent_user": current_user}
return render(request, 'example_dashboard.html', context)

You can make this possible by using split method
After current_user = request.user, Try this:
current_user = current_user.split('#')[0]

Try this solution. Because of request.user is None. That's why you can't split an email.
current_user = request.POST.get(‘email’)
user_name = current_user.split('#')[0]

Related

How to query a user's display information in the AccountDisplayInformation from the AccountModel

Account is my AUTH_USER_MODEL and AccountDisplayInfo consists of all the additional display info of every account. So they can input and submit, and subsequently update their information. These are my codes, but I'm unsure why it isn't working. First of all, I am receiving this error:
DoesNotExist at /account/5/displayinfo/ AccountDisplayInfo matching query does not exist.
Secondly, the "update" function isn't working.
models.py
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
class AccountDisplayInfo(models.Model):
account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
instagram = models.CharField(max_length=50, unique=True, blank=True, null=True) #instagram
.html
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary btn-sm col-lg-5">Update</button>
</div>
</form>
views.py
def display_information_view(request, *args, **kwargs):
user_id = kwargs.get("user_id")
account = Account.objects.get(pk=user_id)
context = {}
displayinfo = AccountDisplayInfo.objects.get(account=account)
if request.POST:
form = DisplayInformationForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
info = form.save(commit=False)
info.account = request.user
info.save()
messages.success(request, 'Your profile display information have been updated', extra_tags='editdisplayinfo')
return redirect("account:view", user_id=account.pk)
else:
form = DisplayInformationForm(request.POST, instance=request.user,
initial={
"instagram": displayinfo.instagram,
}
)
context['form'] = form
else:
form = DisplayInformationForm(
initial={
"instagram": displayinfo.instagram,
}
)
context['form'] = form
return render(request, "account/displayinfo.html", context)
forms.py
class DisplayInformationForm(forms.ModelForm):
class Meta:
model = AccountDisplayInfo
fields = ('instagram')
Also, would be great if you can advise on this::
If I have 2 tables. Table 1 and Table 2. Table 2 has a foreign key to table 1 but table 1 dont have a foreign key to table 2. How can I query table 2's data from table 1? Thanks
By default .get() will return a DoesNotExist exception if no object matches the query you executed and stop the code from running, so if you want to input it manually on the same page use filter instead:
displayinfo = AccountDisplayInfo.objects.filter(account=account).first()
Then in your template do something like this:
{% if displayinfo %}
... show display info...
{% else %}
<p> No info yet </p> <!-- (or show some form) -->
{% endif %}
To answer your other question:
You have to use the related_name or related models attribute to access the ForeignKey data or use the model name with the _set suffix, for example:
class Post(models.Model):
title = models.CharField(max_lenght=10)
class Comment(models.Model):
body = models.CharField(max_lenght=200)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
then you would get the Post and its comments:
post = Post.objects.get(pk=1)
comments = post.comments.all()
if you didn't have the related_name attribute in your model field you would do this instead:
comments = post.comment_set.all()
UPDATE
Maybe the issue is in your Form class, try removing the save method from it and instead do this in your view:
if request.POST:
form = DisplayInformationForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
info = form.save(commit=False)
info.account = request.user
messages.success(request, 'Your profile display information have been updated', extra_tags='editdisplayinfo')
info.save()
return redirect("account:view", user_id=account.pk)

How can I autofill author with a model form (video upload)

I need to tie the user to their post but 'author' is not included in the fields of the video upload form so I can't access the field when I save the form.
When I add 'author' to the fields it gives a drop down box. (users shouldn't be able to post as anyone but themselves) I tried just listing the fields individually like so {{form.title}} to keep the author field but not show it to the user, it showed anyway.
In the 'author' field of the VideoPost model I've tried changing out the null=True for these variants on default default=None, default=0, default='None', default=User, default=User.id where User = get_user_model()
When I used default='None' the author dropdown box had the current users name in it, but still allowed a choice, when I tried to post it I got
ValueError: invalid literal for int() with base 10: 'None'
Also, in the views.py, I tried form = VideoPostForm(request.user,request.POST or None, request.FILES or None)
and got CustomUser object has no .get() attribute and that was caused by form.save()
I feel like this might be obvious to someone else but I've been staring at this code for a while now to figure it out.(a couple hours a day doing research and gaining better understanding as to how all of the things I'm doing actually work 'under the hood', I worked on other parts while trying to figure this out because, development speed matters and I could actually figure the other stuff out)
forms.py
class VideoPostForm(forms.ModelForm):
class Meta:
model = VideoPost
fields = ['author','title', 'description', 'file']
views.py
def upload_video(request):
form = VideoPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save(commit=False)
VideoPost.author = request.user
form.save()
return redirect('home')
else:
form = VideoPostForm()
return render(request, 'upload_video.html', {'form': form})
models.py
class VideoPost(models.Model):
objects = models.Manager()
author = models.ForeignKey(User, related_name='video_post', on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=50, null=True, blank=True)
published_date = models.DateTimeField(auto_now_add=True)
description = models.TextField()
validate_file = FileValidator(max_size=52428800)
file = models.FileField(upload_to='videos/', validators=[validate_file])
def __str__(self):
return 'Post by {}'.format(self.author)
template (excluding author field)
<h1>Create Post Page</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<p> <!-- Normally the fields would be form.as_p -->
{{ form.title }}
{{ form.description }}
{{ form.file }}</p>
<button type="submit">Submit New Post</button>
</form>
The views.py is very close. The form.save() method returns an instance of VideoPost. You can then set the author to the current user directly to the new video post object that was created by the form. See code sample below.
views.py
def upload_video(request):
if request.method == "POST":
form = VideoPostForm(request.POST, request.FILES or None)
if form.is_valid():
new_videopost = form.save()
new_videopost.author = request.user
new_videopost.save()
return redirect('home')
else:
form = VideoPostForm()
return render(request, 'upload_video.html', {'form': form})

Is there a way to get the time of users last logout time Django example user.last_logout (does anything like this exist)

Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. Users have to choose from the existing groups for their posts. Users cannot add, delete, update group's.
Furthermore:
Users can become a member of groups and when they click on a certain group. They see all the posts in that group.
What I want When Users come on the home page they see posts that were added since the last time they logged in
My Models
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
group = models.ForeignKey(Group, related_name='posts')
title = models.CharField(max_length=250, unique=True)
message = models.TextField()
created_at = models.DateTimeField(auto_now=True)
My Views
class Homepage(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(Homepage, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
context['object_list'] = Group.objects.filter(members=self.request.user)
#The last login actually shows the users current login time as the last login. Which makes the below line of code useless
new_posts = Post.objects.filter(created_at__gt=self.request.user.last_login).count()
context['new_posts'] = new_posts
else:
context['object_list'] = Group.objects.all()
return context
In my templates I have
<div class="list-group">
{% for group in object_list %}
{% if not new_posts %}
{{group.post.count}}
{% else %}
{{new_posts}}
{% endif %}
{% endfor %}
</div>
The Issue: The last login actually shows the users current login time as the last login. Is there a way to get users last logout time instead of last login time example user.last_logout
I have the below answer but it doesn't seem to work for me
Django created_at__gt=self.request.user.last_login workinly only on users already signed in.
My profile create function
def signup(request):
if request.method == 'POST':
form = UserCreateForm(request.POST or None)
if form.is_valid():
new_user = form.save()
Profile.objects.create(user=new_user)
return redirect('accounts:edit_profile')
here is an example
class ProfileModel(models.Model):
#fields
last_time_logout = models.DateTimeField()
In a custom view, record the last logout
import datetime
def signout(request):
profile = reques.user.profile # it depends
if request.is_ajax(): # Do it with ajax
logout(request)
profile.last_time_logout = datetime.datetime.now()
profile.save()
return redirect("signin")
raise PermissionDenied

how do I get only text field data from django modelform for email submission?

how do I get only the text field data from a django modelform for email submission? Ive tried a lot of variations in the view, cleaned_data.get() def clean(self): methods etc. Not sure why this is so hard.
# models.py - service model
class Service(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
service_type = models.ManyToManyField('ServiceType')
description = models.TextField(blank=True)
def __str__(self):
return "Service Order for: {user}".format(user=self.user)
class ServiceType(models.Model):
label = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.label
# forms.py
class NewServiceForm(forms.ModelForm):
accept_tos = forms.BooleanField(required=True)
class Meta:
model = Service
fields = '__all__'
exclude = ('user', 'created_at',)
# views.py
#login_required
def newservice(request):
if request.method == 'POST':
form = NewServiceForm(request.POST)
if form.is_valid():
form.instance.user = request.user
service = form.save()
# SEND EMAIL - send copy of project/service modelform data to user and site owner
name = request.user.first_name+request.user.last_name
username = request.user.username
subject = 'New Service Order'
from_email = request.user.email
service_data = form.cleaned_data
message = ''' From: {} {} {}
\n {}
\n {}
'''.format(name, from_email, username, subject, service_data)
recipients = ['mytestemail#gmail.com', request.user.email]
try:
send_mail(subject, message, from_email, recipients)
except BadHeaderError:
return HttpResponse('Invalid header found.')
# END EMAIL
messages.warning(request, 'Success! Your service order has been submitted.')
return redirect('projects')
else:
messages.error(request, 'Invalid submission, check and try again.')
else:
form = NewServiceForm()
return render(request, 'dashboard/newservice.html', {'form': form})
# newservice.html
<form method="post" id="newprojectform">
{% csrf_token %}
Service Type <br> {{ form.service_type }} <br><br>
{{ form.accept_tos }} <br><br>
Description {{ form.description }} <br><br>
<button class="btn btn-sm" type="submit">Submit</button>
</div>
</form>
Im getting wrong output sent to my email inbox below: I just want text output of choices, and description sent to my email inbox (and not boolean=True), ie 'Edit Content Add Content Test Description goes here'
{'service_type': <QuerySet [<ServiceType: Edit Content>, <ServiceType: Add Content>, 'accept_tos': True, 'description': 'Test Description goes here'}
after lots of issues with m2m form field data retrieval I pulled data from the created model using project = form.save() object. much strife, but somewhat easier solution.

Django 2-ModelForm user registration and double submission error

I'm trying to create a basic user registration system for clients of a web application.
I've created the appropriate views and templates to create a form page which creates a Django User object and a UserProfile object of my own creation. (These are linked via a 1-1 field).
After visiting and filing in the forms on my registration page, I click submit and the fields related to initializing the UserProfile fields will be cleared and a "This field is required." error will be displayed over each input box (despite being properly filled in previously). If I fill these selected fields in again, and press submit the registration request will be processed correctly.
In the terminal, I've printed out the value of is_valid() for each form. On the first pass, the User form returns true, while the UserProfile form returns false. On the second submission they both return true.
Could you help me understand why this second form is returning false on the first pass and forcing me to resubmit?
Code is below:
models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=32)
email = models.CharField(max_length=100)
institute = models.CharField(max_length=100)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
postal_code = models.CharField(max_length=24)
description = models.TextField(max_length=2500)
def __unicode__(self):
return self.name
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email']
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
views.py
def registration(request):
if request.method == 'POST':
print('post')
user_form = UserForm(request.POST, prefix='user')
profile_form = UserProfileForm(request.POST, prefix='userprofile')
print('user form ' + str(user_form.is_valid()))
print('profile form ' + str(profile_form.is_valid()))
if user_form.is_valid() and profile_form.is_valid():
print('both valid')
user = user_form.save(commit=False)
user.is_active = False
user.save()
userprofile = profile_form.save(commit=False)
userprofile.user = user
userprofile.save()
print('success')
return HttpResponseRedirect('registration-success/')
else:
print('unbound')
user_form = UserForm(prefix='user')
profile_form = UserProfileForm(prefix='profile')
context = { 'userform': user_form,
'userprofileform': profile_form,}
return render(request, 'registration/register.html', context)
def success(request):
return render(request, 'registration/success.html', )
template.html
<!DOCTYPE html>
<html>
<body>
<h2> Registration </h2>
<form method="POST">
{% csrf_token %}
{{userform}}
</br></br>
{{userprofileform}}
<input type="submit" value="Submit"/>
</form>
forgot username/password<br />
new user
</body>
</html>
In your POST codepath, you have this:
profile_form = UserProfileForm(request.POST, prefix='userprofile')
In your else codepath, this:
profile_form = UserProfileForm(prefix='profile')
The prefix values need to match so that the POST data will be bound correctly to the profile form. It works on your resubmission because that goes through the POST codepath, so the ids used in the template match those the form object expects.