Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django creating Profile with custom company fields try to conect with the owner
I have two forms (OwnerCreateForm, EmployeesCreateForm) and 3 models (Profile, Company and Owner). when the owner signs up, it creates the company and its own User object. after owner login, you can create employees. Have the Owner connect to the profile and associate it with the company I need to associate the owning company to the employees. That each company manages its users, that they see the same thing Here are the details I'm using: MODELS class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return '{} Profile'.format(self.user) class Owner(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return '{} Owner'.format(self.profile) class Tienda(models.Model): dueño = models.ForeignKey(Owner, null=True, on_delete=models.CASCADE) nombre_tienda = models.CharField(verbose_name='Nombre de la Tienda', max_length=120) direccion = models.CharField(verbose_name='Su Direccion', max_length=160) phone = models.CharField(max_length=11, null=True) businessemail = models.EmailField(unique = True, verbose_name='Su email') def __str__(self): return self.nombre_tienda class Employee(models.Model): STATUS = ( ('Admin', 'Admin'), ('Gerente', 'Gerente'), ('Validador', 'Validador') ) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) role = models.CharField(choices=STATUS, max_length=16) tienda = models.ForeignKey(Tienda, null=True, on_delete=models.CASCADE) def __str__(self): texto = "{0} ({1}) {2}" return texto.format(self.tienda, self.role, self.role) FORMS class TiendaForm(ModelForm): class Meta: model = Tienda fields = ('nombre_tienda', 'direccion', 'businessemail') class OwnerCreateForm(UserCreationForm): class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = … -
import "hcaptcha_field" could not be resolved Django
I'm trying to add hCaptcha to my project but I can't get it to work, I've tried several versions of this library but I can't get it to work every time importing 'hcaptcha_field' or 'hcaptcha_fields' gives me the error 'import "hcaptcha_field" could not be resolved Django'. Any solution? -
No 'Access-Control-Allow-Origin' header is present on the requested resource. Uploads are not working
I ran into this cors issue when i deployed my django project which is using the django rest api and netlify for the frontend. I tried some of the solutions on here but nothing worked for me not even: CORS_ORIGIN_ALLOW_ALL = True Is there maybe something i'm missing on the frontend? Is there a way to get more details about what exactly the issue is? This only seems to happen on my upload form. (I added the code below) It works fine on on my local machine using docker. Access to XMLHttpRequest at 'https://domain/dj-rest-auth/user/' from origin 'https://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. patch https://domain/dj-rest-auth/user/ net::ERR_FAILED 400 import { useState } from 'react'; import { Formik, Field, Form, ErrorMessage } from 'formik'; import axios from "axios" import { API } from '../api' import { useDispatch, useSelector } from "react-redux"; import { setInfo } from "../store/userInfoSlice"; import { Button, message, Upload } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; import ImgCrop from 'antd-img-crop'; import { Spin } from 'antd'; export function Profile() { const info = useSelector((state) => state.userInfo.value); const accessToken = useSelector((state) => state.tokens.value.accessToken); const [loading, setLoading] = useState(false) const … -
Add default widgets to a model class
I have one model Foo and a few different forms to create different types of Foo instances. Foo contains several date fields, and I always want to use the Bootstrap datepicker when these fields are listed in a form. The only two approaches I know about right now are: To add the widget to every form, violating the DRY principle. To add the widget to class FooForm(ModelForm), and then inherit FooForm into class BarForm(FooForm), class BazForm(FooForm), etc. However, this approach mean I must remember to inherit each time. If I had instead been able to add widget specifications in the model Foo, then I can "set-and-forget" these settings. However, I have not identified how to do this yet, if it is at all possible. Any thoughts on how to add default widgets to a Django Model class? -
rabbitmq connection across two django project celery task
I have two Django project one for crawl data and another one for rest api. I have a celery task in my crawler project that send crawled data to my api project app that include a celery task for get data and do something on that with rabbitmq connection my problem is while celery tasks run and data send to api getter task. i have below error in my getter task : [2022-08-09 19:00:49,376: ERROR/MainProcess] Received unregistered task of type 'crawler.tasks.news_crawler'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/home/.../Projects/.../.../venv/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'crawler.tasks.news_crawler' -
Creating a separate comments app for a ticket project using django generic class based views
How do I override the get_context_data method of my DetailView so that it displays both the ticket details and its comment list? How do I get the comment object from a different app so that I can put it into the view? The end goal is to have both the Ticket Details and have the comment list on the same page. Here's what I have so far This is my TicketDetailView class TicketDetailView(DetailView): model = Ticket context_object_name = 'comments' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = context['comments'].filter(author=self.request.user) return context This is my CommentListView class CommentListView(ListView): model = Comment template_name = 'tickets/ticket_detail.html' context_object_name = 'comments' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self, *args, **kwargs): ticket = self.kwargs['ticket'] return Comment.objects.filter(ticket=ticket).order_by(self.ordering) -
Django: how to fix collect static in django heroku?
I am trying to deploy a django app to heroku i am already serving the static files using AWS and eveything seems to be working fine on the local server, i have committed the code to github repo and and now i want to deploy using heroku, i get this error on the process of deploying Successfully built django-auto-logout django-formset-js-improved django-jquery-js django-mailgun-provider django-plaintext-password django-rest-auth django-rest-framework django-static-fontawesome psycopg2 rjsmin validate-email starkbank-ecdsa Installing collected packages: validate-email, starkbank-ecdsa, rjsmin, pytz, python-decouple, django-widget-tweaks, django-tinymce, django-templated-mail, django-static-fontawesome, django-social-share, django-js-asset, django-dotenv, django-ckeditor-5, django-auto-logout, dj-database-url, whitenoise, urllib3, uritemplate, sqlparse, six, python-http-client, pyjwt, psycopg2-binary, psycopg2, Pillow, oauthlib, lxml, jmespath, idna, gunicorn, djoser, django-environ, django-crispy-forms, django-ckeditor, charset-normalizer, certifi, asgiref, sendgrid, requests, python-dateutil, Django, requests-oauthlib, djangorestframework, django-taggit, django-storages, django-plaintext-password, django-mailgun-provider, django-jquery-js, django-jazzmin, django-heroku, django-filter, botocore, s3transfer, djangorestframework-simplejwt, django-rest-framework, django-rest-auth, django-formset-js-improved, boto3 Successfully installed Django-3.2.7 Pillow-9.1.0 asgiref-3.5.0 boto3-1.20.26 botocore-1.23.54 certifi-2022.6.15 charset-normalizer-2.0.12 dj-database-url-0.5.0 django-auto-logout-0.5.0 django-ckeditor-6.0.0 django-ckeditor-5-0.1.6 django-crispy-forms-1.12.0 django-dotenv-1.4.2 django-environ-0.9.0 django-filter-21.1 django-formset-js-improved-0.5.0.2 django-heroku-0.3.1 django-jazzmin-2.4.8 django-jquery-js-3.1.1 django-js-asset-1.2.2 django-mailgun-provider-0.2.3 django-plaintext-password-0.1.0 django-rest-auth-0.9.5 django-rest-framework-0.1.0 django-social-share-2.2.1 django-static-fontawesome-5.14.0.0 django-storages-1.12.3 django-taggit-3.0.0 django-templated-mail-1.1.1 django-tinymce-3.4.0 django-widget-tweaks-1.4.8 djangorestframework-3.13.1 djangorestframework-simplejwt-5.2.0 djoser-2.0.5 gunicorn-20.0.4 idna-3.3 jmespath-0.10.0 lxml-4.6.2 oauthlib-3.2.0 psycopg2-2.8.6 psycopg2-binary-2.9.1 pyjwt-2.4.0 python-dateutil-2.8.2 python-decouple-3.5 python-http-client-3.3.7 pytz-2022.1 requests-2.27.1 requests-oauthlib-1.3.1 rjsmin-1.1.0 s3transfer-0.5.2 sendgrid-6.9.7 six-1.16.0 sqlparse-0.4.2 starkbank-ecdsa-2.0.3 uritemplate-4.1.1 urllib3-1.26.9 validate-email-1.3 whitenoise-5.2.0 -----> $ python manage.py collectstatic --noinput Traceback (most recent … -
Django For Loop with Javascript Math
I am trying to figure out how to run all my for loop values through this javascript math. For example, the individual value is a loop for all my inputs whereas the total value is fixed. Exp: Indivdual values are [10, 5, 20] and the total value is 100, I want the javascript to return 10/100, 5/100, and 20/100 to get pct's for each input. This is intended to fill out a table, so it should fill in each % in a table, for instance, the row "cookies" has 10% of total, the row "fish" has 5%, and the row "soup" has 20% of the total 100. Thanks. let securities_in_asset = document.getElementById("asset-size").innerText; securities_in_asset = parseInt(securities_in_asset) for(let i = 0; i < securities_in_asset; i++) { let PctOfPool = document.querySelectorAll(`[id^="pct-of-pool"]`)[i] let indiviudal_value = document.getElementById("individual-market value").innerText; let total_value = document.getElementById("total-market-value").innerText; let problemTypeChoice = 0; if (problemTypeChoice === 0) { PctOfPool.innerText = `${((parseInt(indiviudal_value) / parseInt(total_value)) * 100).toFixed(2)}%` } else { PctOfPool.innerText = 0 } } -
Access Token still working after network changed from local to server
I have same database for local and hosted site. So, I logged in from LOCALHOST and change my base URL to server URL still the older token is working and can access all of the things on hosted site as well. All of this is done in localhost. JWT Authentication settings.py INSTALLED_APPS = [ ... 'rest_framework_simplejwt.token_blacklist', ... ] REST_FRAMEWORK = { 'NON_FIELD_ERROR_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=12), 'REFRESH_TOKEN_LIFETIME': timedelta(days=3), } Backend in DRF Frontend React.js Note if you need more info just ask, i don't really have i any idea what might required for this question -
Initial data not working if I hide some one-to-many fields in django
I want to prefill some one to many fields and also hide these field because I want to avoid a scenario where a user can see all the records related to the fields. The problem I'm facing is when I use 'all' on the form fields I the initial data dictionary is working well, but if I try to use a list of the fields I want displayed, the initial data is not getting passed into the form. Here is my models.py class Agent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=15, null=True, blank=True,) surname = models.CharField(max_length=15, null=True, blank=True,) provcoord = models.ForeignKey(Provcoord, null=True, blank=True, on_delete=SET_NULL) regcoord = models.ForeignKey(Regcoord, null=True, blank=False, on_delete=SET_NULL) region = models.CharField(max_length=15, null=False, blank=True, choices=REGION) province = models.CharField(max_length=15, null=False, blank=False, choices=PROVINCE) id_no = id_no = models.CharField(max_length=10, null=False, blank=False, unique=True,) agent_no = models.CharField(default="Not Assigned", max_length=20, null=False, blank=False) address = models.TextField(null=False, blank=False) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) profile_pic = models.ImageField(upload_to="assets", default="default.png") is_blacklisted = models.BooleanField(default=False) reason_for_blacklist = models.TextField(max_length=500, null=True, blank=True) registered_at = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("agent", kwargs={'str' :str.id}) def __str__(self): return self.user.username class Adult(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=SET_NULL) regcoord = models.ForeignKey(Regcoord, null=True, blank=True, on_delete=SET_NULL) provcoord = … -
Object of type QuerySet is not JSON serializable Django JSON
Everything works until I try to Return JsonResponse I'm looping through the list, which contains usernames then passing those usernames to the models which return basic user information and storing those values in a variable which I later added to the list. def jsonresponse(request, username): Current_User = User.objects.get(username=username) #List of who this user follows followingList = Follower.objects.filter(follower=int(Current_User.id)) UsersInfo = [] for user in followingList: singleUser = User.objects.filter(username=user.following).values( 'username','bio', 'profile_image') UsersInfo.append(singleUser) results = User.objects.filter(username=Current_User).values( 'username','bio', 'profile_image') **This Works** return JsonResponse({'results':list(results), 'UsersInfo':list(UsersInfo)}) This works 'results':list(results), This doesn't 'UsersInfo':list(UsersInfo) print(results) gives me this: <QuerySet [{'username': 'John', 'bio': 'Hello, im new!', 'profile_image': 'images/ape_xhRtC2R.jpg'}]> print(UsersInfo) gives me this: [<QuerySet [{'username': 'Tristan', 'bio': 'Hello, im new!', 'profile_image': 'images/1-scary-tiger-head-robbybubble.jpg'}]>, <QuerySet [{'username': 'William', 'bio': 'Hello, im new!', 'profile_image': 'images/ape_PvPNwCP.jpg'}]>] Any help would really be appriciated -
No library found for Django + React Integrating Sign In With Google 2022 ( Google Identity Services )
For React there is a Library - React OAuth2 | Google For Django AllAuth library existed But after new update in Sign In With Google 2022 ( Google Identity Services ) AllAuth is not been Updated.. There is no other Libraries or easier documentation So please suggest me some Library for Django -
Django Dropdown GET Option Data
I wanted to get the selected text from the dropdown, But I am getting value if I use request.GET['Type']. I wanted to get Data001 instead of Value001 def index(request): print("The output: ",request.POST.get('Type')) return render(request,'index.html',content) <div class="form-row last"> <div class="form-wrapper"> <label for="">Meeting Type</label> <select id="Type" name="Type" class='form-control'> <option disabled="disabled" selected="selected">Choose option</option> <option value='Value001'>Data001</option> </select> </div> </div> <div class="form-wrapper"> <button data-text="Book" type="submit" name="action" value="book"> <span>Book</span> </button> </div> Please note that, There are 30+ dropdown options and I must use values in the dropdown. Kindly help me to get the selected option instead on value -
Use content_object to add an object instead of object_id, in generic relations
I have have a model(profile) which has generic relation with another model(member) in another app. when I want to add a new profile object I have to use object_id which is a field that shows the ID of that member object which has relation with this profile object. I want to use another field instead of that, for example, I have a content_object field that shows exactly the object itself. I Is there a way to use this field(content_object ) instead of object_id feild. profiling.models.Profile: class Profile(models.Model): #objects = ProfileManager() MAN = 'M' WOMAN = 'W' OTHER = 'O' GENDER_TYPE = [ (MAN, 'Man'), (WOMAN, 'Woman'), (OTHER,'Other'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=30) birthdate = models.DateField() gender = models.CharField(max_length=1,choices=GENDER_TYPE) address = models.TextField() profile_image = models.ImageField(null=True, blank=True) #to define generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(unique=True) content_object= GenericForeignKey() def __str__(self) : return f'{self.first_name} {self.last_name}' ticketing.models.Member: class Member(models.Model): username = models.CharField(max_length=100, unique=True) def __str__(self) -> str: return self.username class Meta: ordering = ['username'] -
django authenticaton - Is this a good practice?
Is this a good practice? models.py from django.contrib.auth.models import User User._meta.get_field('email')._unique = True User._meta.get_field('email').blank = False User._meta.get_field('email').null = False I want to make it happen, that every email is only used once and I found this code example on reddit. Should I instead create an AbstractUser or is that fine? Thanks -
Image is not loading in Django Template
I am having a Django HTML page. I would like to display an image in an HTML file. I am returning like this. in views.py params = { 'obj': obj, 'data':data, } return render_to_string('records/record.html', params), obj In html file <img src="{{data.image.path}}"> While logging what I am getting data.image.path like this https://document.s3.amazonaws.com/others/path/20220809-150420-Screenshot-%2897%29.png?Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=6037f61de9173fcf2a2b556ef81e But it replacing & to &amp in html. -
Django project foundation practices
I am planning to create a product(assume it to be similar to linkedin) and I want to understand what practices I should follow or keep in mind while developing this. I have seen projects in django/flask go messy very quickly. I know this is a very open-ended question but it would be helpful if someone can help me here. -
django how can I use multiprocessing in a management command
how can I use multiprocessing in a django management command? I can't figure out how to start the process inside of my websites django context management command users = users.objects.filter(is_active=True) with ProcessPoolExecutor(max_workers=5) as executor: processes = [] for user in users: p = executor.submit(complex_user_calculation,user) processes.append(p) for f in concurrent.futures.as_completed(processes): result = f.result() if result: print(result) when I run this management command I get this error raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ... File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 390, in __get_result raise self._exception concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending. -
How to display all child category from parent category in django-rest-framework
I'm trying to show my all children category from parent category. I want to just hit one API end and show all tables which is related to that item. I want to hit "Master-Category" and show all releated "Category","Sub-Category" and "Root-Item" in Hierarchy form. I display all the data but cannot in Hierarchy form. Can anyone please give me the solution for this problem. Model.py from django.db import models from django.contrib.auth.models import User class MasterCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default='') def __str__(self): return str(self.title) @property def category(self): data = NewCategory.objects.filter(master_category__id=self.id).values return data @property def sub_category(self): data = NewSubcategory.objects.filter(category__id=self.id).values return data @property def root_item(self): data = Rootitem.objects.filter(sub_category__id=self.id).values return data class NewCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") master_category = models.ForeignKey( MasterCategory, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.title) class NewSubcategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") category = models.ForeignKey(NewCategory, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.title) class Rootitem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") sub_category = models.ForeignKey(NewSubcategory, on_delete=models.CASCADE, null=True, blank=True) … -
How to handle this error when referring to an image?
Hey there I have a problem with my header images of my blog post. Every time the page refers to the image this error appears Here is my definition of the Post: class Post(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="Unique ID for this specific post across all blog post.", ) title = models.CharField(max_length=200, unique=True) caption = models.CharField(max_length=200, unique=True) category = models.IntegerField(choices=CATEGORY, default=1) header_image = models.ImageField(null=True, blank=True, upload_to="imgs/blog") author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) body = RichTextField(blank=True, null=True) created_on = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=STATUS, default=0) updated_on = models.DateTimeField(auto_now=True) context_object_name = "post_list" def __str__(self): return self.title def getCategoryStr(self): return CATEGORY[self.category][1] def save(self, *args, **kwargs): if self.status == 1 and self.created_on is None: self.created_on = timezone.now() super(Post, self).save(*args, **kwargs) can anybody please help me. Thank you a lot in advance! -
JQuery Ajax success function not able to access Django View jsonresponse from view
My View class MusicianLikesView(DetailView): model = Musician template_name = "guitar_blog/blog_detail.html" def post(self, request, **kwargs): song = self.get_object() user_id = request.user.id user_username = request.user.username if request.user.is_authenticated: if "Like1" in request.POST and user_username not in song.music_1_users.keys(): song.music_1_votes += 1 song.music_1_users[user_username] = user_id song.save() return JsonResponse({"likes": song.music_1_votes}) elif "Unlike1" in request.POST and user_username in song.music_1_users.keys(): song.music_1_votes -= 1 song.music_1_users.pop(user_username) song.save() return JsonResponse({"likes": song.music_1_votes}) My Urls path('ajax/', MusicianLikesView.as_view(), name="song_likes"), My Template <form method="post" class="voting-setup top_song"> {% csrf_token %} {% if user.get_username in musician.music_1_users %} <button name="Unlike1" type="submit" class="like-button"> <i class="fa-solid fa-guitar icon" ><span class="like-text">Unlike</span></i > </button> {% else %} <button name="Like1" type="submit" class="like-button"> <i class="fa-solid fa-guitar icon" ><span class="like-text">Like</span></i > </button> {% endif %} </form> <span class="after-like first_song_likes">Liked {{ musician.music_1_votes }}</span> My Javascript File $(document).on("submit", ".top_song", function (event) { event.preventDefault(); $.ajax({ type: "POST", url: "ajax/", data: { csrfmiddlewaretoken: "{{ csrf_token }}", }, success: function (response) { console.log(response); }, error: function (re) { console.log(re); } }); }); My Error in Console POST http://127.0.0.1:8000/guitar_blog/20/ajax/ 404 (Not Found) My Changes in View def musician_likes_view(request, pk): song = Musician.objects.get(pk=pk) user_id = request.user.id user_username = request.user.username if request.user.is_authenticated: if "Like1" in request.POST and user_username not in song.music_1_users.keys(): song.music_1_votes += 1 song.music_1_users[user_username] = user_id song.save() return HttpResponse(song.music_1_votes) elif "Unlike1" in … -
How to upload custom data (like Wave height, wind speed and etc) on Mapbox studio from our backend and show it on Flutter application
We are creating a mobile application in Flutter where we have to show ocean routes, wind speed and wave heights in the map with our own data. We explored MapBox documentation and we were not able to find an API which would upload all this data (wind speed, wave height, etc) to the mapbox studio template we created. We have our own database, what we want is to upload this data on the MapBox Studio and show it on our Mobile Application in Flutter. -
Display the history of an object in two apps together in django admin
I have two apps (profiling and ticketing) the ticketing app has three models in names of member,ticket,comment, and the profiling app has one model in name of profile. I do some changes on an profile object via profiling app it displays on profile model history but if I change that object via "inline" from another model the history displays on that model not profile model. I want that history will be displays completly in two models. -
how to set same unique primary key in each model of app according to user in django
i have used custom user model in my django app, first model which has been made by inheriting abstractbase user which i have rendered as a signup form, now i have created another model which i want to render after user signup in his/her profile, now i am stuck at how to assign same unique primary key in another model which i want to render after user signup, so i can access fields from both models. from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser,PermissionsMixin class jobglobeluserManager(BaseUserManager): use_in_migrations = True username = None def create_user(self, email=None, password=None, **extra_fields): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class jobglobeluser(AbstractBaseUser,PermissionsMixin): userid = models.AutoField(primary_key=True) joined_on = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) useris = models.CharField(max_length=30) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) email = models.CharField(unique=True,max_length=100) code = models.CharField(max_length=20) mobile = models.CharField(max_length=13) country = models.CharField(max_length=30) state = models.CharField(max_length=30) city = models.CharField(max_length=30) Gender = models.CharField(max_length=20) password = models.CharField(max_length=20) password2 = models.CharField(max_length=20) resume = … -
Trouble getting a Django Form to render
Wondered if someone could help me with what I am doing wrong. I wish to present an order form in Django where a customer will only ever fill in an order, they will never need to retrieve an existing order. So I think I only need a POST method and no GET method. When I try to render a url with a form, I get a 405 response. In my views.py file where I think I am making a mistake I have: class RequestReport(View): def post(self, request, *args, **kwargs): form = CustomerOrderForm(data=request.POST) if form.is_valid(): form.save() return render( "order.html", { "form": CustomerOrderForm() } ) And in my app urls file I have: urlpatterns = [ path('', views.RequestHome.as_view(), name='home'), path('order', views.RequestReport.as_view(), name='order'), path('blog', views.RequestBlog.as_view(), name='blog'), path('<slug:slug>/', views.PostDetail.as_view(), name='post-detail'), ] And finally in my order.html file I have: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" class="report-buttons"> </form> I know that the Customer Order Form is fine because if I insert this in my view it renders correctly class RequestReport(CreateView): form_class = CustomerOrderForm template_name = 'order.html' success_url = "about" but I want to be able to post the form. Appreciate any help.