Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two Models pointing to One Database Table - Redundant Code [Django 2.1]
I'm working on a Django project that have two models on different apps using the same tables on database. The City and State tables are used in both apps. I want to know which is the best way to apply DRY concepts and use only one model for the two apps access these tables. The two apps are on the project folder and each one has his own models.py with the folowing code for city/state: from django.db import models from django.contrib.auth.models import User,Group from django.db.models.signals import post_save from django.dispatch import receiver class state(models.Model): class Meta: db_table = '"db_property"."state"' created_at = models.DateTimeField(db_column='created_at') updated_at = models.DateTimeField(db_column='updated_at') name = models.CharField(db_column='name',max_length=50) class city(models.Model): class Meta: db_table = '"db_property"."city"' created_at = models.DateTimeField(db_column='created_at') updated_at = models.DateTimeField(db_column='updated_at') name = models.CharField(db_column='name',max_length=50) state = models.ForeignKey(state,on_delete=models.CASCADE) Thanks in advance! -
How to send an object with other variables back to the client using json serialize?
How to add dict a to response and how can I get two objects at the ajax? view def abc(request): cp = Cp.objects.get(id=1) cp = serializers.serialize('json', [cp,]) cp = json.loads(cp) a = {'a': 'a', 'b': 'b'} return HttpResponse(data) js $.ajax({ // success: function(data){ } }) -
DjangoRestFramework: AttributeError: 'str' object has no attribute '_meta'
I traced this error and found that serializer.data is causing the problem. I have used similar code in my other Django apps and they are running perfectly fine. models.py from django.db import models class Category(models.Model): name=models.CharField(max_length=30) def __str__(self): return self.name class Subcategory(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE) name=models.CharField(max_length=30) def __str__(self): return self.name class Products(models.Model): Subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE) name=models.CharField(max_length=30) def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Category,Subcategory,Products class CategorySerializer(serializers.ModelSerializer): class Meta: model='Category' fields='__all__' class SubcategorySerializer(serializers.ModelSerializer): class Meta: model='Subcategory' fields='__all__' class ProductsSerializer(serializers.ModelSerializer): class Meta: model='Products' fields='__all__' views.py def post(self,request): action=request.query_params['action'] if action=='add': category_name=request.query_params['category_name'] category=Category(name=category_name) category.save() serializer=CategorySerializer(Category.objects.filter(name=category),many=True) return JsonResponse({"category details":serializer.data}) I went through all the posts on StackOverflow based on this error but none of those could help me resolve it. -
Django trailing slash in page
I have a problem if i add " / " at the end of the url and then the page 404 not found path('<slug:slug>',post_detail,name="post_detail"), Or if i delete " / " in the url then the page 404 not found path('news/',post_index,name="post_index"), I want to work whether have slash or not. -
ImportError: cannot import name 'PostListView' from 'main.views'
hello guys I'm beginner in learning Django, I got this error when I try to import PostListView from .views this project urls: from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('/', include('main.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my app main urls: from . import views from django.urls import path from main.views import PostListView urlpatterns = [ path('', PostListView.as_view, name="blog"), path('about/', views.about, name='about'), ] and this is my views: from django.shortcuts import render from .models import Post from django.views.generic import ListView def blog(request): context = { 'posts': Post.objects.all() } return render(request=request, template_name='main/blog.html', context=context) class PostListViews(ListView): model = Post def about(request): return render(request=request, template_name='main/about.html') Thank you in advance :) -
How do I point my Django to my Vue files that are loaded via web pack?
I'm setting up a production server on digital ocean using Django and with MPA Vue. I load the Vue scripts and CSS via a webpack loader and it works fine locally. When I try to deploy it as production I get an error that I cannot 'get' the files of Vue I tried changing the webpack.config.js publicpath to the dir location and eventually changed it back to " " I tried changing the settings.py file's STATIC_URL and STATIC_ROOT to fit the dir's location of the Vue files myIp/:25 GET http://myIp/django_vue_mpa/static/vue/css/chunk-vendors.css net::ERR_ABORTED 404 (Not Found) myIp/:28 GET http://myIp/django_vue_mpa/static/vue/js/vue_app_01.js net::ERR_ABORTED 404 (Not Found) myIp/:27 GET http://myIp/django_vue_mpa/static/vue/css/vue_app_01.css net::ERR_ABORTED 404 (Not Found) myIp/:26 GET http://myIp/django_vue_mpa/static/vue/js/chunk-vendors.js net::ERR_ABORTED 404 (Not Found) myIp/:27 GET http://myIp/django_vue_mpa/static/vue/css/vue_app_01.css net::ERR_ABORTED 404 (Not Found) myIp/:28 GET http://myIp/dj ango_vue_mpa/static/vue/js/vue_app_01.js 404 (Not Found) -
How can i add a date/calender widget to django forms?
I tried following these links and this but it didn't work. the widget doesn't load in the form and the js files gives 404 error in the console while it's accessible from the link. I use crispy forms to render my form. forms.py DateInput = partial(forms.DateInput, {'class': 'datepicker'}) # patient Form class PatientForm(ModelForm): birth_date = forms.DateField(label='Birth Date',widget=DateInput()) class Meta: model = Patient exclude = ['user',] The Template <h2>Add Patient</h2> <form method="POST" action="{% url 'patients:patient_create' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary" >Add Patients</button> <p></p> </form> </div> {% endblock %} <script> $(document).ready(function() { $('.datepicker').datepicker(); }); </script> The links of js files + CSS <script src=”https://code.jquery.com/jquery-1.12.4.js”></script> <script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script> <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”> The errors in the console Not Found: /patients/”https://code.jquery.com/jquery-1.12.4.js” Not Found: /patients/”https://code.jquery.com/ui/1.12.1/jquery-ui.js” [18/Jul/2019 15:29:09] "GET /patients/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 6742 [18/Jul/2019 15:29:09] "GET /patients/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 6760 Not Found: /patients/”https://code.jquery.com/jquery-1.12.4.js” [18/Jul/2019 15:29:10] "GET /patients/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 6742 Not Found: /patients/”https://code.jquery.com/ui/1.12.1/jquery-ui.js” [18/Jul/2019 15:29:10] "GET /patients/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 6760 Not Found: /favicon.ico in my code i have many jquery versions can that cause the problem -
how to make dependent foreignkey in model admin (not front side)
I'm new to django.I have to create one Product class and that have two foreignkey product-categories and Attribute.Attribute also have foreignkey of product-categories. I have register this model in wagtail model-admin and create orderable attribute. class Products(ClusterableModel): name = models.CharField(max_length=20) stock = models.IntegerField(blank=True) price = models.FloatField(blank=True) product_type = models.ForeignKey(ProdCategory, on_delete=models.CASCADE) def __str__(self): return "%s"%(self.name) panels = [ FieldPanel('name'), FieldPanel('stock'), FieldPanel('price'), FieldPanel('product_type'), MultiFieldPanel([ InlinePanel('attribute', max_num =3), ], 'All Attributes'), ] class Meta: verbose_name_plural = 'Products' verbose_name = 'Product' from django.contrib.postgres.fields import HStoreField, JSONField class Attribute(Orderable): page = ParentalKey('Products', related_name='attribute') attribute = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE,related_name='+') value = models.CharField(max_length=100) So, when i select category and then attribute can show only that attribute having selected category. Thanks in advance. -
App (Python Django, PostgreSql) is deployed successfully on Heroku, but I'm getting error when trying to open
I have successfully deployed Python/Django app called MyPortfolio in Heroku. But when I am trying to open it gives me an error: ModuleNotFoundError: No module named 'jobs' The project folder is 'MeryPortfolio-project'. The project name is 'MeryPortfolio'. Application name is 'jobs'. So Heroku can't find the module for the application. The case is: I have tried to make local and production settings. Local settings I use when I start the local server. Production settings are used in Heroku with the command: heroku config:set DJANGO_SETTINGS_MODULE=MeryPortfolio-project.MeryPortfolio.settings.production The directories are: 'MeryPortfolio-project' /'MeryPortfolio': _init.py settings.py urls.py wsgi.py /settings: init.py base.py local.py production.py These are logs when I try to open the app (heroku open) $ heroku logs 2019-07-18T12:54:14.328455+00:00 app[web.1]: spew: False 2019-07-18T12:54:14.328457+00:00 app[web.1]: check_config: False 2019-07-18T12:54:14.328459+00:00 app[web.1]: preload_app: True 2019-07-18T12:54:14.328461+00:00 app[web.1]: sendfile: None 2019-07-18T12:54:14.328463+00:00 app[web.1]: reuse_port: False 2019-07-18T12:54:14.328465+00:00 app[web.1]: chdir: /app 2019-07-18T12:54:14.328467+00:00 app[web.1]: daemon: False 2019-07-18T12:54:14.328469+00:00 app[web.1]: raw_env: [] 2019-07-18T12:54:14.328471+00:00 app[web.1]: pidfile: None 2019-07-18T12:54:14.328472+00:00 app[web.1]: worker_tmp_dir: None 2019-07-18T12:54:14.328474+00:00 app[web.1]: user: 36932 2019-07-18T12:54:14.328476+00:00 app[web.1]: group: 36932 2019-07-18T12:54:14.328479+00:00 app[web.1]: umask: 0 2019-07-18T12:54:14.328481+00:00 app[web.1]: initgroups: False 2019-07-18T12:54:14.328483+00:00 app[web.1]: tmp_upload_dir: None 2019-07-18T12:54:14.328485+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2019-07-18T12:54:14.328487+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2019-07-18T12:54:14.328489+00:00 app[web.1]: accesslog: - 2019-07-18T12:54:14.328491+00:00 app[web.1]: disable_redirect_access_to_syslog: False 2019-07-18T12:54:14.328494+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s … -
How to multiply succes_url in Django?
How to multiply succes_url in Django view? I tried this but it doesn't work: class ResetPasswordRequestView(FormView): template_name = "registration/password_reset_form.html" form_class = PasswordResetRequestForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): data = form.cleaned_data["email_or_username"] if self.validate_email_address(data) is True: succes_url = '/reset/password/email/' else: succes_url = '/reset/password/username/' -
Why do I not get labels rendered from CharField when using DJANGO formset
I have a form with 2 CharFields. Both have label="xyz". If I use this form in a formset, the lables are not shown in the HTML I have tried looking at the rendered HTML and the label is missing. I have tried just a form and that works. Forms: class WindingVoltsSpecifier(forms.Form): winding_name = forms.CharField(max_length=20, label="Winding name") voltages = forms.CharField(max_length=20, label="Voltages") View: def add_mains_transformer_primary_configs(request): # Add a new config # Create the formset, specifying the form and formset we want to use. # From https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html VoltsSpecifierFormSet = formset_factory(WindingVoltsSpecifier) if request.method == 'POST': pass else: mt_config_form = MainsTransformerConfiguration() volts_formset = VoltsSpecifierFormSet() context = { 'mt_config_form' : mt_config_form, 'volts_formset' : volts_formset, } return render(request, 'designer/mains_configs.html', context) Template: {% extends 'designer/base.html' %} {% load crispy_forms_tags %} {% block title %}configuration{% endblock %} {% block content %} {% load static %} <h1>Configuration</h1> <form method="post"> {% csrf_token %} {{ mt_config_form|crispy }} {{ volts_formset.management_form|crispy }} {% for volts_form in volts_formset %} <table> {% for form in volts_form %} {{ form }} {% endfor %} <table> <!--<div class="volts-formset"> {{ volts_form.winding_name }} {{ volts_form.voltages }} </div> --> {% endfor %} {% if volts_formset.non_form_errors %} {% for error in volts_formset.non_form_errors %} {{ error|escape }} {% endfor %} {% endif %} … -
Django and DRF: serializer for a user model
I am wrote a serializer for the User model in Django with DRF: the model: from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.db import models from django.utils.translation import ugettext class BaseModel(models.Model): # all models should be inheritted from this model created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class User(AbstractBaseUser, BaseModel): username = models.CharField( ugettext('Username'), max_length=255, db_index=True, unique=True ) email = models.EmailField( ugettext('Email'), max_length=255, db_index=True, blank=True, null=True, unique=True ) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ('email', 'password',) class Meta: app_label = 'users' the serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user def update(self, user, validated_data): user = super().update(user, validated_data) user.set_password(validated_data['password']) user.save() return user It works. But I probably do two calls instead of one on every create/update and the code looks a little bit weird(not DRY). Is there an idiomatic way to do that? $python -V Python 3.7.3 Django==2.2.3 djangorestframework==3.10.1 -
for loop not iterating for second value
Some explaination about the code:- taking user's multiple input (comma separated) from CmdForm (django form)---> getting it in ipInsert ----> splitting it and stored in ipIns---> then Iteration but the issue is when i m taking comma separted value, the for loop is not iterating for the second time. displaying the result of input before comma. In views.py def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler ipInsert = request.POST.get('ip_address', '') ipIns = ipInsert.split(',') for ipIn in ipIns: devices = { 'device_type':'cisco_ios', 'ip':ipIn, 'username':'mee', 'password':'12345', 'secret':'12345', } cmd = request.POST.get('command', '') try: netconnect = ConnectHandler(**devices) except (AuthenticationException): re = 'Authentication failed.! please try again {}'.format(ipIn) print(re) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass except (SSHException): re = 'SSH issue. Are you sure SSH is enabled? {}'.format(ipIn) print(re) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass except (NetMikoTimeoutException): re = 'TimeOut to device {}'.format(ipIn) print(re) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass except (EOFError): re = 'End of file while attempting device {}'.format(ipIn) print(re) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass except Exception as unknown_error: re = 'Some other error {}' .format(unknown_error) print(re) return render(request,'first_app/forms.html', {'form': form, 'reprinting':re}) pass getIP = netconnect.send_command(ipIn) output = netconnect.send_command(cmd) now = time.strftime("%Y_%m_%d__%H_%M_%S") file = … -
Want to create PDF from template html in python django
I have template name in tempName in app django view by conditional check i want to choose matching template present at location app\dashboard\web\html\templates then i want to create pdf of that selected html template.To avoid library uncompatilbilty, i am using python 3.6. -
Set bucket gjango google storage in view
I have a view that is storing data in GoogleStorage. I have different buckets for different projects - so I cant use settings.GS_BUCKET_NAME. How I can set dynamically GS bucket name? I have following idea, but no idea if it will work class GStogare(GoogleCloudStorage): bucket_name = "" def set_bucket_name(self, somethig_with_bucket_name_id): self.bucket_name = SomethingWithBucketName.objects.\ get(pk=something_with_bucket_name_id).bucket gstogare = GStorage() class FileModel(models.Model): something_with_bucket_name = models.ForeighKey(....) file = models.FileField(storage=gstorage) def save(self, gstorage, force_insert=False, force_update=False, using=None, update_fields=None): gstorage.get_bucket_name(self.somethig_with_bucket_name) super().save(force_insert=False, force_update=False, using=None, update_fields=None) Basically - override GoogleCloudStorage class, make it set bucket_name dynamically in model save method. Could it work? -
How to get object at CreatView
There is a form that is rendered by url url(r'kredit/(?P<credit_slug>[-\.\w\d]+)/$', CreditDetail.as_view(), name='credit_detail'), urls url(r'kredit/(?P<credit_slug>[-\.\w\d]+)/$', CreditDetail.as_view(), name='credit_detail'), url(r'kredit_request/$', CreditOnlineRequestView.as_view(), name='credit_request'), The form is processed in the CreditOnlineRequestView(CreateView) view. It is necessary to pull out the credit_slug from CreditDetail view in it (here the form was drawn) views class CreditDetail(FormView): form_class = CreditPaymentForm template_name = 'credits/credit_detail.html' def get_initial(self): initial = super(CreditDetail, self).get_initial() initial['request'] = self.request return initial def get(self, *args, **kwargs): request_form = CreditOnlineRequestForm(self.request.GET or None, prefix="request") class CreditOnlineRequestView(CreateView): form_class = CreditOnlineRequestForm model = CreditOnlineRequest template_name = 'credits/credit_listing.html' prefix = 'request' def form_valid(self, form, **kwargs): credit_request = form.save(commit=False) credit_request.credit = credit #??? return super(CreditOnlineRequestView, self).form_valid(form) def form_invalid(self, form): errors = dict([(k, v[0]) for k, v in form.errors.items()]) return errors forms class CreditOnlineRequestForm(forms.ModelForm): class Meta: model = CreditOnlineRequest exclude = ['credit'] #вот это поле нужно определить def __init__(self, *args, **kwargs): super(CreditOnlineRequestForm, self).__init__(*args, **kwargs) #??? What are the options? I think, either through the cache, or through pulling out the previous page to do, but this is somehow not very humane, as for me. The best option, as for me, is to transfer the credit instance to a hidden form field in the CreditDetail view, but … -
How to create a list of objects by grouping them by a common name
i have a list of ungrouped objects and i want to return a list of grouped objects by a common value [{"name": "test", "group": "A"},{"name": "test2", "group": "B"},{"name": "test3", "group": "A"},{"name": "test4", "group": "B"}] I want to return this [{"group":"A","users":[{"name":"test},{"name":"test3"}]}] -
myModel has no 'object' member / How to setup pylint-django
In my view I want to store in a variables every object from myModel but I have the Class 'myModel' has no 'objects' memberpylint(no-member) error I have red that installing pylint-django as suggested by this similar topic : Class has no objects member but it didn't resolved my error then (in the same topic) I red that adding this "[python]": { "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ], }, To my settings.json would do the trick but I have the warning : Unknown Identifier. Use language identifiers and the error on myModel.objects is still here -
There is a way to block return back to previous page after logout?
I am using my own authentification because i don't know how to extend django registration app to make me have a model user where user will have his login and password inside the model. when i logout i and click on the background firefox button i get the other page, when i refresh the page i have an session key error what is normal, i want to solve the problem like in the django admin where you can't go back after logout class User(models.Model): name = models.CharField(max_length=25) pwd = models.CharField(max_length=100) created = models.DateTimeField(_('created'), auto_now_add=True) active = models.BooleanField(default=False) def logout(request): from django.shortcuts import redirect for key in list(request.session.keys()): if key == 'id' : del request.session['id'] if key == 'code': del request.session['code'] if key == 'name': del request.session['name'] return redirect('/') -
FCM message not showing up in any browser, despite success callback in django app
Im trying to send pushes with firebase from my django app. Here is a code of sending: class Command(BaseCommand): def handle(self, *args, **options): print('entered command') server_key = '<server-key>' token_id = '<token-id>' title = 'test push not' text = 'here is about how cool we are' icon = '' link = 'http://test.ru' url = 'https://fcm.googleapis.com/fcm/send' data = { "notification":{ 'title': title, 'body': text, 'icon': icon, 'click_action': link }, 'to': token_id, } headers = { 'Content-Type': 'application/json', 'Authorization': f'key={server_key}' } r = requests.post(url, data=json.dumps(data), headers=headers) print(r.text) print('message posted') After sending i have a callback from firebase: {"multicast_id":<multicast_id>,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"<message_id>"}]} But nothing showing up.I tryed this from different PCs, browsers, with my mobile phone, but it always success and no notification. A already used this test script with another firebase app, and it works well. And now i didnt changed anything except server key. I register again my devices on new app, but have no effect. Actually i checked this question but there is still no answer, with the same problem. -
Is there any monitoring tool to monitor my Django-channels2 project.?
I want to monitor all the web-sockets and profile their performance. There are a lot of ways to monitor WSGI app but I haven't found anything to monitor ASGI app. Thanks for the help. ! PS: im still new to django-channels. -
How to set different storage engines for each table in Django (MySQL backend)?
I have a MySQL database that I did not create with Django. It has mixed storage engines for tables. I need to tell Django which storage engine it should use for which table. Is there any way I can do that? I' ve seen an approach that inside the DATABASES dictionary in settings.py two separate database connections are defined, each with separate storage engine (as described here: Django set Storage Engine & Default Charset), but that adds extra complexity when using django querysets, because I need to remember then what kind of storing engine is being used in each table. pseudo code of what I want to achieve class Model_1(models.Model): # using InnoDB class Model_2(models.Model): # using MyISAM -
Upload every format of excel in Django
I am uploading CSV files in django like this: Views.py csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) uploaded_by = request.user for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = ItemBatch.objects.custom_update_or_create(name=column[0], pid=column[1], quantity=column[2],length=column[3], width=column[4], height=column[5],volume=column[6], weight=column[7], truck_type=column[9],date=column[8],origin=column[10], destination=column[11], uploaded_by=uploaded_by) How can I modify it so that I am able to upload every format of Excel? Can I add the decodings in the decode('****') ? I have read about the django-excel but couldn't figure it out -
how does django handle password in form
I'm following django docs and got confused with django form model. I'm trying to build a user signup page with custom user class CustomUser(AbstractUser): password = models.CharField(max_length=200, null=False) location = models.CharField(max_length=200, blank=True, default="") description = models.CharField(max_length=300, blank=True, default="") and I also defined a form class CustomUserCreationForm(ModelForm): description = forms.CharField() location = forms.CharField() password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') a view class SignUpView(View): form_class = CustomUserCreationForm template_name = 'signup.html' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save(True) return render(request, self.template_name, {'form': form}) an Admin class CustomUserAdmin(UserAdmin): fieldsets = UserAdmin.fieldsets + (('Misc', {'fields': ('description', 'location')}),) add_fieldsets = UserAdmin.add_fieldsets + (('Misc', {'fields': ('description', 'location')}),) admin.site.register(CustomUser, CustomUserAdmin) question is how this form will handle password field, since there's only one password field in CustomUser Model, and how this form map to CustomModel And what if I want to seperate backend and front end and use pure html/js form instead, do I still need to define a form, if yes, how should I map it to model and html Thanks -
CustomUser has no attribute 'objects'
I am using jwt auth system When I fill the field it returns jwt token easily but if i want to create a profile with this token it says CustomUser has no attribute 'objects' my users/models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(default=timezone.now) object = UserManager() USERNAME_FIELD = 'email' def save(self, *args, **kwargs): super(CustomUser, self).save(*args, **kwargs) return self and user/views.py class CreateUserAPIView(APIView): permission_classes = (AllowAny,) def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) serializer.save() try: email = request.data['email'] password = request.data['password'] user = CustomUser.object.get(email=email, password=password) if user: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) user_details = {} user_details['id'] = "%s" % (user.id) user_details['token'] = token user_logged_in.send(sender=user.__class__, request=request, user=user) return Response(user_details, status=status.HTTP_200_OK) except Exception as e: raise e else: return Response(status=status.HTTP_403_FORBIDDEN) except KeyError: res = {'error': 'please provide a email and a password'} return Response(res) with this code I am getting a token but with this token I cannot create a profile profile/models.py class Profile(TimeModel): user = models.OneToOneField('user.CustomUser', on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image = models.ImageField(upload_to='path', null=True) def __str__(self): return self.user.email here what i have tried so far. I tried …