I have a database like this:
from django.db import models
class User(models.Model):
firstName = models.CharField(max_length=30, blank=False, default=None)
lastName = models.CharField(max_length=30, blank=False, default=None)
email = models.EmailField(max_length=100, blank=False, default=None)
password = models.CharField(max_length=100, blank=False, default=None)
score = models.IntegerField(default=0)
in views.py I want to send a user that currently logged in and show its informations from DB at template.
my views.py:
user = User.objects.filter(email=request.POST['email'])
#some code ....
context = RequestContext(request, {
'user': user[0]
})
return HttpResponse(template.render(context))
my template :
{% if user %}
Wellcome {{ user.firstName }}
{% endif %}
but I don't see anything after welcome.also when I use this:
{% if user %}
Wellcome {{ user }}
{% endif %}
I see welcome anonymousUser where I am wrong ?
You cannot use user as the context variable, as it conflicts with the user object that is injected into the context by the processor
django.contrib.auth.context_processors.auth
Now, to fix your issue, rename user to user_obj or something which makes more sense.
Read more here
Based on the behavior you are describing you are likely not getting any objects returned from the call to filter:
user = User.objects.filter(email=request.POST['email'])
I would look at the value that is returned from request.POST['email'] and making sure that value is in your datbase as the starting point.
Also, you should be aware that the filter function returns a QuerySet and not a User object. If you want to retrieve a unique User object you can use the get function instead.
Related
I am building a competition website where challenges will be released weekly. For each user I want to track if they have completed a challenge but cannot see how this would be done. Currently the challenges are stored as a model and am using the ListView and DetailView to display them.
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0, 'Draft'),
(1, 'Publish'),
)
class Challenge(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
release_date = models.DateTimeField()
preamble = models.TextField()
ciphertext = models.TextField()
plaintext = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-release_date']
def __str__(self):
return self.title
Thank you in advance to anyone who helps me with this. Oh and a solution will be submitted and then checked with this form.
<div class='form'>
{% if user.is_authenticated %}
<textarea rows="10" name="plaintext" form="submitAnswer" wrap="soft" placeholder="Plaintext.."></textarea>
<form method="post" id="submitAnswer">
{% csrf_token %}
<input type="submit" value="Submit">
</form>
{% else %}
<p>Must be logged in to submit answer.</p>
{% endif %}
</div>
A really basic implementation is to add a ManyToManyField between your Challenge model and your the User model :
from django.conf import settings
class Challenge(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL)
# Other fields...
In the above example, you can just activate the relationship if the user has passed the test.
Now, maybe, you want to add informations about this relationship. You can do it with 'through' argument. This model tells if a user has passed the challenge or not and how many tentatives has been done. Modify it as you wish.
from django.conf import settings
class Challenge(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='ChallengeUsers')
# Other fields...
class ChallengeUsers(models.Model):
challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE)
users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
hasPassed = models.BooleanField(default=False)
tentatives = models.IntegerField()
I am using Django-all auth for creating user accounts. I want to get First name, Last name, Email, and Password while signing up. But Sign up page Doesn't show First name and Last name. Sign up page showing only Email and Password. Could someone help me with that? Please let me know if you need any other information. Thanks!
Models.py
class CustomUser(AbstractUser):
# add additional fields in here
first_name = models.CharField(max_length=128, blank=True, null=True)
last_name = models.CharField(max_length=128, blank=True, null=True)
def __str__(self):
return self.email
Forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('email','first_name','last_name')
Signup.html
<h2>Sign Up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
According to the Docs, you can override the the signup form. The default values are:
ACCOUNT_FORMS = {
'add_email': 'allauth.account.forms.AddEmailForm'
'change_password': 'allauth.account.forms.ChangePasswordForm'
'disconnect': 'allauth.socialaccount.forms.DisconnectForm'
'login': 'allauth.account.forms.LoginForm'
'reset_password': 'allauth.account.forms.ResetPasswordForm'
'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm'
'set_password': 'allauth.account.forms.SetPasswordForm'
'signup': 'allauth.account.forms.SignupForm'
'signup': 'allauth.socialaccount.forms.SignupForm'
}
It can be done by just adding ACCOUNT_FORMS = {'login': 'myapp.forms.CustomUserCreationForm'} to your settings.py.
Does this work for you?
There are some problems here. First of all, I'm not sure if you want to set blank=True [Django-doc], since that means that by default Django will hide these fields from editing. You might even not want to make these null=True [Django-doc] either, since that means the users are not required to fill these in. Your probably do not want that:
class CustomUser(AbstractUser):
first_name = models.CharField(max_length=128, null=True)
last_name = models.CharField(max_length=128, null=True)
def __str__(self):
return self.email
As for the form, you should not subclass Meta from the UserCreationForm itself. Perhaps you want to subclass it from the UserCreationForm.Meta:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('email','first_name','last_name')
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return '#{}'.format(self.username)
class placement(models.Model):
name=models.CharField(max_length=150, blank=True, null=True)
ad_space=models.CharField(max_length=100, blank=False, null=False)
PID_TYPE = (
('FN','FORMAT_NATIVE'),
('FNB','FORMAT_NATIVE_BANNER'),
('FI','FORMAT_INTERSTITIAL'),
('FB','FORMAT_BANNER'),
('FMR','FORMAT_MEDIUM,RECT'),
('FRV','FORMAT_REWARDED_VIDEO'),
)
format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False)
pid=models.CharField( max_length=50,default='',blank=False, null=False)
cpm=models.IntegerField(default=0,blank=False, null=False)
ADS_TYPE=(
('FB','FACEBOOK'),
('G','GOOGLE'),
)
source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False)
comments=models.TextField(default='',blank=False, null=False)
objects=models.Manager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("dashapp:disp")`
Now what should i do to only get only the logged in user content to be displayed on the template.As currently all the stored data is being fetched . That is logged out user for data is being displayed.
I'm Basically a beginner so i dont have any advance idea about this.
Full explanation are needed.
You can access the logged in user like this:
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
In django, the logged in user has an attribute is_authenticated which is a boolean value. If user is logged in, it gives True, else False.
Update
If you meant to see the placement model values in template for current user, you need make some relations with the user to placement. So you need to update the placement model:
class placement(models.Model):
user = models.ForeignKey(User, null=True, default=None)
.... # rest of the fields
And save user info to placement in views:
class SomeCreateView(CreateView):
...
def form_valid(self, form):
form.instance.user = User.objects.get(id = self.request.user.id)
return super(SomeCreateView, self).form_valid(form)
and get placements of a user in view like this:
placements = placement.objects.filter(user=request.user)
I am trying to access extended field of User model in Django template but it doesn't work, there are my files:
models.py:
class Author(models.Model):
user = models.OneToOneField(User, related_name='user', on_delete=models.SET_NULL, null=True)
bio = models.TextField(
max_length=1400, help_text="Enter author biography.")
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
user_profile = Author(user=user, bio='my bio')
user_profile.save()
post_save.connect(create_profile, sender=User)
template:
{% extends "base_generic.html" %}
{% block title %}
<title>Author {{user}}</title>
{% endblock %}
{% block content %}
<h1>{{user}}</h1>
<h2>Bio:</h2>
<p>{{user.author.bio}}</p>
<div>
{%for item in user.author.blogs_set.all%}
<p>{{item.title}}</p>
<hr>
{%endfor%}
</div>
{% endblock %}
views:
class UserDetailView(generic.DetailView):
model = User
template_name = 'blogapp/user_detail.html'
I want to get access to the bio field through user.author.bio but nothing displays I have also tried user.bio is there any tricky way to get access to this field?
You set the related_name to:
class Author(models.Model):
user = models.OneToOneField(
User,
related_name='user',
on_delete=models.SET_NULL, null=True
)
But the related_name is the name to access the related Author from a User object (so the name of the relation in reverse). You thus should set it to author (or leave it blank), like:
class Author(models.Model):
user = models.OneToOneField(
User,
related_name='author',
on_delete=models.SET_NULL, null=True
)
By setting it to user, you could have accessed the Author object with user.user, but I strongly advise not to do this, since in the end, it will only result in code that is hard to understand. For Django it of course does not matter (given no two relations originating from User have the same name), but for programmers, it gives a wrong impression.
I have two models in Django that are related with a OneToOneField (PrinterProfile and PrinterAdress).
I am trying to do a form with PrinterProfileForm, but for some reason it does NOT pass the PrinterAddress fields into the form (it's not rendered by Django "magic" in the template).
What should I do so that my PrinterProfileForm include as well the fields from PrinterAddress (its related OneToOneField)?
Thanks a lot
class PrinterProfile(TimeStampedModel):
user = models.OneToOneField(User)
phone_number = models.CharField(max_length=120, null=False, blank=False)
additional_notes = models.TextField()
delivery = models.BooleanField(default=False)
pickup = models.BooleanField(default=True)
# The main address of the profile, it will be where are located all the printers.
class PrinterAddress(TimeStampedModel):
printer_profile = models.OneToOneField(PrinterProfile)
formatted_address = models.CharField(max_length=200, null=True)
latitude = models.DecimalField(max_digits=25, decimal_places=20) # NEED TO CHECK HERE THE PRECISION NEEDED.
longitude = models.DecimalField(max_digits=25, decimal_places=20) # NEED TO CHECK HERE THE PRECISION NEEDED.
point = models.PointField(srid=4326)
def __unicode__(self, ):
return self.user.username
class PrinterProfileForm(forms.ModelForm):
class Meta:
model = PrinterProfile
exclude = ['user']
You have to create second form for PrinterAddress and handle both forms in you view:
if all((profile_form.is_valid(), address_form.is_valid())):
profile = profile_form.save()
address = address_form.save(commit=False)
address.printer_profile = profile
address.save()
Of course in the template you need to show both forms under one <form> tag :-)
<form action="" method="post">
{% csrf_token %}
{{ profile_form }}
{{ address_form }}
</form>
Complementing the accepted answer:
If you have custom clean methods, you need to add a try/except case. For the example presented if address had a clean() method to validate something you needed to change it to:
def clean(self):
try:
printer_profile = self.printer_profile
except ObjectDoesNotExist:
pass
else:
...code to validate address...