Issues regarding form and view [duplicate] - python

I am new to Django and I want to make a user registration form in Django. While creating model, I gave a fieldtype->PasswordField() to password field but when I run this model into terminal I got a error
password=models.PasswordField()
AttributeError: 'module' object has no attribute 'PasswordField'
So I want to know that which field type is used for password in Django.I already refer to form doc but I found nothing.
so please help me

Theory
Use django.db.models.CharField, since this is an OK database column type for a password string
Use django.forms.PasswordWidget, to represent this field in a form, see overriding default form field widgets
Example
models.py:
from django.db import models
class YourModel(models.Model):
password = models.CharField(max_length=200)
forms.py:
from django import forms
from models import YourModel
class YourModelForm(forms.ModelForm):
class Meta:
widgets = {'password': forms.PasswordField}
model = YourModel

There is no PasswordField() in django. You can to use CharField() to store a password, but to show it as password input type in a html form you can specify a widget to it.
Example:
password = forms.CharField(widget=forms.PasswordInput())
More reference at :PasswordInput

Related

How to use UserCreationForm in Django?

I have followed this tutorial to test out the User authentication and Signals in Django. I don't know what I should do with this part (found from the first post of this tutorial):
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
birthdate = forms.DateField()
discord_id = forms.CharField(max_length=100, help_text='Discord ID')
zoom_id = forms.CharField(max_length=100, help_text='Zoom ID')
text = forms.TextField(null=True, blank=True)
class Meta:
model = User
fields = ["username", "password1", "password2", "birthdate", "email", "discord_id", "zoom_id"]
With those imports I get an error NameError: name 'forms' is not defined and if I add an import from django import forms I get errors like AttributeError: module 'django.forms' has no attribute 'TextField'.
Sohuld I add all the fields from my Model into this RegisterForm -class I want to include to the registration process? What do I do to the fields that are textFields in my Model?
Instead of using forms.TextField which does not exist in Django, you need to use forms.CharField(widget=forms.Textarea).
I think you are trying to use CharField instead of TextField. Django uses CharField in its forms with default widget as TextArea.
You can find more details here
https://docs.djangoproject.com/en/3.2/ref/forms/fields/#charfield

Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute

I have a model linked to Django User model but when I try saving to that model using User instance, it says 'User' object has no attribute 'mymodel_set'
My models.py:
from django.contrib.auth.models import User
from django.db import models
class MyModel(models.Model):
user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel')
name = models.CharField(max_length=14, blank=True, null=True)
My views.py:
from django.contrib.auth.models import User
from myapp.models import mymodel
def register(request):
#gets data here from template
user = User(username=reg_username, password=reg_password)
user.save()
user.mymodel_set.create(name= display_name)
return HttpResponse('Success')
If the related object existed, you would use mymodel, but it does not exist and the relationship is void, so it cannot be accessed via the user. Create it first and set the relationship to that user:
mymodel = MyModel.objects.create(name=display_name, user=user)
# ^^^^ set related user
The _set suffix is usually used for reverse ForeignKey relationships and not for OneToOne relationships.
Also note that the related_name on the user field was already specified as mymodel, and the related field can now be accessed from the User model via user.mymodel

what does exclude in the meta class of django mean?

I came across this code:
drinker/models.py:
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Drinker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
drinker/forms.py:
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Drinker
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another.")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The passwords did not match. Please try again.")
return self.cleaned_data
My Question is about the inner class meta which as two attributes:
model=Drinker
exclude=('user`,)
I have a not-so-clear understanding of how this meta class work. I have read the documentation but I am still confused. Can you kindly explain what those two lines mean and what their purpose is?
Thanks
The exclude attribute tells Django what fields from the model not to include in the form.
Quoting the Selecting fields to use section of the model form documentation:
2. Set the exclude attribute of the ModelForm’s inner Meta class to a list of fields to be excluded from the form.
The model line simply tells Django what model to take the fields from; together the two lines tell Django to give RegistrationForm fields based on all fields on the Drinker model, except 'user'. For the given Drinker model, that's birthday and name.
These fields are added to the other form fields already defined on the form. If the Drinker model gained more fields, those would automatically be part of the form too.
See the Overriding the default fields section of the same chapter:
When you explicitly instantiate a form field like this, it is important to understand how ModelForm and regular Form are related.
ModelForm is a regular Form which can automatically generate certain fields. The fields that are automatically generated depend on the content of the Meta class and on which fields have already been defined declaratively. Basically, ModelForm will only generate fields that are missing from the form, or in other words, fields that weren’t defined declaratively.
The inner Meta class is just a convenient way to create a namespace for such configuration on your form class for the Django framework to find. All Django now has to do is introspect Form.Meta and see what attributes are defined there.
Note that using exclude can lead to security problems. From the same documenation:
It is strongly recommended that you explicitly set all fields that should be edited in the form using the fields attribute. Failure to do so can easily lead to security problems when a form unexpectedly allows a user to set certain fields, especially when new fields are added to a model. Depending on how the form is rendered, the problem may not even be visible on the web page.
The alternative approach would be to include all fields automatically, or blacklist only some. This fundamental approach is known to be much less secure and has led to serious exploits on major websites (e.g. GitHub).
fields = exclude() and fields = '__all__' - means display all the fields
exclude = ('password',) - means exclude password field
fields = ('user','email',) - means display only email field and userfield
in short : fields you want to show up in the form should be mentioned in 'fields' attribute ex:
fields = '__all__' #will show all the fields from the model in the form
'exclude' does the opposite
exclude = ['title'] # don't show the title field

Issues regarding field types in Django

I am new to Django and I want to make a user registration form in Django. While creating model, I gave a fieldtype->PasswordField() to password field but when I run this model into terminal I got a error
password=models.PasswordField()
AttributeError: 'module' object has no attribute 'PasswordField'
So I want to know that which field type is used for password in Django.I already refer to form doc but I found nothing.
so please help me
Theory
Use django.db.models.CharField, since this is an OK database column type for a password string
Use django.forms.PasswordWidget, to represent this field in a form, see overriding default form field widgets
Example
models.py:
from django.db import models
class YourModel(models.Model):
password = models.CharField(max_length=200)
forms.py:
from django import forms
from models import YourModel
class YourModelForm(forms.ModelForm):
class Meta:
widgets = {'password': forms.PasswordField}
model = YourModel
There is no PasswordField() in django. You can to use CharField() to store a password, but to show it as password input type in a html form you can specify a widget to it.
Example:
password = forms.CharField(widget=forms.PasswordInput())
More reference at :PasswordInput

Making a CharField use a PasswordInput in the admin

I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this:
class TwitterUser(models.Model):
screen_name = models.CharField(max_length=100)
password = models.CharField(max_length=255)
def __unicode__(self):
return self.screen_name
I need the Admin site to display the password field as a password input, but can't seem to figure out how to do it. I have tried using a ModelAdmin class, a ModelAdmin with a ModelForm, but can't seem to figure out how to make django display that form as a password input...
From the docs, you can build your own form, something like this:
from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
class Meta:
model = TwitterUser
widgets = {
'password': PasswordInput(),
}
Or you can do it like this:
from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
password = forms.CharField(widget=PasswordInput())
class Meta:
model = TwitterUser
I've no idea which one is better - I slightly prefer the first one, since it means you'll still get any help_text and verbose_name from your model.
Regardless of which of those two approaches you take, you can then make the admin use your form like this (in your app's admin.py):
from django.contrib import admin
class TwitterUserAdmin(admin.ModelAdmin):
form = TwitterUserForm
admin.site.register(TwitterUser, TwitterUserAdmin)

Categories

Resources