Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'DatabaseOperations' object has no attribute 'geo_db_type
So I am currently new to Django and developing a GeoDjango application where I need users to be able to upload Shapefiles and Point Features into the database. I am currently using PostgreSQL as my database. Running: python manage.py makemigrations is not a problem at all. The problems comes when I try to migrate using: python manage.py migrate I get the 'DatabaseOperations' object has no attribute 'geo_db_type Error. My models.py file likes like this class Beacon(models.Model): land_id = models.OneToOneField(Land, on_delete=models.CASCADE) lon = models.FloatField() lat = models.FloatField() mpoly = models.MultiPolygonField() beacons = models.MultiPointField() and also the Database configuration part in my settings.py file looks like so, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'LIMS', 'USER': 'postgres', 'PASSWORD': '<my_password_is_here>', 'HOST': 'localhost' } } I have searched all over the internet but all solutions are not working out for me and seems like most of them are using PostGIS as the database. If anyone could help regarding this issue it would be greatly appreciated. Below I've also included the full summary of the error (LIMS) C:\Users\Surveyor Jr\Desktop\Projects\Django\LIMS\LIMS>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, farm_inventory, sessions, users Running migrations: Applying farm_inventory.0023_auto_20201225_1304...Traceback (most recent call last): File "C:\Users\Surveyor Jr\Desktop\Projects\Django\LIMS\LIMS\manage.py", … -
How can fix the generic DetailView for my product variation
I am new to Django and having hard time completing product variation for my product detail page. I am using generic view DetailView. I get the failure notification Exception has occurred: NameError name 'self' is not defined class ProductDetailView(DetailView): model = Item template_name = 'product.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_gallery'] = Images.objects.filter(item=self.object) context['item_variant'] = Variants.objects.filter(item=self.object) return context if self.object.variant is not None: if request.method == POST: variant_id = request.POST.get('variantid') variant = Variants.objects.get(id = variant_id) colors = Variants.objects.filter(item_id = id, size_id = variant.size_id) sizes = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id = %s GROUPBY size_id', [id]) query += variant.title + ' Size:' + str(variant.size) + ' Color:' +str(variant.color) else: pass -
I can't get accurate value in dictionaries in django
Whenever i try to print the dictionaries in Django i can't get what I need The views models are given below Geeks Help to solve this begginner question Views.py def home(request): roomCate=dict(Room_Type.ROOM_CATEGORIES) roomUrl=Room_Type.objects.all() print(roomCate) print(roomUrl) return render(request,'index.html') Whenever I print roomCate and roomUrl,I got what I need in roomUrl but, In roomCate i changing while print the dictionaries of value, <QuerySet [<Room_Type: Sig>, <Room_Type: Lux>, <Room_Type: Elt>]> The value is Not changing while print the value BUT In {'Lux': 'Luxury', 'Sig': 'Signature', 'Elt': 'Elite'} the value changing Here is my models.py class Room_Type(models.Model): """Django data model Room_Type""" ROOM_CATEGORIES={ ('Elt','Elite'), ('Lux','Luxury'), ('Sig','Signature') } image = models.ImageField(upload_to="pics") roomtype = models.CharField(choices=ROOM_CATEGORIES,max_length=20) price = models.CharField(blank=True, max_length=100) def __str__(self): return f'{self.roomtype}' I want the method print result same as roomUrl but I cant get value same as roomUrl please geeks help me solve this Thank You -
Seeing posts next to each other
I am currently working on a django blog and I'd like to know if there's something that can make me see posts next to each other instead of one under another like the image: Here's the css code: <style> body { background-size: cover; background-position: center; background-image: url("{% static 'img/periodic_table.jpg' %}"); justify-content: center; align-items: center; background-repeat: no-repeat; background-attachment: fixed; } div.container { align-items: center !important; text-align: center !important; } .navbar-default { background-color: transparent !important; border-color: transparent !important; } p{ color: white; } .wrap-login100 { margin-top: 70px; background: #fff; border-radius: 10px; min-height: 20vh; justify-content: center; align-items: center; padding: 15px; background-position: center; background-size: cover; background-repeat: no-repeat;; } h3 { padding-top: 20px } </style> And here's the template: <html> {% include 'periodic/head_search.html' %} <body> {% include 'periodic/header.html' %} <br> <br> <div class="container"> <div class="row"> <!-- Latest Posts --> <main class="posts-listing col-lg-8 "> <div class="container"> <div class="row "> <!-- post --> {% for element in query %} <div class= "wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33 six wide post col-xl-6 post col-xl-6"> <div class="post-thumbnail"><a href="{{ element.get_absolute_url }}"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></a></div> <div class="post-details"> </div><a href="{{ element.get_absolute_url }}"> <h3 class="h4"> {{ element.title }}</h3></a> </div> </div> {% endfor %} </div> </div> </main> </div> </div> </div> </body> {% include … -
Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84)
I am trying to get data from api using axios but i am getting this error. I am using django api. my api seems to be working fine on postman but with react it is giving me the error: getStudentById(id) { const url = `${API_URL}/api/student/student-detail/${id}`; return axios.get(url); } componentDidMount() { let urlId = this.props.match.params.id; let thisComponent = this; studentService.getStudentById(urlId) .then(function (response) { console.log(response.data.Name) thisComponent.setState({ id: response.data.id, name: response.data.Name, enrollment_no: response.data.Enrollment_No, registration_no:response.data.Registration_No, semester: response.data.Semester, year: response.data.Year, course_nam: response.data.Course_Name, course_code: response.data.Course_Code, images: response.data.images }); }).catch(error=>console.log(error)) } -
What are the most important basics to have a strong and stable django knowledge?
i want to learn Django but i feel overwhelmed by all the things i can learn. Can some of you guys help me out and give me a guideline for the most important things to know as a django beginner in order to be better for the long term? I am relatively knew to python but getting better really fast. I would like to start with Django. Thank you guys xoxo -
Query elasticsearch using django-elasticsearch-dsl without PostgreSQL connection
I've a first django project with PostgeSQL and elasticsearch 7 running and indexes updated automatically thanks to the django-elasticsearch-dsl library. Now I would like to query (GET search only) the elasticsearch indexes from another django project. I copied the models and the documents.py. It works only if I connect to this new project the original PostgreSQL db, otherwise, with another db (empty but with migration of the models done) I've a zero matching as result (not an error, but no data). -
allDRF regex search on all fields
I need DRF '$'- regex search on all("__all__") fields of a model in Django Rest API Framework. I can specify like search_fields = ['$username', '$first_name', '$email', '$last_name'] this on all fields explicitly. but I need $-regex search on all fields of a model something like search_fields = '$__all__' Please anybody giude me on this , Thanks in advance. -
How to register with Django admin approval?
In the system I created with Django, users should not log in without the admin approval after registration. For example, after the user fills in the registration form, user will see the warning waiting for admin approval and cannot login to the system without approval from the admin panel. views.py def signup(request): form_class = SignUpForm if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) user.first_name = form.data['first_name'] user.last_name = form.data['last_name'] user.rank = form.data['rank'] user.comp_name = form.data['comp_name'] login(request, user) return redirect('/') else: form = form_class() return render(request, 'signup.html', {'form': form}) models.py class UserProfile(AbstractUser): ranks = ( ('analyst', 'Analyst'), ... ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) -
Django Project is not hosting in Cpanel
Problem occuring My Django project is not hosting on cpanel. I have created 2 app in my django project(Affiliate, members). app and project file -
Wagtail-bakery and routable pages implementation
I have a simple Wagtail CMS blog. My models are straightforward but include a routable BlogIndexPage page so I can serve different versions of this page, with filters for category (BlogCategory) or tag (BlogPageTag): from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index from wagtail.snippets.models import register_snippet from taggit.models import TaggedItemBase from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey from wagtailcodeblock.blocks import CodeBlock from .blocks import * class HomePage(Page): def get_context(self, request): context = super().get_context(request) # temporary instead of insta feed@ context['posts'] = BlogPage.objects.live() return context class BlogPageTag(TaggedItemBase): content_object = ParentalKey( 'BlogPage', related_name='tagged_items', on_delete=models.CASCADE ) @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) display_order = models.IntegerField(null=True, blank=True) panels = [ FieldPanel('name'), FieldPanel('slug'), FieldPanel('display_order'), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class BlogPage(Page): date = models.DateField("Post date") intro = models.TextField() tags = ClusterTaggableManager(through=BlogPageTag, blank=True) soundcloud_link = models.TextField(blank=True) main_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True, blank=True ) category = models.ForeignKey( BlogCategory, on_delete=models.SET_NULL, related_name='+', null=True, blank=True ) body = StreamField( [ ('h1_fluid', H1FluidBlock(),), ('h2_fluid', H2FluidBlock(),), ('paragraph', blocks.RichTextBlock()), ('fluid_paragraph', ParagraphFluidBlock()), ('code', CodeBlock(label='Code')), ('image', ImageSrcset(label='Image w/ srcset')), … -
Django - How to make view only acessible to user
How to make a view only accessible only for active user no, staff or superuser can access it only active user. -
Lost with django-social-auth and custom oauth2 backen
This may not be a very good stackoverflow question because I am so lost I think my question will appear like I have made no effort. I want to get the user's email from Xero, a cloud accounting app which specifically allows for this (https://developer.xero.com/documentation/oauth2/sign-in) When I create a Xero "app" to get the necessary credentials, I need to provide an OAuth 2.0 redirect URI, and I think this is very common or even universal for oauth2 authentication. I can't see an example of how I provide this URL to the configuration of my backend (a subclass of BaseOAuth2). Apart from being a redirect URL, it must also be provided in the AUTHORIZATION_URL. The Xero URL template is https://login.xero.com/identity/connect/authorize?response_type=code&client_id=YOURCLIENTID&redirect_uri=YOURREDIRECTURI&scope=email&state=1234 I have read quite a few tutorials. I can't find any on adding a custom oauth2 backend, but in this tutorial there are examples for GitHub and Twitter: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html In both cases, the tutorial says to provide a callback URL of the form http://localhost:8000/oauth/complete/twitter/ when defining the app on the authenticator's side. Is this a hard-coded, undocumented default? Or do I need to define it somewhere in my configuration? In the tutorial, I can't see any reference to a callback url … -
Django DRF Unable to implement logic Foreign Key
I am making a rest api in django and is unable to implement a particular feature in my api. I have 3 models in total in my api.Listed below: class ProductInfo(models.Model): title = models.CharField(max_length=15) image = models.TextField() price = models.CharField(max_length=5) def __str__(self): return self.title + '| ' + str(self.id) class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) proceed = models.BooleanField(default=True) def __str__(self): return self.item.title + ' | ' + self.user.username + ' | ' + str(self.id) class BoughtItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return self.user.username + ' | ' + self.item.title In my model named Bought Item , I want to save multiple item (which is a foreign key) in a single hit.I know how to save one by one with the item id but I want to pass a list in it and also I want the user to be same with also the corresponding quantity of every item in the Bought Item model.I know its quite complicated and so I am unable to do it.I am using it in rest api , so I also need to create a serializer but I … -
How to make make carousel card to to being as tall as the tallest card
I am using the glidejs to make this carousel. I can't figure out how to make the cards have the same height as the tallest one and being responsive at the same time. (See below) I have tried to set the .glide__slides to have height: 35vh and make the card height 100%. This makes the cards have the same height but there is a big white gap at the bottom as shown below when on a smaller width screen Here is part of my code <div class="container-fluid bg-light"> <div class="container"> <div class="row"> <div class="col-lg-2 my-auto"> <h1>Latest Products 2021</h1> </div> <div class="col-lg-10 mt-3"> <div class="glide"> <div class="glide__track" data-glide-el="track"> <ul class="glide__slides"> {% for product in latest_products %} <li class="glide__slide"> <div class="card px-2 h-100"> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.image.url }}" class="carousel-image" alt="{{ product.name }}"> </a> <div class="card-body"> <a href="{{ product.get_absolute_url }}" class="text-decoration-none"> <h5 class="card-title">{{ product.name|truncatechars:30 }}</h5> </a> <h6 class="card-subtitle mb-2 text-muted">RM {{ product.price }}</h6> <button class="btn btn-sm btn-success">Add to Cart</button> </div> </div> </li> {% endfor %} </div> </div> <div class="glide__arrows" data-glide-el="controls"> <button class="glide__arrow glide__arrow--left text-dark" data-glide-dir="<"><i class="fas fa-arrow-left"></i></button> <button class="glide__arrow glide__arrow--right text-dark" data-glide-dir=">"><i class="fas fa-arrow-right"></i></button> </div> </div> </div> </div> </div> </div> -
Django admin How to solve the problem that all parts are not visible?
I created a system with Django. I create an abstract user model with some custom fields. My form is working but in the admin page I cannot see my custom models. models.py class UserProfile(AbstractUser): ranks = ( ... ('cfo', 'Chief Financial Officier'), ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) def __str__(self): return self.username class CompanyProfile(models.Model): ... admin.py admin.site.register(CompanyProfile) class CustomUser(UserAdmin): add_form = SignUpForm model = UserProfile form = SignUpChangeForm list_display = ('username', 'first_name', 'email', 'last_name', 'rank', 'comp_name') fieldsets = ( (None, {'fields': ('email', 'password')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'rank', 'comp_name')} ), ) search_fields = 'email' admin.site.register(UserProfile, UserAdmin) admin view As you can see in admin view there is no ranks and company name field. How can I solve it? -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app1.myUser' that has not been installed
In my Django project, I have an app1 named app. I create a model named myUser in my app1 app's model.py like this: from django.contrib.auth.models import User, AbstractUser class myUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(myUser, on_delete=models.CASCADE, primary_key=True) roll = models.IntegerField(blank=True) I also set AUTH_USER_MODEL in settings.py like this: AUTH_USER_MODEL = 'app1.myUser' Here, admin.site.register(myUser) is also done in admin.py and app1 is also installed in INSTALLED_APPS list in settings.py. Now I have face following error in my console when I use migrate or runserver: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\apps\config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'myuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\contrib\auth\__init__.py", line 156, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "G:\Python\lib\site-packages\django\apps\registry.py", line 210, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "G:\Python\lib\site-packages\django\apps\config.py", line 180, in get_model raise LookupError( LookupError: App 'app1' doesn't have a 'myUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "G:\Python\lib\threading.py", line 932, in _bootstrap_inner self.run() self._target(*self._args, **self._kwargs) File "G:\Python\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() … -
drf use different serializer show 'You cannot call `.save()` after accessing `serializer.data`
i want post question info first , and post options list with question id at "opt_ser.save()" it show "'You cannot call .save() after accessing serializer.data.If you need to access data before committing to the database then inspect \'serializer.validated_data\' instead. '" class QuestionAddApiView(APIView): def post(self, request, *args, **kwargs): option_list = request.data.pop('option_list') question_serializer = QuestionReadAndWriteSerializer(data=request.data) try: if question_serializer.is_valid(): question_serializer.save() question = question_serializer.instance opt_response = [] for option_item in option_list: option_item['question'] = question opt_ser = OptionSerializer(data=option_item) if opt_ser.is_valid(): opt_ser.save() opt_response.append(opt_ser.data) question['option_list'] = opt_response return BResponse(question, status=status.HTTP_200_OK) except Exception as e: return BResponse(question_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
multiple joins on django queryset
For the below sample schema # schema sameple class A(models.Model): n = models.ForeignKey(N, on_delete=models.CASCADE) d = models.ForeignKey(D, on_delete=models.PROTECT) class N(models.Model): id = models.AutoField(primary_key=True, editable=False) d = models.ForeignKey(D, on_delete=models.PROTECT) class D(models.Model): dsid = models.CharField(max_length=255, primary_key=True) class P(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=255) n = models.ForeignKey(N, on_delete=models.CASCADE) # raw query for the result I want # SELECT * # FROM P, N, A # WHERE (P.n_id = N.id # AND A.n_id = N.id # AND A.d_id = \'MY_DSID\' # AND P.name = \'MY_NAME\') What am I trying to achieve? Well, I’m trying to find a way somehow be able to write a single queryset which does the same as what the above raw query does. So far I was able to do it by writing two queryset, and use the result from one queryset and then using that queryset I wrote the second one, to get the final DB records. However that’s 2 hits to the DB, and I want to optimize it by just doing everything in one DB hit. What will be the queryset for this kinda raw query ? or is there a better way to do it ? Above code is here https://dpaste.org/DZg2 -
Django admin how to solve abstract user problem? [duplicate]
I created a system with Django. I create an abstract user model with some custom fields. My form is working but in the admin page I cannot see my custom models. models.py class UserProfile(AbstractUser): ranks = ( ... ('cfo', 'Chief Financial Officier'), ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) def __str__(self): return self.username class CompanyProfile(models.Model): ... admin.py admin.site.register(CompanyProfile) class CustomUser(UserAdmin): add_form = SignUpForm model = UserProfile form = SignUpChangeForm list_display = ['username', 'first_name', 'email', 'last_name', 'rank', 'comp_name'] admin.site.register(UserProfile, UserAdmin) As you can see in admin view there is no ranks and company name field. How can I solve it? -
in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (name) specified for User
[i tryin to create a registration form and while trying to make migration I got this issue any clue what causing error like this][1] -
Django ModelFormset Forms Returning Empty Data
I have been trying to solve this for weeks to no avail, and would really appreciate some help. Background I'm creating a Django app which takes input of a user's educational experience, and wanted to provide users with the ability to add new experiences via an "Add More" button (i.e if they had an undergrad and masters). I'm doing this using ModelFormsets and Jquery, following this answer: Dynamically adding a form to a Django formset with Ajax. Problem When accessing the cleaned_data of the formset, only the first initial form has values in its cleaned_data, the additional generated forms return an empty dictionary with no cleaned data in them. Views.py EducationFormset = modelformset_factory(Education, form=EducationForm, fields=('institution', 'degree', 'major', 'major_start_date', 'major_end_date', 'major_description', 'gpa',)) if request.method == 'POST': formset = EducationFormset(request.POST, request.Files) if formset.is_valid(): formset.save() for form in formset.forms: print(form.cleaned_data) else: print(formset.errors) else: formset = EducationFormset(queryset=Education.objects.none()) context = { 'user_form': user_form, 'education_form': education_form, 'experience_form': experience_form, 'formset':formset, } return render(request, 'create.html', context) HTML {{ formset.management_form }} <div id="form_set"> <div class="form-group"> {% for form in formset.forms %} {{form.errors}} <table class="no_error"> {{form.as_table}} </table> {% endfor %} </div> </div> <div id="empty_form" style="display:none"> <table class="no_error"> {{formset.empty_form.as_table}} </table> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) … -
Django - Grouping data and showing the choices's name in template
I am trying to create a pie chart (chart.js). My goal is grouping titles and displaying how many people work by title in piechart. Models.py class Personel(models.Model): name = models.CharField(max_length=30) surName = models.CharField(max_length=20) titles= models.IntegerField(choices=((1,"Researcher"),(2,"Technician"),(3, "Support Personel")),default=1) def __str__(self): return f"{self.name},{self.surName}" class Meta: db_table = "personel" verbose_name_plural = "Ar-Ge Personeller" Views.py def index(request): personel_titles = Personel.objects.values('titles').annotate(Count('titles')) context = { "personel_titles" : personel_titles, } return render(request, 'core/index.html',context) >>> print(personel_titles) >>> {'titles': 1, 'titles__count': 10} {'titles': 2, 'titles__count': 11} {'titles': 3, 'titles__count': 3}> It is okay for me and all I need is in here. But I couldn't figure out how can I display title's name in my template(also in chart label) Template {% for title in personel_titles %}<p>{{ title.get_titles_display }}</p>{% endfor %} What am I missing? How can I return the choice's name in values? -
django rest framework apis using legacy db without creating django default tables
I am going to develop django rest framework apis using postgres legacy database in which apart from the existing tables no other default django tables should be created. I would like to know without creating any django default tables or doing migrations, can i able to access records from tables using ORM? Can i able to access admin page without creating django auth table (i.e superuser)? If no for both questions, only way to connect to db is using any db adapter like psycopg2? -
Convert Django model form based system into a raw HTML based form system for signup
I have a class-based view system for signup in Django which uses Django's model form. but I need to render my custom build HTML form in place of that. My models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') And views.py: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('students:quiz_list') This system has a form.py also which made the hard work and render the Django model form. Now I need to replace these types of Django's default model form with my custom build HTML form something like this link. How can I use the following types of simple system which will receive data from views.py and will create a user? if request.method == 'POST': this_username = request.POST['username'] this_password = request.POST['password'] this_otherKindofStuff = request.POST['otherKindofStuff'] Student_signup = TableA.objects.create(name=this_name, password=this_password, otherKindofStuff=this_otherKindofStuff) Student_signup.save()