Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with Instagram API. How to fix the encoding error?
Good morning, I'm trying to connect Instagram API with Django. I'm getting Instagram code and give this code to function response(). def response(request): if 'code' in request.GET: url = 'https://api.instagram.com/oauth/access_token' values = { 'client_id':'SOME_ID', 'client_secret':'SOME_SECRET', 'redirect_uri':'SOME_URL', 'code':request.GET.get('code'), 'grant_type':'authorization_code' } data = urllib.parse.urlencode(values) bin_data = data.encode('utf-8') req = urllib.request.Request(url, data=bin_data) response = urllib.request.urlopen(req) response_string = response.read() insta_data = json.loads(response_string) if 'access_token' in insta_data and 'user' in insta_data: #authentication success print('True') else: #authentication failure after step 2 print('False 2') elif 'error' in request.GET: #authentication failure after step 1 print('False 1') But I'm get TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str. What I'm doing wrong? Why when I encode to 'utf-8' or 'ascii' nothing happens? -
MultiValueDictKeyError at /add
Each time I add Project with Expense Category. It's displaying error in the browser Error Image MultiValueDictKeyError at /add 'categoriesString' Although the Project is getting saved in the database! Please help me to figure it out! -
DJANGO // How do I create an input field that only the users can see and not the admin? //
Currently I'm creating a website using Django. The purpose of my website involves storing personal information to the user. For user privacy and security sakes. I'm trying to make it so that I (The Admin) can't see what they have put in the Text or CharFields that gets displayed on their own personal homepage in order to make the user feel more comfortable putting their info on site. I have tried encrypting it just like a password kind of like so: password = forms.CharField(widget=forms.PasswordInput()) but it wouldn't let me or the user add anything to the form. Plus the old fields were shown as encrypted to the user. The way I want it is so that it looks encrypted to me on my admin page but to the user's page it should be normal text. So my one question is how would I be able to accomplish this feat? Thanks in Advance. -
Django tutorial error par3
First sorry I don't speak english very well I can speak a little I have a problem I am currently working on Django tutorial I want to take in my browser at /polls/34/ but I can't If I enter that into the browser it will refuse from localhost Please help me Look at the codes I have mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] mysite/polls/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/polls/views.py from django.http import HttpResponse def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) -
Extending django user(AbstractEmailUser) model
I have the extended user model like below.. class User(AbstractEmailUser): first_name = models.CharField(verbose_name=_('First name'),max_length=128) last_name = models.CharField(verbose_name=_('Last name'), max_length=128) avatar = StdImageField(upload_to='user_avatars/', null=True, blank=True, variations={ 'thumbnail': (settings.AVATAR_THUMBNAIL_WIDTH, settings.AVATAR_THUMBNAIL_HEIGHT, True) }) user_name = models.CharField(null=True,blank=True,verbose_name=_('User id'), max_length=128) def get_short_name(self): return self.last_name def get_full_name(self): return "%s %s" % (self.first_name, self.last_name) def __unicode__(self): return self.email def get_thumbnail_url(self): return self.avatar.thumbnail.url if self.avatar else None I want to authenticate all users other than admin using email field and the admin by user_name field in extended user model.....I am using django 1.9 Is there any default way to do this... -
Template rendering (Django):
Following is the context that contains these two variables, and is being sent for rendering through views.py in my django application: {"all":[{"a":1, "b":2},{"a":3, "b":4}], "columns": ["a", "b"]} code inside template rendering <table> <thead> <tr> {% for c in columns %} <td> {{ c }} </td> {% endfor %} </tr> </thead> {% for a in all %} <tr> {% for c in columns %} <td>{{ a.c }}</td> {% endfor %} </tr> {% endfor %} </table> Problem: I am basically trying to render table rows in Django using the above code. But, even after the data is present, the data is not displayed in the table. Am I correctly accessing the data by writing a.c . If no then, what is the correct code to get the desired output? -
DRF: callable in serializer choicefield
Although django supports callables for the model choices field, I can't find that django rest framework does. My choices in this case are kept in a separate db (which changes between production and dev, so I can't keep this info on the model). Currently, I can't run tests (pytest: Failed: Database access not allowed) because the separate db is being queried on import by the web app serializers.py on instantiation (you cannot mark imported db with the django_db mark). Can anyone suggest a workable solution here? plot_source_positions = serializers.ChoiceField( choices=get_available_data_sets(), <---- not happy allow_blank=True, allow_null=False, required=False) def get_available_data_sets(): return get_service_inputs() . <--- makes a call to cache table -
Stuck for hours on this. You may need to add 'maginate.net' to ALLOWED_HOSTS
I know this question is very similar to others but I read all of them and still have not found a solution. I registered maginate.net with Google Domains so the domain is active. When entering that domain it gives a DisallowedHost Exception. It says to put the domain name in ALLOWED_HOSTS, which I did, in the local_settings.py. And when I put the IP address 206.189.179.58, the website runs perfectly. In my ALLOWED_HOST is a list: ALLOWED_HOSTS = ['206.189.179.58', 'maginate.net', 'www.maginate.net'] And yes I have restarted the server many times. I don't know if my settings.py has anything to do with this, but leaving the ALLOWED_HOSTS blank or not still gives the error. I'm also following this tutorial and doing exactly what it says. -
how can i synchronize the django celery task?
I have two celery task @app.task(bind=True) def task1(): @app.task(bind=True) def task2(): and each task is called by a different api like following @api_view(['POST']) @permission_classes((IsAuthenticated,)) def api1(request): task_1.delay() @api_view(['POST']) @permission_classes((IsAuthenticated,)) def api2(request): task_2.delay() if task2 is called when task1 is running in the background, I want to run task2 after task1 is finished how can i solved the problem?? I'm also considering giving one queue for each user Please give me a perfect solution... -
Call class method from another class in django
I'm building an e-commerce project in Django. I'm using an API from a third party in order to process payments, and every time the payment status changes I receive a notification which changes purchase status. That part is done OK, but there's another thing: the objects being sold are not the purchase objects, but they are contained in it. So when the status shifts to paid, I want to give the user permission to view the content of the purchase object the user has just bought (say, a course). To do so, I'm using django_guardian. class Course(models.Model): title = models.CharField("Título", max_length=140, null=False) description = RichTextUploadingField("Descrição", null=False) ... # give user permission to see the course's content def allow(self, user): assign_perm("view_content", user, self) When I call that method from a function in views.py it works fine. Now, what I actually need is to able to call it from a Manager, which is in a managers.py file. def update_purchase_status(self, transaction): ... user = purchase.user purchase.status = status_map[transaction['status']] purchase_items = [item.course for item in purchase.cart.cart_items.all()] for item in purchase_items: ... elif purchase.status == ("paid" or "available" or "disputed"): item.allow(user) As I said, updating the status works just fine. What doesn't work is the … -
How to redirect to pervious page in django?
Actually i'm new to Django i want redirect to previous page . here i have mentioned my Views.py , html So please tell me how to do that? Views.py def UpdateProducts(request,id): if request.method == 'POST': form = ProductsForm(request.POST, request.FILES) if form.is_valid(): data = Product.objects.get(pk=id) form = ProductsForm(request.POST,request.FILES, instance=data) form.save() messages.success(request, "Updation Success!") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.success(request, "You missed to fill some fields!") return reverse('UpdateProducts.html', kwargs={'pk':int(id)}) Html {% if id %} <form action = "/UpdateProducts/{{id}}" method="post" enctype="multipart/form-data"> {% else %} <form action="/ProductsSave/" method="post" enctype="multipart/form-data"> {% endif %} -
Prompt to activate user's account and redirect him to another page
I write a control function activate to confirm the User's email and his activating code. def activate(request, a_code): """ Activate User's Account by code from his email. """ try: user = User.objects.get(activatecode__code=a_code) user.is_active = True context = {} return render(request, "user/success.html", context) time.sleep(5) return redirect("/") except DoesNotExist: context = {} return render(request, "user/failure.html", context) After the User successfully activate his account, he will be redirected to the homepage. Nevertheless, double returns did not work properly as I intended. How to deal with such a context? -
Convert the Django traceback message to other language
I use the Django as my backend, when I register the user, there return the error message, that is:"A user with that username already exists". But how can I convert it to other language? if I use Korean or Spanish? -
React Redux Simple GET Api Call
I have a react app that will use redux to store certain global state info, like user auth token for Django Rest Framework, and info on the current page. But I'm having trouble figuring out exactly how to get it started. Currently I have the component I need connected to redux, and when it mounts it makes the API call to get information as so... componentDidMount() { axios .get("http://localhost:8000/api/spells/1") .then(response => { console.log('[API]:\t', response); let fields = response.data; let spell = Object.assign({}, this.state.spell); spell.Name = fields.Name; spell.School = fields.School; spell.Subschool = fields.Subschool; this.setState({ spell }); }) .catch(function(error) { console.error('[API]\t', error); }); } I'm more confused as to where I should be putting my API call and how I should be doing it. All tutorials Im reading online don't help much and they're all using the same example. So how should I go about loading a model's info via API with actions/reducers/etc? so that it updates the redux store which has the basic form { other: info, spell: { Name: 'sdfs', School: 'sdfs', Subschool: 'sdfs', } } -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' when running python manage.py migrate
I am taking a tutorial on Udemy and I came across this error when running python manage.py migrate The error is: TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' Here is my code: from django.conf import settings from django.db import models # Create your models here. class Tweet(models.Model): # user user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=140) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.content) This error was created as soon as I added the users. Thanks in advanced! -
How can I change a CSS class from a div after submit to a CreatView in Django?
I have a hidden div in my home page wich tells a "Success message" if the user register a player correctly. Something like this: <div id="success-message" class="alert alert-success margin-top-tiny" role="alert"> <h4 class="alert-heading">Usuário cadastrado com sucesso!</h4> <p>Informações sobre o torneio serão enviadas para o seu email de cadastro.</p> </div> The "success-message" div is initially hidden in my home page. If, for example, the user wants to create a new player he has to go to the registration page. If the registration is done successfully it will be redirected to the home page again and I would like this "success-message" div to be displayed. How can I do that? Here's my simple CreateView and form: #views.py class CreatePlayerView(CreateView): form_class = PlayerForm template_name = 'hotsite/create_player.html' #forms.py class PlayerForm(forms.ModelForm): class Meta: model = Player fields = [ 'name', 'email', 'robot_name', 'contributor' ] labels = { 'name': 'Nome', 'robot_name': 'Nome do robô', } widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'robot_name': forms.TextInput(attrs={'class': 'form-control'}), } -
"user = authenticate(request, username=username, password=password)" user is none
def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } print("User logged in") #print(request.user.is_authenticated()) if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) print(user) print(request.user.is_authenticated()) if user is not None: print(request.user.is_authenticated()) login(request, user) # Redirect to a success page. context['form'] = LoginForm() return redirect("/") else: # Return an 'invalid login' error message. print("Error") return render(request, "auth/login.html", context) Hello, I have started playing around in Django, but in a tutorial, when a tutor clicks submit, it authenticates the user ... I found almost the same problem on stack overflow already, but problem is, that a guy had a string instead of variables ( username = 'username' ) but problem is that when I click submit I get an error : User logged in {'username': 'test123', 'password': 'test'} None False Error User logged in is just a string in print() None <- print(user) False <- print(request.user.is_authenticated()) Error <- else: print("Error") I am struggling for an hours with this problem ( we have the same version of Django ) Django==1.11.4 -
Adding django-star-ratings to Django Models What do I add in the fields
I am new to Django so please forgive any errors in Logic or code. Intro: I am working on a project where. Users can sell a Activity. Example "Candle-Making" They will write a Post on the details of the Activity have images explaining everything you need, to do the activity. They also have the ability to sell "in-person" courses, which other users can take and after they have taken the courses they can rate the course. I have a groups models example: outdoor, fitness, music Users can post their posts in any of the groups depending on the kind of activity. My Questions: How do I make this rating system I am trying to implement the https://github.com/wildfish/django-star-ratings Is my approach correct, I have a app called post: post.models.py 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) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post model has other fields like images, likes, etc, which I have omitted in my code above for simplicity I then made another app called alumni which is supposed to track which course is taken by the user. Below is the alumni.models.py class Alumni(models.Model): user = models.ForeignKey(User, related_name='student') post = models.ForeignKey(Post, … -
Python Machine learning Web Api
Hi I would like to do a machine learning hello world, e.g. the Iris data set. I would then like to create a web API (RESTful service) to allow a HTTP Post request to send over (petal_length, sepal_length) and get back the prediction on the type of Iris. I intend to use Scikit learn but what should I use to make a web API? what do people normally use to make a ML Web API? Django, I know about this for making websites but I am not sure if it is used for web APIs. http://www.django-rest-framework.org/ Flask, I have also heard about this one but never used it before. http://flask.pocoo.org/ I would like to write unit tests and integration tests. It will also need to use authentication to ensure users have access. Currently my Web API for authenticating users is an ASP.Net Core Web Api and I use JWT. -
django validation error does not work
I have validation controls which used to work in django 1.11.1 , after upgrading to 1.11.4 and to 1.11.13 , raise forms.validationerror command is not raised and system directly goes to form is not valid section in views. Do we have to make controls and messaging in form is not valid session of views. Am i doing smth wrong, system used to work normally in previous version. How can we solve that... class DenetimForm(forms.Form): pk_no = forms.IntegerField(required=False, widget=forms.HiddenInput()) denetim_adi = forms.CharField(widget=forms.TextInput(attrs={'class':'special', 'size': '50'})) proje = forms.ModelChoiceField(queryset=proje.objects.all(), widget=autocomplete.ModelSelect2(url='proje-autocomplete'), required=False) rutin_planli = forms.ChoiceField(choices=RUTINPLANLI, widget=forms.RadioSelect, label="Planlı/Rutin") rp_hidden = forms.CharField(max_length=1, widget=forms.HiddenInput()) denetci = forms.ModelChoiceField(queryset=Profile.objects.filter(denetci="E"), widget=autocomplete.ModelSelect2(url='denetci-autocomplete'), required=False) tipi = forms.ModelChoiceField(queryset=tipi.objects.all(), widget=autocomplete.ModelSelect2(url='tipi-autocomplete'), required=False) takipciler = forms.ModelMultipleChoiceField(queryset=User.objects.all(), label='Takipçiler', widget=autocomplete.ModelSelect2Multiple(url='takipci-autocomplete'), required=False) hedef_baslangic = forms.DateField(label='Hedef başlangıç...:', required=False, widget=forms.TextInput(attrs={ 'class':'datepicker' })) hedef_bitis = forms.DateField(label='Hedef bitiş...:', required=False, widget=forms.TextInput(attrs={ 'class':'datepicker' })) aciklama = forms.CharField(label='Açıklama', widget=forms.Textarea(attrs={'cols': 50, 'rows': 8}), required=False) #zonlar = forms.ModelMultipleChoiceField(queryset=zon.objects.all(), label='Zonlar............:', # widget=autocomplete.ModelSelect2Multiple(url='zon-autocomplete', forward=['tipi'] ), required=False) bolum = forms.ModelMultipleChoiceField(queryset=bolum.objects.all(), label='Bölümler...............:', widget=autocomplete.ModelSelect2Multiple(url='bolum-autocomplete', forward=['tipi'] ), required=False) detay = forms.ModelMultipleChoiceField(queryset=detay.objects.all(), label=None, widget=forms.CheckboxSelectMultiple(attrs={"checked":""}), required=False) def __init__(self, *args, **kwargs): bolum_listesi = kwargs.pop("bolum_listesi") #init_param = kwargs.pop("init_param") #detaylar = kwargs.pop("detaylar") super(DenetimForm, self).__init__(*args, **kwargs) print("init içinden seçilen bölüm listesi", bolum_listesi) #print("init param...", init_param) #print("init içinden detaylar....", detaylar) qs = detay.objects.none() if not (bolum_listesi == None): i = 0 … -
python django ajax : ValueError: The view khobor.views.show_recommendation didn't return an HttpResponse object. It returned None instead
I know such questions exist gallore in SO. But none satisfies my problem. My code however works in localhost in my PC but not in online server. The site is here. You can go to the English tab and click a news headline to see the ajax request. It is a simple ajax request from the template to the view.py file through a URL defined in the urls.py file. The url (i.e. show_recommendation) is defined in the following way : from django.contrib import admin #from django.urls import path from django.conf.urls import url from khobor import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^find_feed/', views.find_feed, name="find_feed"), url(r'^show_articles/', views.show_articles, name="show_articles"), url(r'^clear_cookie/', views.clear_cookie, name="clear_cookie"), url(r'^show_recommendation', views.show_recommendation, name="show_recommendation"), ] JavaScript code in template is as follows: $.ajax({ url:"/show_recommendation/", method:"POST", dataType: 'JSON', data:{ id_found:id_found, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function (data) { //data=$.parseJSON(data); alert(data); if(window.console){ console.log(" response data = "); console.log(data); } if($.isArray(data)){ for(i=0; i<data.length; i++){ var id_found=data[i][0]; if(window.console){ console.log(" id found = "+id_found+" id found result = "+jQuery.inArray(id_found, ids_all)); } if(jQuery.inArray(id_found, ids_all) ==-1){ ids_all.push(id_found); new_ids.push(id_found); if(window.console){ console.log(" id pushed = "+id_found); } //$("#recommendations").append('<li>'+data[i][0]+' ... '+data[i][1]+'</li>'); $("#recommendations").append('<li class="article_indiv inline_block">' + '<span class="top_image inline_block" data-id="'+data[i][0]+'" ><img src="'+data[i][4]+'" alt="image"/>'+ '</span>' + '<a class="link" data-id="'+data[i][0]+'" target="_blank" … -
Apps aren't loaded yet when trying to import model in a a celery task files
Hello Awesome People! I bet my question is not awesome at all, but I'm pretty sure one of you can help me out. Before any explanations, here is the tree of my project | projectname |____|__init__.py |____|celery.py |____|settings.py |____|urls.py |____|wsgi.py |app1 |app2 Here's my celery.py from celery import Celery from celery import shared_task os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') app = Celery('projectname') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() from app1.models import * @share_task def tasks(): ''' ''' Every time I try importing models to the celery.py file with this line from app1.models import * I got: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. And the local server stops working all of a sudden. This post is related to a similar problem, but not sure it's the case here. What I want is to import some models to the file, so I can use them for some queries. I got a little clue about what can be wrong, but not sure. views import stuff from models.py views import stuff from celery.py like the task to be executed and celery.py tries to import stuff from models. So that circle like a snake that bites its own tail is weird to me. Any hint will be appreciated -
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I've created a custom user model in Django and everything went fine but when I try to create a new user it gives me an error here are my files : first that my models.py where I created the user table class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name and here is the forms.py where I created the signup form : class SignUpForm(UserCreationForm): email = forms.CharField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ') name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع') password1 = forms.CharField(widget=forms.PasswordInput, help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك') password2 = forms.CharField(widget=forms.PasswordInput, help_text='تأكيد كلمة المرور - … -
Django filter the model on ManyToMany count with a limit specific to each object?
Django filter the model on ManyToMany count? My question is very similar to the above one, but with a difference: there's a limit to the many-to-many relationship inside the model. So instead of being class Party(models.Model): organiser = models.ForeignKey() participants = models.ManyToManyField('auth.User', related_name="participants") It would be class Party(models.Model): organiser = models.ForeignKey() max_participants = models.PositiveIntegerField() participants = models.ManyToManyField('auth.User', related_name="participants") So I want to find all Party objects in which the count of participants is less than Party.max_participants. How can I make that query using Django's ORM? -
Django: Add birthday to a user profile
I am new to Django. I've been looking for an solution for my problem but i was not able to find anything that fixed the Problem. I have a Register view for new users. Here the new user enters his E-Mail-address and Password (each twice), his first and his last name and his Birthday. Everything is working fine (it saves email address, Password and names), but I am not able to save his birthday with this form. I can add the date when logged in in /admin and there the date is saved. Thanks for your help! forms.py: class UserRegisterForm(forms.ModelForm): username=forms.EmailField(label='Email address') email=forms.EmailField(label='Confirm Email') password=forms.CharField(widget=forms.PasswordInput) password2=forms.CharField(widget=forms.PasswordInput) first_name=forms.CharField(label='First Name') last_name=forms.CharField(label='Last Name') birthday=forms.DateField(label='Birthday') class Meta: model=User fields=[ 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birthday', ] def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") email=self.cleaned_data.get("email") password=self.cleaned_data.get("password") password2=self.cleaned_data.get("password2") username=self.cleaned_data.get("username") birthday=self.cleaned_data.get("birthday") if username!=email: raise forms.ValidationError("Emails must match") email_qs=User.objects.filter(username=username) if email_qs.exists(): raise forms.ValidationError("This Email has already been registered") if password!=password2: raise forms.ValidationError("Passwords must match") return super(UserRegisterForm,self).clean(*args,**kwargs) models.py: class UserTest(models.Model): username=models.OneToOneField(User, on_delete=models.CASCADE) email=models.EmailField(User) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) birthday=models.DateField(auto_now=False, null=True, blank=True) def __str__(self): return self.username.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile=UserTest.objects.create(username=kwargs['instance']) post_save.connect(create_profile,sender=User) views.py def register_user_view(request): title="Register User" form=UserRegisterForm(request.POST or None) if form.is_valid(): user=form.save(commit=False) password=form.cleaned_data.get('password') birthday=form.cleaned_data.get('birthday') user.save(password) user.set_password(password) user.save() new_user=authenticate(username=user.username,password=password) login(request,user) return redirect("/register/done") context={ "form":form, "title":title …