Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework different format response format for same URL and HTTP method
I working on an application with uses Django Rest Framework to handle queries and I use django-rest-framework-datatables plugin to help me handle pagination to datatables. Works fine, but when I request for a single register it keeps bringing me a json format for datatables, like this: { "count": 1, "next": null, "previous": null, "results": [{ "id": 1, "name": "University of Passo Fundo", "country": "Brazil" }] } This is not a big issue, but I would prefer to receive just the result field. How can I defined two different response format for a same URL and same method, just checking request parameters in django rest framework? Follow my code: urls.py router = routers.DefaultRouter() router.register(r'institution', InstitutionViewSet, base_name='Institution') urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), # api path('api/', include(router.urls)), # views url(r'^$', Home.as_view(), name='index'), url(r'institution/', Institution.as_view(), name='institution'), ] serializer.py class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = '__all__' datatables_always_serialize = ('id', 'name', 'country') models.py class Institution(models.Model): id = models.AutoField(db_column='id', primary_key=True) name = models.CharField(db_column='name', max_length=255, null=False) country = models.CharField(db_column='country', max_length=255, null=False) class Meta: db_table = 'Institution' managed = True verbose_name = 'Institutions' verbose_name_plural = 'Institutions' ordering = ['id'] def __str__(self): return self.name views.py class InstitutionViewSet(viewsets.ModelViewSet): serializer_class = InstitutionSerializer def get_queryset(self): if 'type' in … -
django keeps creating new migrations even when model has not changed
The following is my model: class Biovariable(models.Model): bioid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200) description = models.CharField(max_length=2000) units = models.ForeignKey(unit, on_delete=models.CASCADE) def __str__(self): return self.name class Biovariable_data(models.Model): biovar = models.ForeignKey(Biovariable, on_delete=models.CASCADE) value = models.CharField(max_length=2000) evdate = models.CharField(max_length=30) evtime = models.CharField(max_length=30) linkedcustomer = models.ForeignKey(customer, on_delete=models.CASCADE) linkeddoctor = models.ForeignKey(doctor, on_delete=models.CASCADE) linkedclinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) class Meta: unique_together = [ "biovar", "value", "evdate", "evtime", "linkedcustomer", "linkeddoctor", "linkedclinic" ] Each time I run makemigrations, django keeps creating new migrations, and I cant understand why. joel@hp:~/myappointments$ ./manage.py makemigrations Migrations for 'appointments': appointments/migrations/0010_auto_20190310_2138.py - Add field dob to customer - Alter field biovar on biovariable_data joel@hp:~/myappointments$ ./manage.py migrate Operations to perform: Apply all migrations: admin, appointments, auth, clinic, contenttypes, sessions Running migrations: Applying appointments.0010_auto_20190310_2138... OK joel@hp:~/myappointments$ ./manage.py makemigrations Migrations for 'appointments': appointments/migrations/0011_auto_20190310_2139.py - Alter field biovar on biovariable_data joel@hp:~/myappointments$ ./manage.py makemigrations Migrations for 'appointments': appointments/migrations/0012_auto_20190310_2139.py - Alter field biovar on biovariable_data joel@hp:~/myappointments$ ./manage.py migrate Operations to perform: Apply all migrations: admin, appointments, auth, clinic, contenttypes, sessions Running migrations: Applying appointments.0011_auto_20190310_2139... OK Applying appointments.0012_auto_20190310_2139... OK joel@hp:~/myappointments$ ./manage.py makemigrations Migrations for 'appointments': appointments/migrations/0013_auto_20190310_2140.py - Alter field biovar on biovariable_data joel@hp:~/myappointments$ -
How to setup mutagen for Django?
I am planning to verify all the uploaded music files using mutagen. Can someone explain how to set it up so that when i import mutagen in my forms.py, it wouldn't show errors. PS: i am a noob -
Python - "client_id" is missing. How to solve?
I've been playing with the LinkedIn api (OAuth 2) and I've found an example to help test it. I've followed the tutorial to the letter, but for some reason when I provide my full redirect URL (as requested in the code), I get the error: (invalid_request) A required parameter "client_id" is missing. I'm not sure what I'm doing wrong, but if anyone has any idea, I appreciate the feedback. Upon searching for a solution, I've found another person struggling with this: "client_id" is missing when authenticate with LinkedIn Here's the code from the example: Linkedin.py from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import linkedin_compliance_fix # Credentials you get from registering a new application client_id = SECRET client_secret = SECRET # OAuth endpoints given in the LinkedIn API documentation authorization_base_url = 'https://www.linkedin.com/uas/oauth2/authorization' token_url = 'https://www.linkedin.com/uas/oauth2/accessToken' linkedin = OAuth2Session(client_id, redirect_uri='http://localhost:8000') linkedin = linkedin_compliance_fix(linkedin) # Redirect user to LinkedIn for authorization authorization_url, state = linkedin.authorization_url(authorization_base_url) print ('Please go here and authorize,', authorization_url) # Get the authorization verifier code from the callback url redirect_response = input('Paste the full redirect URL here:') # Fetch the access token linkedin.fetch_token(token_url, client_secret=client_secret,authorization_response=redirect_response) # Fetch a protected resource, i.e. user profile r = linkedin.get('https://api.linkedin.com/v1/people/~') print (r.content) Link to example: https://requests-oauthlib.readthedocs.io/en/latest/examples/linkedin.html … -
how to pass primary key value from JsonResponse to dynamic url in Django?
I face the problem to pass primary key value to the dynamic url using Ajax in Django. Thanks for any helps... below is the JS code for click button's function: $(function () { $(".js-create-book").click(function () { $.ajax({ url: '/supplier/**<int:pk>**/new/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); }); the views.py got the function new_stok() as follows: def new_stok(request, pk): supplier = get_object_or_404(Supplier, pk=pk) form = NewStokForm() context = {'pk': supplier.pk, 'form': form} html_form = render_to_string('includes/partial_stok_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) -
How to check user have permission or not on url in django
How to check user have permission or not on URL in Django I have URL - admin/users/userprofile and I want to check that login user have permission to access how to do that ? def get_nav_list(context, **kwargs): request = context['request'] app_list = admin.site.get_app_list(request) navigation = Navigation.objects.all() menus = [] menu_tree = {} for nav in navigation: if nav.parent_id is None: menus.append(nav.navigation_weight) menu_tree[nav.id] = {} menu_tree[nav.id]['parent'] = nav menu_tree[nav.id]['children'] = {} for nav in navigation: if nav.parent_id: #print(request.user) print(check_menu_permissions(nav.navigation_link , request.user , app_list )) if check_menu_permissions(nav.navigation_link , request.user , app_list): menu_tree[nav.parent_id]['children'][nav.id] = nav Note: I have build navigation Module like wordpress in django -
How to Fetch Data in ManyToMany Django And render in view.py
I want to fetch Data to my view.py where the buyer select a specific market. Which Means the Buyer can only see the Market he selects. class Market(models.Model): name = models.CharField(max_length=30) address = models.TextField("Market Address") interval = models.PositiveIntegerField("Market Day Interval", default=5) startdate = models.DateField("Initial Date", auto_now=False, auto_now_add=False) location = models.ForeignKey(Local, related_name='market_location', on_delete=models.CASCADE) desciption = models.TextField("Good Description") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) market = models.ManyToManyField(Market, related_name='interested_markets') status = models.BooleanField("User Status", default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username view.py @login_required @buyer_required def welcome_buyer(request): buyer = request.user.buyer market = buyer.interested_markets.all() return render(request, 'buyer/home.html', { 'market': market }) -
Django - Modelform - pre-set one of the fields
How can you pre-define one of the fields in a ModelForm? When creating a ModelForm, you can choose which fields to display in your browser. Though, I would like to preset one of them. thanks to all ! -
How to create an interface with for blog post with options,bold/ italic in django blog
am creating a blog using django and in between i found that my blog posts aren't arranged properly like no paragraphs,links,an option to add in between images and just every thing is random. i would to know if there is way of cleaning the post by making it to have paragraphs or headings like the interface in the picture. enter image description here -
Passing user input into a query set
I'm trying to create a delete function for my model/database however I would like the user to be able to enter the id of the row they would like to delete. To do so I created a new form class DeleteForm(forms.Form): enter_id = forms.IntegerField(min_value=1) Is it possible to pass this user input into a view function without having to store the data? def delete(request): form = DeleteForm(request.POST) if form_del.is_valid(): object_id = form_del.cleaned_data['enter_id'] model.objects.filter(id=object_id).delete() -
Put request.user.email inside another model field
I try to get user email from user model and put it in a field on another model the code is working and the counter count perfect but the add line not this is the code: models.py class Posts(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(blank=True, max_length=100) slug = models.SlugField(null=True, blank=True) contain = models.TextField(blank=True) post_image = models.ImageField(upload_to="post_img", default='post_img/humanity.jpg') post_published = models.DateTimeField(blank=True, auto_now_add=True) post_updated = models.DateTimeField(blank=True, auto_now=True) post_deleted = models.BooleanField(default=False) post_approved = models.BooleanField(default=False) post_sponsored = models.CharField(max_length=100, null=True, blank=True, default = None) post_sponsored_accepted = models.BooleanField(default=False) def save(self, *args, **kwargs): if not self.slug: self.slug= slugify(self.title) super(Posts, self).save(*args, **kwargs) def __str__(self): return f'Author: {self.author}, Title:{self.title}, Posted: {self.post_published}' views.py def post_check(request, pk): pos = Posts.objects.get(pk=pk) u = UserProfile.objects.get(user=request.user) if u.sp_counter < 3: pos.post_sponsored = request.user.email u.sp_counter += 1 u.save() messages.success(request, 'طلبك قيد المراجعة، الرجاء انتظار الموافقة') return redirect('index') else: messages.warning(request, 'وصلت الحد الاقصى للكفالات') return redirect('index') -
how to execute mysql query with LIKE statement in Django
I am trying to search in my mysql database with LIKE statement : indexstr = request.GET['index'] indexstr = '%' + indexstr + '%' offset = int(request.GET['offset']) for row_data in advertisement.objects.raw( 'select * from requests_advertisement WHERE short_description LIKE ' + indexstr + ' LIMIT 10 OFFSET ' + str(offset*5)): but it has this error : error image it seems that , it cannot work with % character , when I remove % it works correctly -
Django URL namespace 'admin' isn't unique. for endpoints with and without slash
I am getting this warning and I would like to get rid of it... My urls.py urlpatterns = [ path('admin/', admin.site.urls), path('admin', admin.site.urls), re_path(r'^(?P<Model>[A-Za-z]+)', GenericViewSet.as_view({'get': 'list', 'post': 'create'}), ) ] What I want to achieve is a request to /admin and /admin/ to fall to the admin site and any other request will be passed to my generic model handling API. Th problem is that without path('admin/', admin.site.urls), a request to /admin/ falls to the model endpoint. Which it probably should not... This is probably the real problem. So I have to specify both admin and admin/ path, to make requests to both /admin and /admin/ fall to the admin site and that is causing the warning to appear. Can I somehow go around this? (Without changing my desired url paths...) -
Django making multiple objects and calling them
So with my project users can create object called for example "money". What i'm now trying to do is for that same user who created "money" to attach objects with integer values. I have no problem with input but not sure how to create those objects and call all of the values user has created for the "money" object. Models for the "money" and values: class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): return self.name class Meta: unique_together = ['name', 'user'] class DataItem(models.Model): data = models.IntegerField(default=0) list = models.ForeignKey(List, on_delete=models.CASCADE, related_name='data_items') The way im trying to create these objects at the moment is with a form like this. <form action="{% url 'addData' %}" method="POST" role="form"> {% csrf_token %} {{ add_data.num }} <button type="submit">Close</button> </form> url "addData" calls for view looking like this.. (it is not working view) @require_POST def addData(request): form_data = data_form(request.POST) if form_data.is_valid(): user = request.user.pk specific_list = List.objects.filter(user=user, name='squat') new_data = DataItem(data=request.POST['num'], list=specific_list) new_data.save() return redirect('/app/') I have tried many views for to get this work but no luck so far.. This particular version gives error "Cannot assign "]>": "DataItem.list" must be a "List" instance. I'm pretty new to django so bare … -
django digital ocean git
I have set up my python, virtualenv, django environment in my digital ocean Ubuntu droplet. I have also set up SSH access to be able to deploy using git. I have set a remote url, so to push I just use "git remote live master". I have used git webhooks to push remotely. Since I used git init --bare for my remote repo, I cannot see the source code, I just see the hooks folders, etc. The only issue is after pushing to the remote repository, how do I connect that repository to my django environment so that I can run it, access those source codes, so that I can do "python manage.py runserver"? I am a beginner to webhosting automatic deployment using git and django, I do appreciate your help. -
Django 2 Allauth email confirmation redirects to empty page
I'm trying to set up allauth and it's been challenging to say the least. My registration page works (although the username field refuses to appear on the form) and on submission, redirects a user to an empty page with a banner saying Check your email to confirm account The email says To confirm this is correct, go to http://localhost:8000/users/verify-email/Ng:1h2xx7:z9x0t0wmvAhicak5twI_QtVWNYo When I click on the link, the page is empty (although still styled by my base.html, there is no content.) I'm assuming it should be directing to the login page and showing a banner Account confirmed, you may now log in. Can someone please indicate to me why this is happening? Is there a views.py class for the page after email confirmation I should know about? urls.py from django.contrib.auth import views as auth_views from users import views as user_views from allauth.account.views import confirm_email urlpatterns = [ path('register', user_views.MySignupView.as_view(template_name='users/register.html'), name='register'), path('login', user_views.MyLoginView.as_view(template_name='users/login.html'), name='login'), path('verify-email/<str:key>', confirm_email, name='account_confirm_email'), views.py from allauth.account.views import SignupView, LoginView class MySignupView(SignupView): template_name = 'users/register.html' class MyLoginView(LoginView): template_name = 'users/login.html' forms.py class UserRegisterForm(forms.Form): email = forms.EmailField() first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserRegisterForm' ACCOUNT_EMAIL_REQUIRED = True … -
How to fix Django sitemap error 'str' object is not callable when using @cached_property
I'm trying to add sitemaps to my django site and I am facing problems, Here is the traceback: Internal Server Error: /sitemap.xml Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\views.py", line 16, in inner response = func(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\views.py", line 71, in sitemap protocol=req_protocol)) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\__init__.py", line 111, in get_urls urls = self._urls(page, protocol, domain) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\__init__.py", line 120, in _urls loc = "%s://%s%s" % (protocol, domain, self.__get('location', item)) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\__init__.py", line 68, in __get return attr(obj) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\sitemaps\__init__.py", line 75, in location return obj.get_absolute_url() TypeError: 'str' object is not callable This is happening because I have used @cached property on the method get_absolute_url() of the model that's being used for sitemaps. The method in model: @cached_property def get_absolute_url(self): return reverse('person', args=[self.slug]) In urls.py sitemaps = { 'people': GenericSitemap({ 'queryset': Person.objects.all() }, priority=0.4, changefreq='weekly'), } urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] When I remove cached_property, it does work properly but I don't want to remove the decorator because I think it help reduce caclulate the reverse … -
ValueError at /edit/3 The view main_panel.views.edit didn't return an HttpResponse object. It returned None instead
I'm having little problem.Need yours help. I'm trying to add edit button to my project and gives me error. This is my views.py: def edit(request, list_id): if request.method == 'POST': item = List.objects.get(pk=list_id) form = ListForm(request.POST or None, instance=item) if form.is_valid(): form.save() return redirect('home') else: item = List.objects.get(pk=list_id) return render(request, 'main_panel/edit.html', {'item': item}) This is my edit.html: {% extends 'main_panel/base.html' %} {% block content %} {% if item %} <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input type="search" value="{{ item.name }}" name="name"> <input type="search" value="{{ item.choice_field }}" name="choice_field"> <input type="search" value="{{ item.product }}" name="product"> <input type="search" value="{{ item.avans }}" name="avans"> <input type="search" value="{{ item.total_price }}" name="total_price"> <input type="search" value="{{ item.status }}" name="status"> <button type="submit">Kaydet</button> </form> {% endif %} {% endblock %} This is my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('add/', views.add, name='add'), path('delete/<list_id>', views.delete, name='delete'), path('edit/<list_id>', views.edit, name='edit') ] And it gives me this error: ValueError at /edit/3 The view main_panel.views.edit didn't return an HttpResponse object. It returned None instead. When i click submit button after i edit my data it gives me error. Thank you. -
Django crontab, running a job every 12 hours
I have a django crontab sceduled to run every 12 hours, meaning it should run twice per day however, it is running more than that. Can anyone tell me what's wront with it ? ('* */12 * * *', 'some_method','>>'+os.path.join(BASE_DIR,'log/mail.log')) Also what changes I need to make if I need it to run every 24 hours? -
Create separate models/tables that are subset of base model
I have a Transaction model that contains the list of all transactions from my bank account. I want to create "sub" models that are just different categories of transactions. For instance, an Income model that just contains the deposits or a Bill model that contains the transactions that are from bills. The closest I could find were proxy models but either they are too complex for me to understand or I'm totally wrong anyway. class Transaction(models.Model): date = models.DateField(default=datetime.date.today) description = models.CharField(max_length=100) category = models.CharField(max_length=100) amount = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.description + ' ' + str(self.amount) class Income(Transaction): class Meta: proxy = True Is this possible? -
Adding a custom domain in PythonAnywhere does not work
I added my application to pythonanywhere, now I'm trying to add a custom domain but I can not get a positive result. My change I've added in pythonanywhere looks like this. Under my hidden field is my domain name. According to the documentation, I added a CNAME record (at my domain provider, it looks like this.). But after entering in the address www.ka ....pl I am not being redirected to my django application in pythonanywhere. This is my first time when i added my domain, how to fix this error (so that my application will appear after entering the domain), any help will be appreciated. -
Changing an image in Django formset puts it to the end of the list
Supposing I am making a "How to" Django webapp where users make posts about how to do different things like. "How to" make a rope "How to" make an earthen pot "How to" learn to ride a bike You get the idea. I have made the post create view for this. which is a singe post.Now when members make the post.They add additional images to the post Example: "How to" make a rope They have a main image on the post. A post title and post description. Now they have to show images step by step how the rope is made Image 1: Do this 1st Image 2: Do this 2nd I am using Django formsets along with my post model to achieve this. Everything is working absolutely fine. no problems The Problem The problem is when a user wants to switch image 2. from their post to a different image. for their personal reason. Even though they changed the 2nd image. That image now ends up at the very end of the list. Making the user to re-upload all the images. To bring back the Order. Making my app look buggy. Below are my models: class Post(models.Model): user = … -
Django 2fa registration form
I'm trying to make my own 2fa implementation for my project. I found this library. They have this example, i'm studying it in order to understand how it all works. I'm now running the example using py -3.7 manage.py runserver, but i'm having some trobules understanding the following: 1) I would like to add an email address to the registration form, where do i edit the form? I tried to open the views.py file but there is nothing there. 2) How do i edit the login form? I would like to add captcha to the form, but still, there is nothing in the views file -
Django-select2 filtering widget data by owner (Related user)
I'm using django-select2 with class based view (create, update, delete view) In CreateView, i'm use form_class in view with my form. In this form i'm use widgets for selecting related objects. And i need filtering these objents by created_user (owner). How can i pass current user in my scheme to widget ModelSelect2MultipleWidget class? forms.py: class AccountSearchFieldMixin(object): search_fields = [ 'login__icontains', 'password__icontains', 'phone__icontains', ] class AccountSelect2TagWidget(AccountSearchFieldMixin, ModelSelect2MultipleWidget): model = VkAccount queryset = VkAccount.objects.exclude(proxy__isnull=True) def create_value(self, value): self.get_queryset().create(name=value) class TaskVkInvitationsFriendsSearchForm(forms.ModelForm): # country = ModelChoiceField(Countries.objects.all(), empty_label=None, label='Страна')f class Meta: model = TaskVkInvitationsFriendsSearch exclude = ['type', 'date_creation', 'date_update', 'maintask', 'invited_friends'] widgets = { 'accounts': AccountSelect2TagWidget, 'cities': CitiesSelect2TagWidget, 'scheduler_data': forms.HiddenInput, # 'country': CountrySelect2TagWidget } def __init__(self, *args, **kwargs): self.owner = kwargs.pop('owner') super(TaskVkInvitationsFriendsSearchForm, self).__init__(*args, **kwargs) views.py: class BaseTaskMixin: model = TaskVkInvitationsFriendsSearch form_class = TaskVkInvitationsFriendsSearchForm success_url = reverse_lazy('vk_bot_tasks_list') template_name = 'vk_bot/create_task.html' class TaskCreateView(BaseTaskMixin, CreateView): def form_valid(self, form): model = form.save(commit=False) t = Task() t.save() model.maintask = t model.save() form.instance.owner = self.request.user return super(TaskCreateView, self).form_valid(form) -
I can not show the photo that is in the database
I am uploading the image to the database, in the folder static, media, the photo appears with its versions, media, large and thumbnail. But I can not call this image inside the perfil.html And inside django admin, I can not find this image either and if possible I would also like to know how to call more than one image to the perfil.html, since the user will be able to send more than one photo, as if it were a gallery views.py def gallery(request): gallery = Gallery.objects.all() form = GalleryForm() data = {'gallery': gallery, 'form': form} return render(request, 'gallery.html', data) def gallery_novo(request): if request.method == 'POST': form = GalleryForm(request.POST, request.FILES) if form.is_valid(): form.save(user=request.user) return redirect('sistema_perfil') else: form = GalleryForm return render(request, 'gallery.html', {'form': form}) def perfil(request): usuario = Usuario.objects.all() form = UsuarioForm() data = {'usuario': usuario, 'form': form} gallery = Gallery.objects.all() form2 = GalleryForm() data2 = {'gallery': gallery, 'form2': form2} return render(request, 'perfil.html', data, data2) models.py class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) email = models.EmailField(blank=False) foto = StdImageField( blank=False, variations={ 'large': (600, 400), 'thumbnail': (100, 100, True), 'medium': (300, 200), }) telefone = models.CharField(max_length=20, blank=False, verbose_name="Celular") cpf = models.CharField(max_length=19) …