Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a LDAP users and groups from the dajango interface admin
I am trying to modify a user in OpenLDAP server. As of now I can log but when I try to create users or groups in django. I can't see those users and groups in my LDAP server. Do you have any idea how a can sycnronize this data from django to LDAP For now i use the package django-auth-ldap for LDAP backend. This my conf in settings.py #OpenLdap-AUTH import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType,PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://localhost' AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com' AUTH_LDAP_BIND_PASSWORD = 'omar77' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=users,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=groups,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True # Populate users from the LDAP directory to Django db. AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=example,dc=com" AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=groups,dc=example,dc=com" AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "username": "uid", "password": "userPassword", } AUTH_LDAP_PROFILE_ATTR_MAP = { "home_directory": "homeDirectory" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", "is_staff": "cn=staff,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_FIND_GROUP_PERMS = True -
Django find common instances data in two models
I have models like: class Hospital(models.Model): name = models.CharField(max_length=200, unique=True) manager_name = models.CharField(max_length=200, default='') manager_id = models.CharField(max_length=200) def __str__(self): return f'{self.name}' class Sick(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) illName = models.CharField(max_length=200) hospital = models.ForeignKey(Hospital, related_name='sicks', on_delete=models.DO_NOTHING) def __str__(self): return f'({self.name}, {self.nationalID})' class Employee(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) company = models.ForeignKey(Company, related_name='employees', on_delete=models.CASCADE) def __str__(self): return f'({self.name}, {self.nationalID})' views: @api_view(['POST']) def get_sick_employee_by_hospital(request): pass and a serializer like : from rest_framework import serializers class NameSerializer(serializers.Serializer): name = serializers.CharField(required=True, max_length=200, allow_null=False) my problem is : my view get_sick_employee_by_hospital() receives a hospital name and it must return all sick peoples that are employees and They have visited that hospital, in a dictionary with keys 1,2,3,..., n and values like "(name, nationalID)". Pay attention that it does not matter which value is assigned to which key. what is the best way to do that ? how can i get all sick peoples that are employees and They have visited a hospital? thanks for your time. -
verbose name on class field in django
I am need of help to add a verbose name class Address(models.Model) : class Zip(models.Field): def db_type(self, connection): return 'char(8)' zip = Zip() address = models.CharField(max_length=200, verbose_name="Rua") ..... Need put the vebose name of ZIP to CEP -
How multiply and sum two columns in different tables in django
I have an application for calculating diets based on the nutrients of each meal. In admin of this application I want to price of each meal to the Meal table, which I have managed to do by calculating the price when displaying it in admin: # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] @admin.display(description='Price') def price(self, obj): unit_prices = np.asarray(obj.mealingredient_set.order_by('id').values_list('ingredient__unit_price')) amounts = np.asarray(obj.mealingredient_set.order_by('id').values_list('amount')) to_return = float(np.matmul(np.transpose(unit_prices), amounts) / 1000) return mark_safe(to_return) Now my main question: I need to allow ordering of Meal table based on Price which I don't know how. based on my search it seems I should use annotate instead of my current way of calculating the price to be able to sort my table, I found a solution in here # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(_price=Sum('mealingredient__amount * mealingredient__ingredient__unit_price')) But sadly it throws this error (I think it's because i'm trying to SUM over different tables): Unsupported lookup 'amount * mealingredient' for AutoField or join on the field not permitted. Any help is appreciated, forgive me if I have missed something obvious, I'm a beginner in django. Some of the relevant Models for Meal table: … -
I want to host my webserver installed on aws ec2 instance [closed]
I have django webserver running on my aws ec2 instance. I installed self signed SSL on the apache2 webserver but whenever I try to access my webserver, i get a Install certificate warning. I know why this is happing but I want my server to be accessible to the public over https without showing this warning. How can I get a certificate for my webserver?? -
python manage.py collectstatic not working: TypeError: sequence item 0: expected str instance, NoneType found
I have been following this video on Youtube: https://www.youtube.com/watch?v=inQyZ7zFMHM1 My project so far is working fine with static files and all the files load and work properly. So, now I have to deploy the website on Heroku and for that, I uploaded the database on Amazon AWS using this video. After bucket creation, I did the configurations as mentioned in the video (copied the static files into the Bucket AWS) but it didn't work for me. It always showed me an error, that failed to load the resources On searching, I found the command python manage.py collectstatic to upload files into Bucket so I tried it out but this is the error I keep on getting TypeError: sequence item 0: expected str instance, NoneType found I have searched a lot on this but unable to figure out what is the issue. This is also the same error which I got when I myself uploaded static files into Bucket and tried to upload a Profile Image My settings.py file is as follows, """ Django settings for fcap project. Generated by 'django-admin startproject' using Django 4.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their … -
Adding commas to Django for loop values
I am trying to write a javascript to 3 digit comma separate number values that are passed in through my django database and can't figure it out. Exp: (1000 -> 1,000). Before writing the JS, I am also trying to figure out if I comma separate these values, will they mess up potential usage in other JS code that utilize these numbers to do math? Thanks. <table class="database-table"> <thead> <tr> <th>Market Value</th> </tr> </thead> <tbody> <tr> {% for s in securities %} <tr> <td id="security-value">${{s.market_value_of_security}}</td> </tr> {% endfor %} </tr> </tbody> </table> <script> const security_value = document.getElementById("security-value"); function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } -
How to add new field to a table in django that have "managed=False" because it was generated using inspectdb tool
I'm using an existing mysql database in a new django project, so I generated the models using inspectdb tool. But now I need to add a new field to a table, I'm doing it by adding the new field to the model and running migrations, but it doesn't work, It doesn't add the field to the table. Maybe it is because I have managed=False in the meta config of the model, but if I remove it, the migrations won't work, giving me the error "Table5 already exists" Here is the Model where I'm trying to add the "fields" field class Table5(models.Model): names = models.CharField(max_length=150) fields=models.JSONField(null=True) class Meta: managed = False db_table = 'table5' How can I achieve this? -
Django Celery Error on Runserver Using Redis
Currently using django and celery i have done my configuration and installed redis and redis is actually active i have check using the cli also when i run python manage.py shell and run a task it works perfectly but when i access the task by calling it from a view i get this error Internal Server Error: /contact/ Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/transport.py", line 188, in _connect entries = socket.getaddrinfo( File "/usr/local/lib/python3.9/socket.py", line 953, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -9] Address family for hostname not supported During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/transport.py", line 129, in … -
Does obj.save() in save_model() in admin.ModelAdmin call save() in models.Model?
I overrided "save()" in "Person(models.Model)" class as shown below: # "models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def save(self, *args, **kwargs): super().save(*args, **kwargs) Then, I also overrided "save_model()" in "PersonAdmin(admin.ModelAdmin)" class as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) Then, I could add "Steve Jobs" as shown below: Next, for "save_model()" in "PersonAdmin(admin.ModelAdmin)" class, I replaced "super().save_model(request, obj, form, change)" with "pass" as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): pass # super().save_model(request, obj, form, change) But now, I couldn't add "Bill Gates" as shown below: So, I checked save_model() on Django repository on GitHub. Then, in "save_model()" in ModelAdmin(BaseModelAdmin)" class, "obj.save()" is called as shown below: # "django/django/contrib/admin/options.py" # ... class ModelAdmin(BaseModelAdmin): # ... def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() # Here So, does "obj.save()" call "save()" in "Person(models.Model)" class? -
Javascript: Ecommerce add to cart function not working in Javascript?
I am trying to write an add to cart functionality using Javascript and django (main functionality is Javascript). I have written this code for the cart.js var updateBtns = document.getElementsByClassName('update-cart') console.log("Working"); for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId is:', productId, 'Action is:', action) console.log('USER:', user) }) } And this is the code for template index.html {% for product in products %} {{ product.title }} {{ product.price}} <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> {% endfor %} When i print(product.id) it gets the specific product id but the button does not wwork what could be the problem with my code? -
I am getting an error in Django while trying to submit the details in my form, what should I do?
Basically I am filling in the details in my form in Django and clicking on submit but the error is appearing. What should I do? Thanks in advance. My Error- TypeError at /contact Contact() got unexpected keyword arguments: 'name', 'email', 'phone', 'desc', 'date' My views.py from django.shortcuts import render, HttpResponse from datetime import datetime from Home.models import Contact # Create your views here. def index(request): context = { 'variable':"this is sent" } return render(request,'index.html',context) #return HttpResponse("This is Home Page") def about(request): return render(request,'about.html') #return HttpResponse("This is About Page") def services(request): return render(request,'services.html') #return HttpResponse("This is Service Page") def contact(request): if request.method == "POST": name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') desc=request.POST.get('desc') contact = Contact(name=name, email=email, phone=phone, desc=desc,date=datetime.today) contact.save() return render(request,'contact.html') #return HttpResponse("This is Contact Page") My urls.py from django.contrib import admin from django.urls import path from Home import views urlpatterns = [ path("",views.index, name='home'), path("about",views.about, name='about'), path("services",views.services, name='services'), path("contact",views.contact, name='contact'), ] -
django how to know how many times that the user has been recapitulated in template
in this case i want to count how much each user has been recapitulated in same class, the calculation is like mr.a has attended 4 times mr.b has attended 5 times this is my Recap models: class Recap(models.Model): qr = models.ForeignKey(GenerateQRCode, on_delete=models.CASCADE, related_name='qr_c', related_query_name='qr_c') user = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) the Recap models have relation with GenerateQRCode models, this is the GenerateQRCode: class GenerateQRCode(models.Model): qr_code = models.SlugField(unique=True) valid_until = models.DateTimeField(blank=True) class_name = models.ForeignKey(ClassName, on_delete=models.CASCADE, related_name='from_class', related_query_name='from_class') creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creator') qr_img = models.FileField(blank=True, upload_to='qr/') according the code it has relations with ClassName with class_name field, so here my ClassName models class ClassName(models.Model): name = models.CharField(max_length=255) link = models.SlugField(max_length=255, unique=True) unique_code = models.CharField(max_length=255, unique=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='class_creator', related_query_name='class_creator') so if i login as mr.a i want to know how many i've been recapitulated, anyone know the count code? i just thinks like recap.user.count() each class -
Why my function isn't work in view.py in Django?
I am currently working on E-Commerce Website with Django.And I have faced many problems in the cart app & I use Session framework for cart functionality.So please anybody help to solve this problem. My onlinePizza app models.py class Product(models.Model): product_id = models.AutoField product= models.CharField(max_length=50) category = models.ForeignKey(Category, default='', null=True, on_delete=models.CASCADE) desc = models.TextField() price = models.FloatField(max_length=10, default=0) nonveg = models.BooleanField() slug = models.SlugField(max_length=100) image = models.ImageField(upload_to='onlinePizza/image', default="") @staticmethod def get_products_by_id(ids): return Product.objects.filter(product_id__in=ids) def __str__(self): return self.product My cart app views.py from django.shortcuts import render, redirect from django.views import View from onlinePizza.models import Product def AddCart(request): product = request.POST.get('product') remove = request.POST.get('remove') cart = request.session.get('cart') if not cart: request.session['cart'] = {} if cart: quantity=cart.get(product) if quantity: if remove: if quantity<=1: cart.pop(product) else: cart[product]=quantity-1 else: cart[product]=quantity+1 else: cart[product]=1 else: cart={} cart[product]=1 request.session['cart']=cart return redirect ('Menu') def Cart(request): ids = list(request.session.get('cart').keys()) products = Product.get_products_by_id(ids) context={'products':products} print(products) return render(request , 'cart/pc_cart.html', context) Here Cart function is not work This is pc_cart.html where I want to show my cart products. <div class="position-fixed d-flex flex-column flex-shrink-0 p-3 border mb-5 " style="width: 380px; height: 420px; border-radius: 10px; box-shadow: 1px 1px 2px #000000; background-color: #ffff; overflow-y: scroll;"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <h2 class="text-center">Your … -
how to upload a document in django rest framework
I am trying to upload a document using django rest framework and currently, for some reason, Django do not create an instance of the table Document nor save the uploaded file to media/documents folder locally settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Document(models.Model): name = models.CharField(max_length=10) document_to_upload = models.FileField(upload_to="documents/") serializers.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model = File fields = ["name", "document_to_upload"] views.py @api_view(["POST"]) def upload_file(request): if request.method == "POST": serializer = FileSerializer(request.data, request.FILES) if serializer.is_valid(): serializer.save() return Response(data=request.data) else: serializer = FileSerializer() return Response(HTTP_400_BAD_REQUEST) the response i am getting from the front end is : config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: 400 headers: {content-length: '3', content-type: 'application/json'} request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" Unfortunately, no instance was created, no document uploaded either, is there something that i am doing wrong here? -
How to use model method as default for field in django model?
I want to use instance method of my model as default value for a new field. How can I do this? The value should be calculated based on other fields and third-party library, so I have to use callable as default with arg of current instance or its fields. Is it ever possible? -
Remove the micro seconds from model method datetime objects
I have this method, it returns the time_left hence the name. My problem is the additional microseconds appended at the end. from django.utils.timezone import now class ModelClass(models.Model): .... due_date = models.DateTimeField() @property def time_left(self): data = {"in_negative": False} remaining = self.due_date - now() data["remaining"] = remaining if remaining.days < 0: data["in_negative"] = True return data This is what I get on my template 3 days, 10:38:53.070894 What I want 3 days, 10:38:53 -
Serializing a model in GeoDjango where the geo_field is in a related field
I have a model which is related to another model by a ManyToMany Relationship that contains the location data. I am trying to serialize this model, but am getting extra fields in my geojson file: Models.py class Historicalfile(models.Model): dmsesite = models.ManyToManyField(Dmsesite) name = models.CharField(verbose_name='Job Name', max_length=250) ... class Dmsesite(models.Model): ptgeom = models.PointField(srid=4326, blank=True, null=True) plgeom = models.PolygonField(srid=4326, blank=True, null=True) Serializers.py class DmsesitePtSerializer(serializers.ModelSerializer): class Meta: model = Dmsesite fields = ("ptgeom",) class HistoricalFileSerializer(serializers.GeoFeatureModelSerializer): dmsesite = DmsesitePtSerializer(many=True) class Meta: model = Historicalfile geo_field = "dmsesite" fields = ("company", "name",) Viewsets.py class DmsesitePtSerializer(serializers.ModelSerializer): class Meta: model = Dmsesite fields = ("ptgeom",) class HistoricalFileSerializer(serializers.GeoFeatureModelSerializer): dmsesite = DmsesitePtSerializer(many=True) class Meta: model = Historicalfile geo_field = "dmsesite" fields = ("company", "name",) This mostly works, except that I get an "extra" field in my GeoJson output: "properties": { "company": { "name": "Don-More Surveys" }, "name": "51938" } }, { "type": "Feature", "geometry": [ { "ptgeom": { "type": "Point", "coordinates": [ -65.66314398960121, 45.65473652218946 ] } } ], I am expecting something like: { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -65.09304726799569, 45.90454322923145 ] }, "properties": { "company": { "name": "Don-More Surveys" }, "name": "51938" } }, I belive my issue is related to this being a many-to-many … -
Python Django3 - Register form issue after deployment on VPS
I have problem with Register form for project deployed here: http://donation.rogalowski.uk:2052/ . Domain name from cloudflare. VPS host: www.mikr.us with reverse proxy to port 2052 unsecured. Dockerized. After click Załóż konto (Sign up) and filling the form it should send a mail verification, shows error: enter image description here For tests, debugging turned on. Registration works fine on localhost. How can I fix this? Github project: https://github.com/Rogalowski/Portfolio_oddam_w_dobre_rece views.py def send_activation_email(user, request): current_site = get_current_site(request) email_subject = 'Aktywacja konta na stronie ODDAM W DOBRE RĘCE' email_body = render_to_string('auth/activate.html', { 'user': user, # 'domain': 'donation.rogalowski.uk:30157', 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email = EmailMessage( subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email] ) email.send() def activate_user(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) if user and account_activation_token.check_token(user, token): user.is_email_verified = True user.is_active = True user.save() messages.add_message( request, messages.ERROR, 'Email zweryfikowany poprawnie, możesz się zalogować :)') return redirect('login_view') messages.add_message(request, messages.ERROR, f'Użytkownik źle zweryfikowany, prawdopodobnie aktywny!') return redirect('register_view') class RegisterView(View): def get(self, request): return render(request, 'register.html') def post(self, request, *args, **kwargs): name = request.POST.get('name') surname = request.POST.get('surname') email = request.POST.get('email') password = request.POST.get('password') password2 = request.POST.get('password2') if password == password2: password2 = make_password(password) else: messages.add_message( request, messages.ERROR, f'Podane hasła różnią się od siebie, spróbuj jeszcze raz!') … -
amadeus api giving 400 error in Hroku app
I have hosted django app that calls amadeus api to get some details. The issue is when running it on heroku it gives [400] but when I run application locally it is working fine, does any one have any idea what might be the issue. log snapshot for ref. -
obj argument returns with the "None" value when deploying the project on the cloud
I deployed my website on namecheap.com and when I'm trying to upload any image I meet this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 38-43: ordinal not in range(128) I took a few hours until I found the issue and the problem in this code: class MultipleImageManaged(admin.ModelAdmin): list_display = ('id', 'images') def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj=None, **kwargs) form.base_fields['images'].widget.attrs = { 'multiple': 'multiple' } return form def save_model(self, request, obj, form, change): for data in request.FILES.getlist('images'): cat_name = Category.objects.get(name=obj.category) if obj.album: album_name = Album.objects.filter(category__name=cat_name).get(name=obj.album) else: album_name = None Gallery.objects.create(images=data, category=cat_name, album=album_name) when I print out "obj" argument in get_form() method I figured out that this arg returns the "None" value knowing that, this argument is working in my localhost. actually, I don't know why it is working like that but now I'm trying to stick with another approach, I'm not sure if this approach will work properly but I need help with that. so, I'm trying right now to use signals instead and there's my new approach: from django.contrib import admin from .models import Gallery, Album, Category from django.db.models.signals import pre_save from django.dispatch import receiver class MultipleImageManaged(admin.ModelAdmin): list_display = ('id', 'images') def get_form(self, request, obj=None, … -
How to populate field with model method as default?
I want a migration created populate new field with calculated value which calculates as model instance method class Migration(migrations.Migration): dependencies = [ ('appname', '0001_initial'), ] operations = [ migrations.AddField( model_name='modelname', name='new_field', # model method to calculate a value for a new field based on existing data. # with the below I, as expected, get "... missing 1 required positional argument: 'self'" field=models.TextField(default=ModelName.calc_new_field), preserve_default=False, ), ] -
Django - How to set ForeignKey relation in forms.ModelForm
My task is to implement a form in which the choice of the value of the second field depends on the value of the first field. (For example, if the value of the first field is Cars, then the second field should show sedan/SUV, etc., if the value of the first field is Commercial vehicles, then the second box should show truck/bus, etc.) Code models.py: class TypeTransport(models.Model): transport_name = models.CharField(max_length=100, verbose_name='kind of transport') class TypeBodyTransport(models.Model): transport = models.ForeignKey(TypeTransport, on_delete=models.CASCADE, blank=True, null=True, verbose_name='kind of transport') body_name = models.CharField(max_length=100, verbose_name='transport body type') class Advertisement(models.Model): transport = models.ForeignKey(TypeTransport, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='kind of transport') body = models.ForeignKey(TypeBodyTransport, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='transport body type ') Code forms.py: class CreateAdvertisementForm(forms.ModelForm): transport = forms.ModelChoiceField(queryset=TypeTransport.objects.all(), to_field_name="transport_name") body = forms.ModelChoiceField(queryset=TypeBodyTransport.objects.filter(transport=transport), to_field_name="body_name") class Meta: model = Advertisement fields = ('transport', 'body') I thought it could be done with filter(transport=transport), but this error is returned: TypeError: Field 'id' expected a number but got <django.forms.models.ModelChoiceField object at 0x7f40d7af5ac0>. Can you please tell me how to implement the feature I need? -
Django show list of strings in textarea, each string from new line
I have a list lst=['apple', 'pear', 'peach']. I want to show each item in textarea from new line (removing redundant subspaces). <textarea> {% for item in lst %} {{ item }} {% if not forloop.last %}<br/>{% endif %} {% endfor %} </textarea> This code doesn't work. <br/>s are shown as they are. And there are redundant whitespaces at the beginning of the textarea and between the items. -
I got the error code trying to install django
Traceback (most recent call last): File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\urllib3\response.py", line 438, in _error_catcher yield File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 465, in read s = self.fp.read(amt) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto return self._sock.recv_into(b) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into return self.read(nbytes, buffer) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read return self._sslobj.read(len, buffer) TimeoutError: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\HP\myproject\lib\site-packages\pip_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 472, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 341, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria if not criterion.candidates: File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\structs.py", line 151, in bool return bool(self._sequence) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 140, in bool return any(self) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 128, in return (c for c in iterator if id(c) not in self._incompatible_ids) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 32, in _iter_built candidate = func() File …