Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError at /accounts/signup in django when trying to signup
this is my blog : http://gorani-dncvb.run.goorm.io/ I am trying to build a signup page for my django blog. I finished writing codes for template/view/form/url, and successfully connected to the page : http://gorani-dncvb.run.goorm.io/accounts/signup. So I came to think there is no problem in template/url. but the problem arises after trying signup, It saids : IntegrityError at /accounts/signup UNIQUE constraint failed: auth_user.username and this is my view code : def signup(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = User.objects.create_user(username=username, password=raw_password) return redirect("post_list") else: form = SignupForm() return render(request, 'registration/signup.html', {'form':form}) and this is form code : class SignupForm(forms.ModelForm): class Meta: model = User fields = ('username','password',) (I didn't used UserCreateForm on purpose) There's definitely no overlapping another user, so why I'm seeing this error message? -
Is sending token authentication information via cookie headers secure?
0 i am by no means a security engineer , and i have barely started my journey as a web developer. Im utilizing a python package known as django for my backend , react.js for my front end . Recently i have incorporated django-channels , which is a package that gives me the ability to use websockets in my project. Since i have decoupled my front and backends , the basis of authentication im using is via tokens (will look into using jwt) . The issue is that with javascript , it is not possible to send authentication headers via websocket connection (or so im told) , therefore a lot of people are using cookies to send this authentication token instead. Heres an example snippet of how i am sending the token from my front end: const path = wsStart + 'localhost:8000'+ loc.pathname document.cookie = 'authorization=' + token + ';' this.socketRef = new WebSocket(path) doing this allows me to then extract out the token information through utilizing a customized middleware on my backend . import re from channels.db import database_sync_to_async from django.db import close_old_connections @database_sync_to_async def get_user(token_key): try: return Token.objects.get(key=token_key).user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware: """ Token authorization middleware … -
Only show last record in html
I am new for Django. I want to list all passenger in each flight. However, the display is only the passenger of last flight only. I think it may be something wrong in my html. My code in view.py as follows:- def list (request): flights = Flight.objects.all() for flight in flights: for flight in flights: passengers = Flight.objects.get(pk=flight.id).passengers.all() for passenger in passengers: context = { "flights": flights, "flight":flight, "passengers": passengers, "passenger":passenger, } My HTML is listed as follow:- {% block body %} <h1>Flights</h1> <div class = "list"> {% for flight in flights %} <li> <a href="{% url 'flight' flight.id %}"> Flight #{{ flight.id }}: {{ flight.origin }} to {{ flight.destination }} </a> <ul> <li>Flight Number: {{ flight.id }}</li> <li>Origin: {{ flight.origin }}</li> <li>Destination: {{ flight.destination }}</li> <li> {% for passenger in passengers %} <--- I think it should have some instruction to point to flight Passengers: <ul> <li> {{passenger}} </li> {% empty %} <li>No passengers</li> {% endfor %} </ul> </li> </ul> </li>{% endfor %}</div>{% endblock %} Last flight passenger appear only. Would any one can help me to review if any missing ? Thanks a lot for your help The results is only show last flight passenger -
Django Form - Filter a list based on Foreign Key Value
So basically I have the following in my models.py class Company (models.Model): title = models.CharField(max_length=100) short = models.CharField(max_length=50,default='NA') class AccountingGroups(models.Model): title = models.CharField(max_length=50, unique=True) description= models.CharField(max_length=150,blank=True) section = models.ForeignKey(Section, on_delete=models.PROTECT) class Transaction (models.Model): description = models.CharField(max_length=100) date_created= models.DateField(auto_now_add=True) posting_date = models.DateField() user=models.ForeignKey(User, on_delete=models.PROTECT) company = models.ForeignKey(Company, on_delete=models.PROTECT) account_group = models.ForeignKey(AccountingGroups, on_delete=models.PROTECT) income_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0) expenditure_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0) Now I am displaying the transaction Form on the browser so to log in all the income and expenditure of a particular company. The below is the forms.py file. class TransactionForm(ModelForm): #posting_date = DateField(input_formats=['%d/%m/%Y']) posting_date = DateField(widget=DatePickerInput(format='%d/%m/%Y').start_of('event active days'), input_formats=('%d/%m/%Y',), required=False) class Meta: model = Transaction fields = ['description','posting_date','account_group','income_amt','expenditure_amt'] Now the structure of the website is that each each company that i have in my database has a distinct url. When i go to each url i can view/edit or create a new/existing transaction for that particular company. Now what I'm asking if whether I can restrict the form so that it will show only the Accounting Groups for that particular company only rather than displaying all the accounting groups irrespective on which company I m trying to create the transaction on. -
How to redefine a display form field so it shows a content with filtring?
I have some models classes. And some classes have bounding fields with another class. Each class have the field - author. I whould like that for each user the form bounding field shows only those data which was created these authors. For example: class "TypeJob" has field "author". User Jhon created a TypJob - "Painting". User Alex created a TypJob - "Cleaning". When Jhon opens the form and click "type job" field, he sees both type job: painting and cleaning. I whould like that he sees and could choose only "painting". Because he is it author. Django 3 -
Value Error : "<User: ClipUo>" needs to have a value for field "id" before this many-to-many relationship can be used
I am making a program with multiple user hierarchies. My models.py - class Role(models.Model): ROLE_CHOICES = ( (1,'ADMIN'), (2,'HR'), (3,'MGR'), (4,'EMP'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True) def ___str___ (self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) class Admins(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) class HRs(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) My views.py - class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'ADMIN' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/form1/forms/') class HRSignUpView(CreateView): model = User form_class = HRSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'HR' return super().get_context_data(**kwargs) def form_valid(self,form): user = form.save() login(self.request, user) return redirect('/form1/forms') Initially it was user.roles = 2 or 1 but I changed it after that induced an error to .set() based on the recommendation of the debugger. My forms.py - from django.contrib.auth.forms import * from django.db import transaction from .models import * class AdminSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fname = forms.CharField(max_length=256) lname = forms.CharField(max_length=256) @transaction.atomic def save(self): user = super().save(commit=False) user.roles.set(1) user.save() admin1 = Admins.objects.create(user=user) admin1.first_name.add(*self.cleaned_data.get('fname')) admin1.last_name.add(*self.cleaned_data.get('lname')) return user class HRSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic() def save(self, commit=True): user = super().save(commit=False) … -
Using a GenericRelation attribute as a unique_together
I recently learned the benefits of using GenericForeignKey and GenericRelation, so I started transitioning some of my models.ForeignKey() attributes to GenericRelation(). I'm using the boilerplate definitions inside my Product class: class Product(models.Model): [...] content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Before transitioning to GenericRelation, one of my models used unique_together: class Rank(models.Model): pub_date = models.DateField(db_index=True) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) day_rank = models.IntegerField() class Meta(object): unique_together = ['pub_date', 'product'] However, when I try changing Rank's product attribute to this: [...] product = GenericRelation('Product', on_delete=models.DO_NOTHING) class Meta(object): unique_together = ['pub_date', 'product'] I get the following error: 'unique_together' refers to field 'product' which is not local to model 'Rank'. Is it possible to find a workaround for this error? Why was I able to use a ForeignKey but not a GenericRelation when defining unique_together? -
Is it a good idea to build a website fully in python and django
I realize this is a very general question, and do not expect a perfect answer, but I am currently working on building a full and well running website from scratch. It is a bit of a double project for me since I am learning python at the moment, and wanted to build it in said language. However I know visual basic and am very comfortable in that, but I want to expand my knowledge of languages, while also doing something with a purpose. I want to know if that is a good endeavor, not so much if possible more so I do not know where to start since I know I have to do both front end and back end work, and python is coming along well for me, however I keep seeing web resources that say that it is not a good idea and do not understand why that is. I am familiar with HTML and CSS and am prepared to put the bells and whistles on to make things look nice and pretty, however I want to know why I cannot or should not use python to link my database to the webpage alongside other scripting languages to … -
ValueError: Expected table or queryset, not str
This might be something really simple but I can't put my finger on it. I created a table using django-tables2 and added a checkbox column in it, above the table I created an actions dropdown for delete and edit inside a form, here's my html code <div class="container"> <div class = "mt-5"> <h1 class="display-4">My Table</h1> <form action="/delete_or_edit_item/" method="POST"> {% csrf_token %} <select name="action_options"> <option value="delete">Delete</option> <option value="edit">Edit</option> </select> <input type="submit" class="btn btn-info px-3 py-1 ml-2 mb-1" value="Go"> {% render_table mytable %} </form> </div> </div> I created a single function based view for it, here's the code in views.py, I know my problem is here somewhere in my action == 'edit'... def delete_or_edit(request): if request.method == "POST": pks = request.POST.getlist("selection") # handle selection from table action = request.POST.get('action_options') selected_objects = my_tbl.objects.filter(object_id__in=pks) if action == 'delete': selected_objects.delete() return HttpResponseRedirect("/") selected_object = my_tbl.objects.get(object_id__in=pks) if action == 'edit': form = my_tbl_form(request.POST or None, instance=selected_object) if form.is_valid(): form.save() return HttpResponseRedirect("/") return render(request, 'staffplanner/index.html', {'form':form}) in my urls.py urlpatterns = [ path('', views.index, name = 'home'), ... path("delete_or_edit_item/",views.delete_or_edit), ] in my tables.py class myTable(tables.Table): selection = tables.CheckBoxColumn(accessor='object_id', attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False) class Meta: model = my_tbl template_name = "django_tables2/bootstrap-responsive.html" fields = ('selection','object_id','manufactured','expiry','company','category') attrs … -
Django ORM sum all fields value of onetoone fields
This is my models: class Bill(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) flat_rent = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) gas = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) I know a way but i dont like this: like bill = Bill.objects.get(--------) total = bill.gas + bill.flat_rent But I think this is bad practice, coz, I have more than 20 fields in this model. So I want to know the total of all these fields in single line of query. Can anyone help me in this case? -
How to store a list of 'ModelBase' object in a view ('ModelBase' object is not subscriptable)
I'm trying to build an app with Django where you can build different foods based on ingredients you can previously create. The way the user does this is by selecting each Ingredient for the Food. Note that one request is sent by each Ingredient selection. models.py: class Ingredient(models.Model): """User selects different instances of this model, to build instances of FoodDetail, it can be, for instance: 'Meat'.""" account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) code = models.CharField(max_length=20, null=False, blank=False) name = models.CharField(max_length=100, null=False, blank=False) cost = models.DecimalField(max_digits=14, decimal_places=2, null=False, default=0.00) stock = models.DecimalField(max_digits=14, decimal_places=3, null=False, default=0.000) class Food(models.Model): """The new food the user will create once it has finished the Ingredients selection. For instance, 'Burger'.""" account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=100, null=False, blank=False) price = models.DecimalField(max_digits=14, decimal_places=2, null=False) class FoodIngredient(models.Model): """Instance of an ingredient (e.g. 'Bread') of a specific instance of Food (e.g. 'Burger').""" food = models.ForeignKey(Food, on_delete=models.CASCADE, null=False) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, null=False) quantity = models.DecimalField(max_digits=14, decimal_places=3, default=0.000, null=False) So you can create any ingredients, and then use them to build different foods. Now imagine that user sends one FoodIngredient per request, and I need to accumulate them in the view, so that I can submit the new Food with … -
Unable to write to Db using cursor.execute() in Django - Boolean value of this clause is not defined error
I'm trying to build a user registration form with Django. I have created a function like this: def create_user(user_dict): from django.db import connection from sqlalchemy.sql import text from django.contrib.auth.hashers import make_password if 'middle_name' not in user_dict: user_dict['middle_name'] = None if 'alt_email' not in user_dict: user_dict['alt_email'] = None if 'alt_mobile' not in user_dict: user_dict['alt_mobile'] = None if 'role' not in user_dict: user_dict['role'] = None password = make_password(user_dict['password']) user_dict['password'] = password insert_query = """ insert into user_info (first_name, middle_name, last_name, email, mobile, alt_email, alt_mobile, password, role ) values(:first_name, :middle_name, :last_name, :email, :mobile, :alt_email, :alt_mobile, :password, :role) """ insert_query_text = text(insert_query) cursor = connection.cursor() cursor.execute(insert_query_text, user_dict) return(True) When I call this function, I get the following error: Traceback (most recent call last): File "D:\Documents\django\project1\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Documents\django\project1\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Documents\django\project1\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Documents\django\project1\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\Documents\django\project1\myproject\boards\views.py", line 84, in register_user create_user(body) File "D:\Documents\django\project1\myproject\boards\methods.py", line 115, in create_user cursor.execute(insert_query_text, user_dict) File "D:\Documents\django\project1\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "D:\Documents\django\project1\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\Documents\django\project1\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return … -
displaying user posts inside there profile in django
I am fairly new to django, i have two models in my app MyProfile and MyPost, users have a profile and they can create a post, it's all work but i want to show posts created by perticular user inside their own profile i tried adding a user_posts object in MyProfile with a filter author but nothing happened. MyView @method_decorator(login_required, name="dispatch") class MyProfileDetailView(DetailView): model = MyProfile def broto(request): user = request.user user_posts = MyPost.objects.filter(author=request.user).order_by('-cr_date') return render(request, {'user_posts':user_posts,'user': user}) Profile page html {% extends 'base.html' %} {% block content %} <div class="p-5"> <img src="/media/{{myprofile.pic}}" /> <h1 class="myhead2">{{myprofile.name}}</h1> <p><strong>Address: {{myprofile.address}}</strong></p> <p><strong>Phone Number: {{myprofile.phone_no}}</strong></p> <p><strong>Email: {{myprofile.user.email}}</strong></p> <p><strong>About:</strong> {{myprofile.purpose}}</p> <p><strong> Total Donation Recived: {{myprofile.donation_recived}}</strong></p> <hr> <table class="table my-3"> <thead class="thead-dark"> <tr> <th>Title</th> <th>Date</th> <th>Action</th> </tr> </thead> {% for MyPost in user_posts %} <tr> <td>{{MyPost.title}}</td> <td>{{MyPost.cr_date | date:"d/m/y"}}</td> <td> <a class="btn btn-dark btn-sm" href='/covid/mypost/{{n1.id}}'>Read More</a> </td> </tr> {% endfor %} </table> </div> {% endblock %} -
saving anonymous user session key get None in django
I have an app where user comes select item and add to cart it work perfectly for login user but i want it for anonymous user . So i am trying to get session key and save in models and after user login map it with user and get details. views.py def AddToCart(request): if request.method == 'POST': cart = AddCart() cart.session_key = request.session.session_key cart.user = request.user cart.testselected = request.POST['selectedTests'] cart.save() models.py class AddCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) session_key = models.CharField(max_length=32, null=True) testselected = models.TextField() Now, i have trouble to save session key for anonymous user it saves none but if user is login it save session key . is something missing in my code ? and if anonymous user session key gets save how can i use that after user login or register and should i remove user field from model once i have added session key as new to django no idea to proceed. -
How to map flask and Django to same database model?
I want to have a database model which is written in Django ORM and the same database is used to read data by flask using SQLAlchemy for microservices. What is the right way to do this so that I don't have to write model in both django ORM and flask separately? The django model is required as there is a need of admin functionality and flask will be used to serve data to UI which is written in Angular. -
Python: isinstance on Abstract Inherited Classes?
New to Python here– I'm trying to see if isinstance(obj, Class) works on abstract inherited classes. Specifically I'm working on a Django project and I want to check if one type of object is inherited from a set of shared base classes. class AbstractClass(models.Model): class Meta: abstract=True class ClassA(AbstractClass): ... class ClassB(AbstractClass): ... obj = ClassB() if isinstance(obj, AbstractClass): ... Does this work? -
Change inheritance to OnToOne relation in Django models
I have models that have a inheritance relationship. I want to turn this relationship into a OneToOne relationship, without removing anything data in project. This is structure of models: class BaseFieldsModel(models.Model): create_date = DateTimeField(auto_now_add=True,) update_date = DateTimeField(auto_now=True,) created_by = ForeignKey('UserManager.User', related_name='created_%(class)ss') updated_by = ForeignKey('UserManager.User', related_name='updated_%(class)ss') class User(AbstractBaseUser,BaseFieldsModel): # Some fields class Teacher(User): # Some fields class Student(User): # Some fields All things was good until I want to resructure my database because of this problem that I had in this design. In new DB model, I want to have something like this: (OneToOne Relation) class User(AbstractBaseUser,BaseFieldsModel): # Some fields class Teacher(BaseFieldsModel): user_ptr = OneToOneField('UserManager.User', primary_key=True,related_name='student_user') # Some fields class Student(BaseFieldsModel): user_ptr = OneToOneField('UserManager.User', primary_key=True,related_name='teacher_user') # Some fields So I did run makemigrations: Migrations for 'UserManager': UserManager/migrations/0022_auto_20200425_1233.py - Change managers on student - Change managers on teacher - Add field create_date to student - Add field created_by to student - Add field update_date to student - Add field updated_by to student - Add field create_date to teacher - Add field created_by to teacher - Add field update_date to teacher - Add field updated_by to teacher - Alter field user_ptr on student - Alter field user_ptr on teacher and then run migrate … -
How to set date without year using Date Field on Python?
I want to set dates without year using Date Field on Python, the solution was to set year 2000, but I am not interested on the year, is it possible to modify Date Field to set it not to require year data? -
Django app on Apache2 Forbidden 403 Response
I have been battling with this for about an hour and I am not sure how to fix the issue. It seems my Apache server is running fine but anytime I try to access the website I get a Forbidden 403 Error. Here Is what added to the default .conf file <Directory "/home/mredwin/website\ v1.0/marketingvideosclub"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "/home/mredwin/website\ v1.0/marketingvideosclub/wsgi.py" WSGIDaemonProcess marketingvideosclub python-home="/home/mredwin/website\ v1.0/venv" python-path="/home/mredwin/website\ v1.0" WSGIProcessGroup marketingvideosclub And I checked the logs and there is nothing useful in there except that it is getting a GET and it is returning a 403 error code. Any help is appreciated thanks! -
Div not being found when Ajax loaded
I have a Django template that looks like this: page.html {% extends 'core/base.html' %} {% block content %} <div class="example"> ..some..content.. </div> {% endblock %} Inside base.html contains a wrapper div that wraps everything up. I'm trying to retrieve this page like so in Ajax: $.ajax({ url: '/page/', method: 'GET', success: function (data) { console.log($(data).find(".wrapper")); } }); However, the log says that .wrapper does not exist for some reason, even though if I do console.log(data); it shows the wrapper and all the HTML. Is it because the tag hasn't loaded yet? If so, how can I make it show? -
django admin list filter?
Actually, my models has foreign key to User table. And I want to make admin list show only what I made. # models.py class Store(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=20) state = models.CharField(max_length=2) phone = models.CharField(max_length=25) user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING) # admin.py class StoreAdmin(admin.ModelAdmin): list_display = ('name', 'address', 'city', 'state') list_filter = ['name'] search_fields = ['name'] But this shows all of list. -
UTF-8 is not saving txt file correctly - Python
My django application reads a file, and saves some report in other txt file. Everything works fine except my language letters. I mean, encoding="utf-8" can not read some letters. Here are my codes and example of report file: views.py: def result(request): #region variables # Gets the last uploaded document last_uploaded = OriginalDocument.objects.latest('id') # Opens the las uploaded document original = open(str(last_uploaded.document), 'r') # Reads the last uploaded document after opening it original_words = original.read().lower().split() # Shows up number of WORDS in document words_count = len(original_words) # Opens the original document, reads it, and returns number of characters open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) # Makes report about result report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") report_twenties = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-20.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
cannot send large text using POST request in Django
I am making an app in reaact native and backend is in django. I am sending POST request from the app to the api, when the text is small it is working fine but when I try to send long text like about 3 paragraphs, only 1.5 paragraph comes in request the other half is not coming. Please help me on this. -
django gunicorn workers vs theads vs other possibilities
My app in django with gunicorn and I am kinda new to gunicorn. My app is heavy on IO, not so much on memory and CPU, essentially a thread has to save a or serve a big file (from few MB to few GB) from storage. Currently because of this the workers run out while there is no load on CPU or memory or even the HDD. By default has a config file for gunicorn that looks like this: import os daemon = True workers = 5 # default localhost:8000 bind = "127.0.0.1:8000" # Pid pids_dir = '/opt/pids' pidfile = os.path.join(pids_dir, 'app.pid') # for file upload, we need a longer timeout value (default is only 30s, too short) timeout = 7200 limit_request_line = 8190 I am not sure about how to configure the workers and threads etc for my work load. let me provide more details: We run "a few VMs" of 2 CPUs/8GB RAM. python is 2.7 we are on the way to upgrade to 3.7, but for now is 2.7 I already tried adding threads with different values (1 to 6), but it does not seem to work. Can someone please help explain what I can do? -
Getting id of an item instead of value, django forms
I have created a form and I wanted to create a field that is for display only, after adding that line, the form started returning id instead of the value. class AmendLoan(ModelForm): borrower = forms.CharField(disabled=True) class Meta: model = BikeInstance fields = ( 'borrower', 'due_back', 'status' ) Any ideas, how to display value of borrower, instead of id?