Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/cardamageapp.git'
I followed the exact steps as mentioned in the article 'https://medium.com/bithubph/how-to-deploy-your-django-applications-on-heroku-8b58fdb09dd0', while deploying my django project to heroku. However, I am getting the following error: [git push heroku master][1] Please could anyone let me know what could be the possible issue. FYI: I have the Procfile, requirements.txt, runtime.txt in my project root directory. I am also sure my credentials are correct. Also, I havnt pushed anything to master before and I am the only owner of this app. My runtime.txt has the code: python: 3.7.9. My Procfile has the code: web: gunicorn cardamage.wsgi --log-file - My requirements.txt: absl-py==0.12.0 astunparse==1.6.3 cachetools==4.2.1 certifi==2020.12.5 chardet==4.0.0 cycler==0.10.0 dj-database-url==0.5.0 Django==1.10 django-heroku==0.3.1 gast==0.3.3 google-auth==1.28.0 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 grpcio==1.36.1 gunicorn==20.1.0 h5py==2.10.0 idna==2.10 importlib-metadata==3.10.0 joblib==1.0.1 Keras==2.4.0 Keras-Applications==1.0.8 Keras-Preprocessing==1.1.2 kiwisolver==1.3.1 Markdown==3.3.4 matplotlib==3.4.1 numpy==1.20.2 oauthlib==3.1.0 opt-einsum==3.3.0 pandas==1.1.5 pickle5==0.0.11 Pillow==8.2.0 protobuf==3.15.7 psycopg2==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2021.1 PyYAML==5.4.1 requests==2.25.1 requests-oauthlib==1.3.0 rsa==4.7.2 scikit-learn==0.24.1 scipy==1.4.1 seaborn==0.11.1 six==1.15.0 tensorboard==2.2.2 tensorboard-plugin-wit==1.8.0 tensorflow==2.2.0 tensorflow-estimator==2.2.0 termcolor==1.1.0 threadpoolctl==2.1.0 typing-extensions==3.7.4.3 urllib3==1.26.4 Werkzeug==1.0.1 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.4.1 -
python django prefetch_related on form set and inlineformset_factory
Hi folks I have a forms.inlineformset_factory with 50 extra rows. It is taking forever to load and getting 204 queries are running to get that data with almost 200 duplicate queries how do I get prefetch_related in the forms.inlineformset_factory here is the code from forms.py AddReceipeDetailFormSet = forms.inlineformset_factory( ReceipeMaster, ReceipeDetail, fields=( 'item_type', 'item', 'quantity'), extra=50, widgets={ 'item_type': forms.Select(attrs={'class': 'form-control'}), 'item': forms.Select(attrs={'class': 'form-control'}), 'quantity': forms.NumberInput(attrs={'class': 'form-control'}), } ) Here is my view from views.py def create_receipe(request): child_forms = AddReceipeDetailFormSet(request.POST or None) parent_form = ReceipeCreateForm(request.POST or None) context = {'parent_form': parent_form, 'child_forms': child_forms} if request.method == 'POST': if parent_form.is_valid(): print('parent form is valid') else: print('invalid parent form', parent_form.errors) if child_forms.is_valid(): print('child form is valid') else: print('invalid child form', child_forms.errors) print("post request is received***", request.POST) return render(request, 'receipes/create.html', context=context) regards -
If block not being evaluated in templates
I am trying to render a list of items using ListView like so: views.py class EventView(generic.ListView): model = Event template_name = 'timer/index.html' def get_queryset(self): events = Event.objects.order_by('-day')[:7] return events events is then passed to index.html like so: index.html {% block content %} {% if events %} <ul> {% for event in events %} <li><a href="{% url 'timer:detail' event.id %}"></a>>{{ event }}</a></li> {% endfor %} </ul> {% else %} No events to show {% endif %} {% endblock %} The challenge is that the else block is always returned. I made sure that I have objects in my db and they are never returned. What am I doing wrongly? -
django.jQuery is not a function
I am using redis cache and select2 with settings like this: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': [env('REDIS_URL', default="redis://127.0.0.1:6379"), env('REDIS_REPLICA_URL', default="redis://127.0.0.1:6379")], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'IGNORE_EXCEPTIONS': True } }, 'select2': { 'BACKEND': 'django_redis.cache.RedisCache', # 'LOCATION': 'redis://127.0.0.1:6379/2', 'LOCATION': env('SELECT2_CACHE_URL', default='redis://127.0.0.1:6379/2'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'IGNORE_EXCEPTIONS': True, 'MAX_ENTRIES': 10000 }, 'TIMEOUT': 60*30 } } Error found is this : Not Found: /select2/fields/auto.json on the python debugger console When I do inspect element in the browser I get: 1. django_admin_hstore_widget.js:171 Uncaught TypeError: django.jQuery is not a function at django_admin_hstore_widget.js:171 2. jquery.js:10099 GET http://localhost:8000/select2/fields/auto.json?field_id=IjE0ZjIxNjE2LWIxNTgtNDUxYi05NWEzLTM4YmQ1NzBjYzQyOSI%3A1lTKnr%3A8caHvDkhDEVA4bOSFOfsaVaxqQs Basically select2 is unable to load results wherever it is used in the code. -
Django Wagtail - How to set the date format?
I have created a Blog with the Django CMS "Wagtail". As a part of a blog page, I want to set a date in a specific format. Now, setting the date itself is not a problem at all. The blog page is constructed a bit like this: date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) author = models.ForeignKey(BlogAuthor, on_delete=models.PROTECT, null=True) ... The DateField then creates a date on my blog page in the format "April 2, 2021". Alas, as we are located in Germany I'd like to change this format to "2. April 2021". I was searching a lot whether it would be feasible to add a parameter to the DateField in order to define the format. Didn't find anything that worked so far. Any ideas? Thanks in advance! Timo -
Django Model save methode
I trying to add a save method for an model: def save(self, *args, **kwargs): if self.Position: ProductImages.objects.filter(Position=self.Position, ProductID=self.ProductID).update( Position=self.Position+1) It is working fine, but if I have an Image in Position 1 and one in 2 and add another in Position 1 then I have 2 times Images in Position 2. Is there an uncomplicated way to check all Positions with the ProductID? -
How to use sqlite3 database with Django on Kuberenets pod
I am having one python-django project which consist of sqlite3 database, I am deploying it on Kubernetes pod, wanted to know how to access the sqlite3 database, once I deploy the app on Kubernetes. Generally If I was using postgres or mysql, I would have created another pod and then expose my services, not sure for sqlite3 database. How to access it and use the database, or I have to create a new pod for sqlite3? Dockerfile for my Django app: FROM python:3.4 RUN apt-get update \ && apt-get install -y --no-install-recommends \ sqlite3 \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
How to achieve Asynchronous I/O in python2.7?
I have my project running in django1.1, how to implement async support for one of the methods which involves call made to db, I want to optimize it. I have gone through tornado library but I am not sure how to implement / use it with django1.1. Please suggest if there is any other library to achieve async support and how to use tornado with django -
Errors during configuration of the neo4j django-neomodel
I'm trying to do a simple project in Django using the Neo4j database. I've installed a django-neomodel library, set the settings as follows: import os from neomodel import config db_username = os.environ.get('NEO4J_USERNAME') db_password = os.environ.get('NEO4J_PASSWORD') config.DATABASE_URL = f'bolt://{db_username}:{db_password}@localhost:7687' created a model: class Task(StructuredNode): id = UniqueIdProperty() title = StringProperty() added 'django_neomodel' to INSTALLED_APPS, removed the default database configuration and when I try to enter the website it raises the error: ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.. It's the only error because after running the python manage.py install_labels command it raises: ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error)) neo4j.exceptions.ServiceUnavailable: Failed to establish connection to IPv6Address(('::1', 7687, 0, 0)) (reason [Errno 99] Cannot assign requested address). I'm pretty sure that the database works correctly because as you see I can access this. screenshot docker-compose: version: "3.9" services: api: container_name: mm_backend build: context: ./ dockerfile: Dockerfile.dev command: pipenv run python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/mm_backend ports: - 8000:8000 env_file: .env depends_on: - db db: container_name: mm_db image: neo4j:4.1 restart: unless-stopped ports: - "7474:7474" - "7687:7687" volumes: - ./db/data:/data - ./db/logs:/logs -
When i am trying to upload file its showing FieldFile is not JSON serializable - Django
TypeError at /web/ticketcreation/ Object of type FieldFile is not JSON serializable here is my models.py class Ticket(models.Model): Email=models.CharField(max_length=60) to=models.CharField(max_length=60) cc=models.CharField(max_length=60) subject=models.CharField(max_length=25) module = models.CharField(max_length=25) priority = models.CharField(max_length=25,null=True) message = models.CharField(max_length=70) choosefile = models.FileField(null=True, blank=True) -
How to make a blogpost model in Django?
I am trying to make a website and I want to add blogs and articles to my website using the admin page. How do I make a model that takes both text and the images I want after every paragraph in my article? If that's not possible how do I input both separately and render it in the correct order together? -
How to get the uploaded file content in json format using django rest framework?
Hi I was trying to get the get the uploaded file content in json format as response ( not file details) Upto now I did the upload of file using django rest framework which I did mention in my previous question “detail”: “Method \”GET\“ not allowed.” Django Rest Framework now I am getting the json response as follows in the given picture link https://ibb.co/wzTmG6W please help me thanks in advance -
Compare two text files to show changes made like in version control systems in python
Background: I'm trying to make a VCS for text articles using django as a learning project, like so, where anyone can edit an article and the changes made can be displayed on the site. Till now I've only found the difflib module. I've copied and tried code from here. import difflib lines1 = ''' How to Write a Blog Post This is an extra sentence '''.strip().splitlines() lines2 = ''' How to Write a Blog Post '''.strip().splitlines() for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0): print (line) It outputs the following: --- file1 +++ file2 @@ -2 +1,0 @@ -This is an extra sentence But this code only shows the differences between two files and even in that it won't show differences properly if for example words or letters in a line are edited. Is there a python library/module which can help show the changes made to the file or even the differences between any two edits? -
How to calculate the price of Order using (sum of) OrderItems prices in django rest framework
I am able to calculate the OrderItem model prices using @property decorator but unable to calculate the total price of the Order model while creating the order object. When I called the post api for creating the orde, there is no error but I am not getting total_price in the api response. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) #logic to calculate the total_price, and its not working @property def total_price(self): return sum([_.price for _ in self.order_items_set.all()]) #realted name is order_items def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') #Logic to calculate the total_item_price, it works. @property def price(self): total_item_price = self.quantity * self.order_variants.price return total_item_price My serializers: Class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) #price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) # total_price … -
How to make Django link to different html pages based on the result of a form?
I am confused on how to change html pages based on the results of a form. I want to create a form to get a search query. Based on this query, a page should be rendered to the user. For example, if the page query is chocolate, then a page should be main/chocolate. Same for any other query: main/"query". How is it possible to do this? I have tried using a normal form in order to do this, but this did not work. I have tried: this is from views.py: if request.method == "GET": ask = NewForm(request.GET) if ask.is_valid: Muk = ask.cleaned_data("Stuff") result = util.get_entry(Muk) good = markdown2.markdown(result) return page(request, good) else: return render(request, "encyclopedia/index.html") return render(request, "encyclopedia/layout.html", { "form": ask })``` And it always meets me with an error page, since earlier in views.py, I defined: def page(request, name): ```stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })def page(request, name): stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })``` -
How to count and make addition with for loop with a table in Django?
I created a customer system. In this system, a user has several customers. I have a Customer model and this model has multiple fields like risk_rating, credit_limit, country, etc... I want to list the countries where customers are located and show data about them in a data table. I am using .distinct() method for that, but I cannot figure out how can I show some data. For example, I want to total credit_limit (adding operation) in the related country and I want to count all customers that have Low risk risk_rating. I can do this the long way with if statement. But I can't think of anything other than just creating a concatenated if statement for all countries. This would be a very long and inefficient way. Because there are 208 countries in the world. How can I do that? Note: I try to use for loop counter for counting the number of risks but it did not work properly. models.py class Customer(models.Model): RISK_RATING = [ ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk', 'Moderately High Risk'), ... ] customer_name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) credit_limit = models.FloatField(default=0, null=True) risk_rating = models.CharField(max_length=50, default='Select', choices=RISK_RATING, … -
Django suddenly gives me error that Apps aren't loaded yet
I am using Django3.1. All was working fine. I pip installed a new app and tried to run makemigrations. It suddenly doesn't work anymore. I get error 'Apps are not loaded yet'. I thought it was the app. Uninstalled it. Didn't work. Deleted the virtualenv directory. Created new one and installed all apps again except the last one. It didn't work. I had installed another version of Postgres and hadn't restarted my computer since then. Restarted but didn't work. Tested by running another project to make sure it was not new Postgres issue. That worked as expected. Commented out my url confs and installed apps in the settings.py. But still the same error. Tried multiple SO suggestion related to this error but nothing works. Can anyone please help. Error from console: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\translation.py", line 60, … -
Why are there so many ways in doing the same thing in Python Script Commands in calling dependencies?
Forgive me because I came from Laravel 8 (to be specific) I am still a newbie in Django and in Python in general because I want to learn both at the same time because I always see in social media sites that they're always marketing python hence a trending language nowadays and I like to be a web developer so I also want to learn Django like i did with php, javascript, css-pre-processors, vue and react alll inside of the Laravel Ecosystem Like for example I just discovered you can do this but on a different command call of dependency libraries and I am confuse both the py and python starting commands in calling and importing python scripts and is there going to be some slight sort of technical issues Example 1: Via Package Manager Installation of the Django Web Framework and additional Parameters @MINGW64 ~/backend Opt1: pip install django djangorestframework django-cors-headers Opt2: py -m pip install Django djangorestframework django-cors-headers Opt3: python -m pip install django gunicorn psycopg2-binary Opt4: py -3 -m pip install Django djangorestframework django-cors-headers Example 2: And in testing and running the server (venv)@MINGW64 ~/backend/djangoreactProj Opt1: py -m manage runserver 0.0.0.0:5000 Opt2: py -3 -m manage runserver … -
enable/disable password protection for website
I want to give my client the option to enable/disable password protection on their website through a admin panel kind of like how Shopify does it. first question would be is this option available in any existing headless cms. if not can this be done with my own custom cms using Django or a different backend framework? i'v looked around for resources but can't seem to find anything so any advice/resources would be appreciated note will be built in react -
“detail”: “Method \”GET\“ not allowed.” Django Rest Framework
I know this question was duplicate I am beginner in django I tried in all ways but not able to find solution I was trying to upload a file and get a json response as ok using django rest framework So far I tried is views.py: from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: from django.conf.urls import url from .views import FileView urlpatterns = [ url(r'^upload/$', FileView.as_view(), name='file-upload'), url(r'^upload/<int:pk>/$', FileView.as_view(), name='file-upload'), ] The error is: Method /GET/ is not allowed please help me thanks in advance -
Code works locally but not on the server (Django, Opencv)
I'm trying to convert the image and save it in the static folder temporarily by using the cv2.imwrite function, but I'm getting an error that says No such file or directory: './static/images/0.png' (In order to convert the image, I had to save images temporarily). It works locally but not on the server. What am I supposed to do? class Article(models.Model): writer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='article', null=True) project = models.ForeignKey(Project, on_delete=models.SET_NULL, related_name='article', null=True) title = models.CharField(max_length=200, null =True) image = models.ImageField(upload_to='article/', null=True, blank=True) image_converted = models.ImageField(upload_to='article/converted/', null=True, blank=True) style = models.CharField(max_length = 50, blank = True, null=True, choices=ACTION_CHOICES) content = models.TextField(null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) def convert_image(self, *args, **kwargs): image_converted = convert_rbk(self.image, self.style) self.image_converted = InMemoryUploadedFile(file=image_converted, field_name="ImageField", name=self.image.name, content_type='image/png', size=sys.getsizeof(image_converted), charset=None) def convert_rbk(img, style): if style == "HAYAO": img = Image.open(img) img = img.convert('RGB') img = ImageOps.exif_transpose(img) img.save("./static/images/0.png") model = Transformer() model.load_state_dict(torch.load('pretrained_model/Hayao_net_G_float.pth')) model.eval() img_size = 450 img = cv2.imread('./static/images/0.png') T = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size, 2), transforms.ToTensor() ]) img_input = T(img).unsqueeze(0) img_input = -1 + 2 * img_input img_output = model(img_input) img_output = (img_output.squeeze().detach().numpy() + 1.) /2. img_output = img_output.transpose([1,2,0]) img_output = cv2.convertScaleAbs(img_output, alpha = (255.0)) cv2.imwrite('./static/images/1.png', img_output) result_image = "./static/images/2.png" cmd_rembg = "cat " + "./static/images/0.png" + " … -
How to add one to one unique relationship between multiple models in django?
class User(models.Model): # User's fields such as username, email etc class Agent(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Seller(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Buyer(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields Here I have one custom User model and 3 different models, Agent, Seller, Buyer, so the relationship must be one-directional from user to any of the 3 models. Suppose I have a user User1, he can be either an agent or a buyer or a seller, he cannot be both a buyer and seller. So for instance, User1 is a buyer, after creating an object of the Buyer model with User1, User1 cannot be used to create Seller object or ``Agent` object How can I do that? -
How to render html file in Django
In my views.py from django.shortcuts import render def home(request): return render(request, "app/base.html") In my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="Home") ] I'm so confuse, it is not working -
To test a POST request for an authenticated route in Django Rest Framework
I want to test a post request for a route with authentication required(Knox from Django Rest Framework). Here the post request should object for a logged in user. Following is urls.py path('cards', addCard.as_view(), name="cards"), Following is addCard view class addCard(generics.ListCreateAPIView): serializer_class = CardSerializer permission_classes = [permissions.IsAuthenticated, IsOwnerOrNot] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) card = serializer.save(owner=self.request.user) return Response({'card': CardSerializer(card, context=self.get_serializer_context()).data,}) def get_queryset(self): return self.request.user.cards.order_by('-id') Following is the test case, I used this answer, I got 401!=201 error, clearly Unauthorized user. class addCardAPIViewTestCase(APITestCase): url = reverse("cards") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = get_user_model().objects.create_user(self.username, self.password) self.token = Token.objects.create(user=self.user) def test_create_cards(self): client = APIClient() client.login(username=self.username, password=self.password) client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = client.post(self.url,{ "bank": "Citibank", "card_number": "5618073505538298", "owner_name": "c1", "cvv": "121", "expiry_date_month": "03", "expiry_date_year": "2023" },format='json') self.assertEqual(response.status_code, 201) -
Django allauth with custom fields in User Moel
I am trying to use Django All Auth for login and signup using custom User Model and Form. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True,default=create_new_ref_number()) country_code = models.IntegerField(default='91') two_factor_auth = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'teacher'), (3, 'unassigned'), (4, 'teacherAdmin'), (5, 'systemadmin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,default=3) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name', 'phone_number', 'country_code'] I am not sure how or where should I get phone_number from users who are signing up. Since the field is required and unique, I am using random number to temporarily have some value. Please suggest.