Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I write the full python venv path to be able to run manage.py
I have a problem in the virtual environment with django manage.py I use git bash terminal. and when I activate my venve like this : source explorer/Scripts/activate I successfully activate the environment (explorer text above command line appears) , but still the terminal is pointing to the C:/python37/python.exe path When i run : python manage.py runserver I receive this error : $ python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' but when I type the absolute path to python.exe inside my virtual environment as follows : /explorer/Scripts/python.exe manage.py runserver , it works fine I should be just activating the environment and then typing the python manage.py runserver and it should be working Thanks in advance -
How to display RabbitMQ messages dynamically in HTML (frontend)?
I try to pass variables coming from RabbitMQ and display them in the frontend in my Django project. I am using HTML. I can send the messages and receive them in backend and I can display them in console. But I try to display them in the frontend. How can I do that? functions.py def send_message(text): credentials = pika.PlainCredentials('username', 'pass') parameters = pika.ConnectionParameters('ip', 5672, '/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body=text) print(" [x] Sent 'Hello World!'") connection.close() class my_class(): def __init__(self, ...) send_message("Downloading...") self.download_all() ... def download_all(self, ...) ... var = "" arr_length = len(scans) for s in scans: i = 1 var = "Progress = " + str(i) + "/" + str(arr_length) send_message(var) i += 1 views.py def setup_wizard(request): functions.my_class(...) return render(request, 'setup_wizard.html', context) Note: Celery don't work for us. -
How to access query parameter in serializer django rest framework
I am trying to access query parameter in the serializer. I am not sure what I am doing wrong, I tried to follow a few solution. class MyViewSet(viewsets.ModelViewSet): ....... serializer_class = MySerializer def get_serializer_context(self): context = super().get_serializer_context() context['test'] = "something" return context In my Serializer, class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): print(self.context['test']) return self.context['test'] I am getting this error, Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'test' Interestingly, I can see it can print the value in console and then the exception. I also tried to directly access the request variable like class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['request'].query_params['page'] But its showing the same error Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'request' Any suggestions? Thanks in advance. -
take screenshot from a website and return token screenshot as httpsresponse for download in django
i want to take a screenshot from a website and return token screenshot as https for download. I am using Html2Image lib. i am tring this code: def certification1(request, *args, **kwargs): hti = Html2Image() image = hti.screenshot(url='https://www.python.org', save_as='screenshot.png') response = HttpResponse(image, content_type='png') return response but it return url of saved image. like this enter image description here how can i return token image for download? -
Django case insensitive unique constraint
I want my charField to be case-insensitively unique, but I don't want to store everything lower or upper cased. Existing solutions suggest CITextField or checking for uniqueness in the form, but I thought I should be able to do it with a UniqueConstraint, specially with Django 4.0 UniqueConstrain expressions new feature. But with these code: class Tag(models.Model): title = models.CharField(max_length=24, unique=True) ... class Meta: ordering = ['title'] constraints = [ models.UniqueConstraint( Lower('title'), name='unique case insensitive title' ), ] I get this error when running migrate command. (makemigrations works fine) ... File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 282, in _remake_table self.create_model(new_model) File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 353, in create_model sql, params = self.table_sql(model) File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 202, in table_sql constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints] File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 202, in <listcomp> constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/constraints.py", line 188, in constraint_sql fields = [model._meta.get_field(field_name) for field_name in self.fields] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/constraints.py", line 188, in <listcomp> fields = [model._meta.get_field(field_name) for field_name in self.fields] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: NewTag has no field named 'Lower(F(title))' What I'm doing wrong? Is it possible to set case-insensitive uniqueness on model level in Django … -
How do I modify djoser account verification system
Here's my custom user model: class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_verif = models.BooleanField(default=) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["firstname", "lastname"] objects = AccountManager() def __str__(self): return self.email @property def is_staff(self): return self.is_superuser @property def is_admin(self): return self.is_superuser def has_perm(*args, **kwargs): return True def has_module_perms(*args, **kwargs): return True So right now I have a standard djoser account verification system. So I'm unable to login with unverified user because the is_active field is set to False. Where and how do I modify the code so that every time I verify an account it checks the is_verif field instead of the is_active and the is_active field is always set to True ? Thank you -
Background-color of AutocompleteSelect field not working
I want to set the background-color of a AutocompleteSelect field. When the page loads, the background-color is set, but will be overwritten immediatelly. Code of the form: class ProjectLineAdminForm(forms.ModelForm): work_type = forms.ModelChoiceField( WorkType.objects.all(), widget=AutocompleteSelect(ProjectLine._meta.get_field('work_type'), admin.site), ) def __init__(self, *args, **kwargs): super(ProjectLineAdminForm, self).__init__(*args, **kwargs) # Set background colors of worktype if self.instance.work_type: if self.instance.work_type.code == 'JOHN': self.fields['work_type'].widget.attrs.update({'style': 'width:110px; background-color: red'}) Code of the Inline class: class ProjectLineInline(admin.TabularInline): model = ProjectLine fields = ("work_type",) form = ProjectLineAdminForm I don't have this problem with other fields. -
Getting SystemError: unknown opcode error with LIME explain_instance
I have dump the LIME LimeTabularExplainer using Jupyter Notebook with dill. While I am able to unpack it but I am not able to use it in the .py file in django app to deploy the model. #unpack the LimeTabularExplainer with open('Resources/CLS_explainer.pkl', 'rb') as f: explainer = dill.load(f) #use the explainer exp = explainer.explain_instance(data_row = ts[0], predict_fn=self.model.predict_proba) And Below is the error: XXX lineno: 72, opcode: 160 Internal Server Error: /customerlead Traceback (most recent call last): File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\repo\test\mio\CustomerLeadScore\views.py", line 28, in post score= obj.predict(data) File "C:\repo\test\mio\Services\CustomerLeadScore.py", line 48, in predict exp = explainer.explain_instance(ts[0], predict_fn) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ lime\lime_tabular.py", line 340, in explain_instance data, inverse = self.__data_inverse(data_row, num_samples) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ lime\lime_tabular.py", line 537, in __data_inverse first_row = self.discretizer.discretize(data_row) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ … -
Create a Model instance when a button is clicked (One-to-Many)
I would like to create a Bid for a project when I click the "Bid" button in my template. How do I go about this. see the below example models.py class Project(models.Model): academic_level = models.CharField(max_length=20, choices=ACADEMICS_LEVEL) type_of_paper = models.CharField(max_length=50, choices=TYPE_OF_PAPER) subject_area = models.CharField(max_length=50, choices=SUBJECT_CHOICES) title = models.CharField(max_length=250) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("project_detail", kwargs={ "slug": self.slug }) class Bid(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) made_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) date = models.DateField(auto_now_add=True) def __str__(self): return self.project.title views.py class ProjectDetailView(LoginRequiredMixin, DetailView): model = Project def create_bid(self, request): if request.method =="POST": try: project = self.instance made_by = request.user bid = Bid.objects.create(project=project, made_by=made_by) bid.save() messages.success( request, "Bid sent sucessfully! Wait for feedback from the project owner on the Bids Tab") except: messages.error(request, 'cannot send multiple bids for one project') return render(request, 'users/project_detail.html') the Bid button is found in the project_detail template. How do I check for event and how do I get the current project instance in the Detailview above? Thanks in advance -
Access to XMLHttpRequest at 'http://127.0.0.1:8000/login/' from origin 'http://localhost:3000' has been blocked by CORS policy
full error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. settings.py: CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOW_HEADERS = ['*'] INSTALLED_APPS = [ 'django_debugger', 'django_extensions', 'corsheaders', 'rest_framework', 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] in react (frontend side): function Login(){ const [login,setLogin] = useState({ email: '', password:'' }); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/',login, {withCredentials:true}) } my authentication method is using sessions, I am not sure how to fix this CORS problem -
Screenshot of web and return image as http response for download in django
I am tring to take screenshot from a website and return token screenshot. I am using this code. My code But it return the token screenshot. Like this enter image description here How can i return token screenshot as httpresponse? -
get data from ManyToMany field django
How do I use product.title in tag view ? something like this t = Tag.products.title Models.py class Tag(models.Model): title = models.CharField(max_length=120) slug = models.SlugField( blank=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class products(models.Model): title = models.CharField(max_length=150) description = models.TextField() price = models.IntegerField() tag = models.ManyToManyField(Tag, blank=True) -
i am using django 4.0 and want to add templates in setting file i wrote a code TEMPLATE_DIRS =BASE_DIR/'templates'
using django 4.0 it shows error like this raise TypeError('Invalid path type: %s' % type(value).name) File "", line 783, in exec_module TypeError: Invalid path type: tuple -
How to remove fields from user creation form in django
I am creating an app in django with postgressql. So I am creating my custom user model with own fields.BUt when I go to my database their are many fields like first name , last name, id. I dont want to see those field, I only want to see the fields that I am writing in my custom model. -
Django session authentication with React
This is not a coding question, rather a general question: in Django, if I am using default authentication (session authentication in that case), what does the frontend (in my case it is react) need in this case? lets say i log in on browser (login button from frontend side), now it is gonna send username and password data to django, django going to deserialize the data and then authenticate and login, now the problem here is that i redirect to another page where only authenticated users are able to view, the problem is that i cant view it, simply because Django identify me as un-authenticated, after bit of research the answer was because each end (frontend and backend) have different ports, in order to make it work the frontend need to access cookies i assume, is there any simple example to this problem? -
we can i solve [error: open("venv/bin/python"): Invalid argument fatal: Unable to process path venv/bin/python] this problem?
I create a virtual environment and i want to push this in my github but i could not. picture is below. -
Django project not starting
I am using the command django-admin startproject api_practice to start a new django project and getting the following errors - Traceback (most recent call last): File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\Farhan\AppData\Local\Programs\Python\Python39-32\Scripts\django-admin.exe\__main__.py", line 7, in File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle('project', project_name, target, **options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\templates.py", line 114, in handle django.setup() File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\__init__.py", line 1, in from .base import ( File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\http\__init__.py", line 5, in from django.http.response import ( File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\http\response.py", line 16, in from django.core.serializers.json import DjangoJSONEncoder File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\serializers\__init__.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\serializers\base.py", line 7, in from django.db import models File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\__init__.py", line 3, in from django.db.models.aggregates import * # NOQA File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\expressions.py", line 10, in from … -
ProgrammingError at /sign-up/
i recently deplolyed my todoapp on heroku and it works just fine, at least until i try creating an account then it prompts me with this error: relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."username i'm so confused ive tried so many things i.e Heroku app python manage.py makemigrations i get an error something about id not found. is there anythin i can do? my register view def register(request): if request.user.is_authenticated: return redirect('home') form = registerform() if request.method == 'POST': form = registerform(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'User does not exist') return render(request, 'register.html', {'form' : form}) forms.py class registerform(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] -
Best way at add date time stamp in directory of django image field
Till now i was using this function def user_compressed_path(instance, filename): profile_pic_name = 'user/{0}/compressed/profile.jpg'.format(instance.id) full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name) if os.path.exists(full_path): os.remove(full_path) return profile_pic_name def user_picture_path(instance, filename): profile_pic_name = 'user/{0}/picture/profile.jpg'.format(instance.id) full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name) if os.path.exists(full_path): os.remove(full_path) return profile_pic_name i want path something like 'user/{0}/compressed/{1}/profile.jpg'.format(instance.id, date_time_stamp) 'user/{0}/picture/{1}/profile.jpg'.format(instance.id, date_time_stamp) what should be the value of date_time_stamp -
How do I refactor my Purchase and Sales models by the method of DRY
I am making a Medical Billing Application with the Django framework but my models need refactoring so that they can work on the principle of DRY(Don't Repeat Yourself). Please help me out with this! Here are the files: models.py(Medicines Model) #------------------------Medicine models---------------------------------- gst = ( (0, '0%'), (5, '5%'), (12, '12%'), (18, '18%'), ) # Create your models here. class Medicines(models.Model): Med_HSN = models.IntegerField(default=0) Med_name = models.CharField(max_length=20) Med_Quantity = models.PositiveIntegerField(default=0) Med_Manufacturer = models.CharField(blank=True,max_length=50) Med_Expiry = models.CharField(default=1,max_length=10) Med_Batch_no = models.CharField(blank=True,max_length=15) Med_MRP = models.FloatField(blank=False) Med_Rate = models.FloatField(blank=False) Med_GST = models.IntegerField(default=0,choices=gst) date_created = models.DateField(default=timezone.now) def caluclate_value(self): value = self.Med_MRP * (self.Med_GST/100) total_value = self.Med_MRP + value return total_value def get_cost(self): return self.caluclate_value() * self.Med_Quantity def __str__(self): return self.Med_name + " | " + str(self.caluclate_value()) + " || Quantity in Stock : " + str(self.Med_Quantity) #----------------------------------End Medicines Models-------------------------------------- models.py(Sales Model) #---------------------------------Sales Models-------------------------------- from django.core.checks import messages from django.db import models from Customer.models import Customer from django.utils import timezone import math payment_status = ( ('Due', 'Due'), ('Paid|Cash', 'Paid|Cash'), ('Paid|Cheque', 'Paid|Cheque'), ('Paid|Online', 'Paid|Online'), ('Cancelled','Cancelled') ) dis = ( (0, '0%'), (5, '5%'), (10, '10%'), (15, '15%'), (20, '20%'), ) # Create your models here. class Sales(models.Model): # sales_id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customer,on_delete=models.CASCADE) prescribed_doctor = models.CharField(blank=True,max_length=150) … -
django error where even though i allowed an attribute in url it isn't working
path('', views.index, name='index') above code works when url: ...8000/app path('<str:name>', views.index, name='index') but this doesn't work when url: ...8000/app/kenny gives page not found error does anyone why it is working with no attributes but not with attributes. Same for other paths also. -
how do i wrtite django fbv to class based view
I have two user types a and b i need to write the below fbv into class based Logoutview(auth.view) how do i write the below fbv to cbv views.py @login_required def logout(request): if request.user.usertype_a: logout(request) return redirect(reverse('user_a_login')) else: logout(request) return redirect(reverse('user_b_login')) -
No value returned in django powered HTML
Looked for the solution for almost 2 days without luck - any guidance is much appreciated. Given 'views.py' looks like this (all needed lib are imported properly): class HomeView(generic.TemplateView): template_name = 'polls/djIndex.html' def test(request): data = {'temperature': '53F', 'state': 'NY', 'mood': ['good', 'bad'] return render(request, 'polls/djIndex.html',{'data':data}) These are not working (no value returned) on djIndex.html: test #1: {% for key, value in data.items %} <h3>{{key}}-----: {{value}}</h3> {% endfor %} test #2: {% for key in data.items %} <p>Value of Key 1 : data["key1"]</p> {% endfor %} test #3 {% for key, value in data %} <p>Key {{ key }}, Value {{ value }}</p> {% endfor %} test #4 <h2> context2: {{data.temperature}}</h2> But these are working on djIndex.html: <h2> Temperature: {{temperature}}</h2> <h2> State: {{state}}</h2> <h2> Mood: {{mood}}</h2> Ask: How to make those non-working test #1-#4 to work on my HTML page. Am I doing something wrong in my djano config, as some of those test #1-#4 are accepted answers in some forums in different instances? -
Multiselect dropdown is not working correctly with django-ajax call?
<form method="POST" data-attributevalue-url="{% url 'vendor:ajax_load_attributes_values' %}"> <div class="d-flex ms-4"> <div class="col-lg-8"> {{ productform.attributes|as_crispy_field }} --dropdown select field <select class="form-control" multiple aria-label="size 3 select example" required name="attribute_values" id="id_attribute_values"> <option value="">----</option> </select> </div> </div> </form> <script> //attribute_values category filter $("#id_attributes").change(function () { var url = $("#productForm").attr("data-attributevalue-url"); var attributeId = $(this).val(); $.ajax({ url: url, data: { 'attributes': attributeId }, success: function (data) { console.log("success") $("#id_attribute_values").html(data); } }); </script> <script type="text/javascript" src="{% static 'multiselect/dist/js/BsMultiSelect.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#id_attribute_values").bsMultiSelect(); }); here I want to make a dropdown that can have a multiple selectable options. This will be done after the ajax call. Here I get the values return back by ajax and also I have received values, I seen those in the browser elements tab. But that values not populated inside this dropdown. How to solve this? Need help -
Can't put data into tuple in forms.py Django
I'm currently getting the data from an external API (also developed with django) and put it into a tuple and it's showing it in the HTML but when i use that info into a form and post it, it always shows that field has "none" (Views.py) def register_user(request): if request.method == "POST": if "register" in request.POST: mainForm = mainUserForm(request.POST) form = userForm(request.POST) if mainForm.is_valid() and form.is_valid(): user = User.objects.create_user(mainForm.cleaned_data['username'],mainForm.cleaned_data['email'],mainForm.cleaned_data['password']) if form.cleaned_data['userType'] == 2: user.is_superuser = True user.is_staff = True user.save() userextended = models.commonUserModel(user = user, firstName = form.cleaned_data['firstName'], lastName = form.cleaned_data['lastName'], phoneNumber = form.cleaned_data['phoneNumber'], rut = form.cleaned_data['rut'], userType = form.cleaned_data['userType'], company = form.cleaned_data['company']) userextended.save() return redirect('registerUser') else: return redirect('registerUser') context = {} context['mainForm'] = mainUserForm context['form'] = userForm() context['userExtend'] = commonUserModel.getUserExtended(request.user.id) return render(request, template_name='auth/register.html', context= context) (Models.py) class commonUserModel(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name="extend") company = models.IntegerField() firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) phoneNumber = models.CharField(max_length=20) rut = models.CharField(max_length=20, unique= True) userType = models.IntegerField(choices=CLIENT_TYPES, default=1) disabled = models.BooleanField(default = False) (Forms.py) class userForm(forms.ModelForm): def __init__(self,company_choices, *args, **kwargs): choices=[] super(userForm, self).__init__(*args, **kwargs) self.fields['testeo']=forms.ChoiceField(choices=((0, 'Normal' ), (1, 'Especial'),)) testeo= forms.ChoiceField()