Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-allauth signup error: filename must be a str or bytes object, or a file
I am using django-allauth for user login/signup. I didn't modify any .py files or template files in django-allauth. But when I tried to create a new user, the system throw out an error: Django Version: 3.0.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'MyBlog', 'allauth', 'allauth.socialaccount', 'allauth.account', 'widget_tweaks', 'imagekit', 'ckeditor', 'ckeditor_uploader', 'comment', 'channels', 'webssh'] Installed Middleware: ['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'] Template error: In template /usr/local/lib/python3.8/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 7 filename must be a str or bytes object, or a file 1 : <fieldset class="module aligned {{ fieldset.classes }}"> 2 : {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %} 3 : {% if fieldset.description %} 4 : <div class="description">{{ fieldset.description|safe }}</div> 5 : {% endif %} 6 : {% for line in fieldset %} 7 : <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %} {% for field in line %} {% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> 8 : {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif … -
How do you use a Custom Model Manager method for a related Many-to-Many model field?
I am working on a small project, mostly for learning, and I am running into an issue with accessing expected custom model manager methods on some related M2M type models. The application I am trying to implement is a travel calculator, that can determine total fuel requirements and weights for all vehicles in a particular trip. models.py ... from django.db import models from django.db.models import Sum # Create your models here. class TripManager(models.Manager): def get_vehicle_weight(self): return self.get_queryset().all().aggregate(total_weight=Sum('vehicle__weight')) def get_vehicle_fuel(self): return self.get_queryset().all().aggregate(total_fuel=Sum('vehicle__fuel')) class Vehicle(models.Model): """A vehicle may belong to multiple businesses and multiple trips at once.""" name = models.CharField(max_length=50, help_text="The common name of the vehicle.") fuel_capacity = models.IntegerField(default=0, help_text="The total fuel capacity in gallons.") burn_rate = models.FloatField(default=0, help_text="The burn rate of fuel in gal/h.") weight = models.FloatField(default=0, help_text="The weight of the vehicle in pounds.") def __str__(self): return self.name class Business(models.Model): """""" name = models.CharField(max_length=50, help_text="The name of the business.") def __str__(self): return self.name class EmployeeType(models.Model): """Employee types can belong to many businesses.""" name = models.CharField(max_length=50, help_text="The title/role of a type of employee.") def __str__(self): return self.name class Trip(models.Model): """A trip will be the primary object, composed of other objects that are associated with the trip.""" name = models.CharField(max_length=128) vehicles = models.ManyToManyField(Vehicle, … -
Please see if it is possible to print various options (no code) during the implementation of the Django shopping mall
I am a student who is learning Janggo. I'm asking you a question because I have a question while processing shopping mall options. The data for the ongoing project are as follows. Cardigan has two options, Size and Color, and I want to use Select in the template to import the Value of Size and Value of Color separately. I want to know if this is possible. For example, I would like to write: I wonder if it's possible, and if possible, I'd appreciate it if you could let me know how it can be implemented. -
<QuerySet [<Address: Shreyash>, <Address: Shreyash>]>": "Order.address" must be a "Address" instance
I have model related to that form what I want is to when user click on submit button from go submit and save in database but here I got error so what to achieve is a single address got submit in that instead of all the address which is linked with whit model choice field so any idea how i can achieve that here is my models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) address = models.ForeignKey(Address, on_delete=models.CASCADE) price = models.FloatField(blank=False) update_at = models.DateTimeField(auto_now=True, editable=False) def placeorder(self): self.save() def __str__(self): return self.user.username class Address(models.Model): eighteen_choice = { ('Yes','Yes'), ('No','No') } phoneNumberRegex = RegexValidator(regex = r"^\d{10,10}$") pincodeRegex = RegexValidator(regex = r"^\d{6,6}$") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username my views.py class Checkout(View): def post (self, request,): user = request.user address = Address.objects.filter(user=request.user) ids = … -
Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name [duplicate]
How can I fix this error? NoReverseMatch at /tr/super/user/ Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name. -
How to define mongodb ArrayField in Djongo's model
class question(models.Model): question_id = models.IntegerField() choice = models.CharField(max_length=100) tags = models.ArrayField(models.CharField(max_length=100)) ERROR: packages\djongo\models\fields.py", line 116, in _validate_container for field in self.model_container._meta._get_fields(reverse=False): AttributeError: 'CharField' object has no attribute '_meta' I want to add a ArrayField in my models using djongo models. i hope 'tags' looks like ['tag1', 'tag2', 'tag3' ...]. But djongo requeirs model_container, but i only want an array contains strings, not a model ,please help~~ -
Django - Pagination display
I am having an issue figuring out my pagination for django. Following the docs everything works correctly if I am on the first page or the last page, but I have code duplicating. Everything I have tried I end up getting some sort of exception, mostly empty page exception. I understand that this is because my solutions involve not checking if page_obj.has_previous or .has_next. I am not sure how to solve this and any help would be greatly appreciated. I will attach a screen shot so you can see what I mean. pagination: <div class="pagination justify-content-center pt-3"> <nav aria-label='pagination'> <ul class="pagination step-links"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label='Previous'> <span aria-hidden='true'>&laquo;</span> </a> </li> <li class="page-item"> <a class='page-link'> {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </a> </li> {% endif %} {% if page_obj.has_next %} <li class="page-item"> <a class='page-link'> {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </a> </li> <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label='Next'> <span aria-hidden='true'> &raquo; </span> </a> </li> {% endif %} </ul> </nav> </div> As you can see the '2 of 3' gets duplicated. I see exactly why it gets duplicated in my code but if I delete one of the list items … -
Django / Nginx / uWSGI - CSRF verification failed
I am trying to authenticate myself on my server by making a POST request using python requests module. Unfortunately I have the following error : Forbidden (403) CSRF verification failed. Request aborted. I have been trying other people Nginx's configuration (see here, here, or here) but the request still fails. I am not familiar with this task. Can someone help me figure out my mistake please? Code with the requests on the client side import requests username_django = 'username' password_django = 'password' server_django_ca = '/path/to/ca.pem' login_url = 'https://login_url' api_url = 'https://api_url' def get_django_authentication_token( login_url, username, password, server_django_ca ): #hilens.info('NOW AUTHENTICATING USER') request_session = requests.Session() request_session.headers.update({'referer': 'HiLens'}) response = request_session.get( login_url, verify=server_django_ca ) token = response.cookies['csrftoken'] print(f'Token 1 = {token}') headers = {'X-CSRFToken': token} # THIS REQUESTS FAILS - returns a csrf verification failed login_response = request_session.post( login_url, data={ 'username':username, 'password':password, 'next':'/ihm_maquette/set_hi_lens_detection'}, verify=server_django_ca, headers = headers ) print(login_response.text) token = request_session.cookies['csrftoken'] print(f'Token 2 = {token}') if login_response.status_code == 200: #hilens.info('AUTHENTICATION WORKED') return request_session, token else: print('Login response error') def send_post_request_to_django( username_django, password_django, login_url, api_url, server_django_ca, bboxes ): datas = {} for bbox in bboxes: label = int(bbox[4]) if label == 0: datas['label'] = 'No Mask' elif label == 1: datas['label'] = … -
Heroku not updating database
Recently I deployed my Django blog app in Heroku, its running fine. When I create a new account or blog post, it will updated easily, but after a hour, its not there. every time, db. resets to the old value. how can I pass over it? -
Viewing s3 files in browser
I have created a bucket in s3 and successfully uploaded files to it with django storages. However, when I try to access the files in the browser, I get the following error: IllegalLocationConstraintException The eu-south-1 location constraint is incompatible for the region specific endpoint this request was sent to. I have also realised I do not have region name included in my URL(https://docs.s3.amazonaws.com/media/admin/2.pdf...). Could that be the problem? If so, how do I set it to append the region name? What could be missing here? -
I have models four models called Profile, Experience, Work Education, Social Work. How can I make something like this on admin panel?
I tried using Jazzmin theme for my admin but couldn't build something like this. I want Profile, Experience and other models in horizontal line in admin panel. -
Django UUIDField default value
I have a django model to which I would like to add a UUIDField : uuid = models.UUIDField( default = uuid.uuid4, unique = True, editable = False ) I'd like this uuid to be unique, however at migration of an existing database, I have the following error : django.db.utils.IntegrityError: (1062, "Duplicate entry '3ba46cb5f7f340ffa43e348cb789901a' for key 'carbon.uuid'") How can I provide to default an other uuid if this one is already used ? -
i want to see all the users in django admin panel and i can select more than one user
hello i had done some modification in models and get the User.username and inserted them in a user_list and in multiselectfield(choices=user_list) is was working fine but in the case as i made/create a new user and i go to the application to select multiple users, my newly made user is not showing there until i restart the django server my model is like that: class Video(models.Model): listo = [] user = User.objects.all() for i in user: a = (str(i), str(i)) listo.append(a) print("this is listo", listo) caption = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y",null=True,blank=True) show_to = MultiSelectField(choices=User.username) # show_to = models.ForeignKey(User, on_delete=models.CASCADE) url_video= models.URLField(blank=True) def __str__(self): return self.caption the thing i want is to instantly show the newly made user in the django application so i could not restart the server again and again. thanks in advance! -
Is it secure to use firebase tokens for authentication between my server and an application?
I'm thinking about using firebase to authenticate users. Users could sign up via a pyqt app. Their email address and password would be sent via a POST request to my server (Django). On my server, I would use firebase (pyrebase) to sign them up. I would then store the firebase token in the database on my server, and also return the token to the user and save it there locally. Afterwards, I would always (or until the user logs in again which would return a new token) use this token to authenticate the user and let them access my database. Would this be secure? Something like this: On sign-up: User: token = requests.post(url, {"email": email, "pwd": pwd) Server: response = auth.create_user_with_email_and_password(email, pwd) token = response['idToken'] c.execute('INSERT INTO Tabel (email, token) VALUES(?, ?)', (email, token)) return token After sign-up: User: some_data = requests.post(url, {"token": token, "email": email) Server: token_in_database = c.execute("SELECT token FROM Tabel WHERE email = (?)", (email,)).fetchone() if token == token_in_database: return some_data -
TypeError: Test loader returned an un-runnable object
Not sure what these test errors are in Django when I try running: python shepard.py test --settings=core.settings.test Tests in each django app failing with: Error in shepherd.core.tests.test_exampleapp TypeError: Test loader returned an un-runnable object. Is "shepard.core.tests.test_authorization" importable from your current location? Maybe you forgot an __init__.py in your directory? Unrunnable object looks like: None of type <class 'NoneType'> with dir ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] -
Problem with aldryn_form after update Django and Django CMS
I'm trying to update my requirements.txt I got Django=1.11.29, DjangoCMS=3.7.4, aldryn-forms=5.0.4 and try to update to => Django=3.2, DjangoCSM=3.9.0, aldryn-forms=6.2.1. But when I upgrade packages, ./manage.py migrate and do ./manage.py cms list plugins the FormPlugin is no more installed. Here my origin requirements.txt : aldryn-apphooks-config==0.6.0 aldryn-boilerplates==0.8.0 aldryn-categories==1.2.0 aldryn-common==1.0.5 aldryn-forms==5.0.4 aldryn-translation-tools==0.3.0 asgiref==3.3.4 backports.csv==1.0.7 beautifulsoup4==4.9.1 bleach==3.1.5 cachetools==4.1.1 certifi==2020.6.20 chardet==3.0.4 cmsplugin-svg==0.1.2 cssselect==1.1.0 cssutils==1.0.2 defusedxml==0.6.0 dj-database-url==0.5.0 Django==1.11.29 django-absolute==0.3 django-admin-sortable2==0.7.7 django-appconf==1.0.4 django-appdata==0.3.0 django-bootstrap3==14.1.0 django-ckeditor==5.9.0 django-classy-tags==1.0.0 django-cms==3.7.4 django-cms-tools==0.7.1 django-emailit==0.2.4 django-filer==1.7.1 django-formtools==2.2 django-js-asset==1.2.2 django-macros==0.4.0 django-mptt==0.11.0 django-multiupload==0.5.2 django-parler==2.1 django-polymorphic==2.1.2 django-ranged-response==0.2.0 django-sekizai==1.1.0 django-simple-captcha==0.5.14 django-sizefield==1.0.0 django-sortedm2m==3.0.2 django-standard-form==1.1.1 django-tablib==3.2 django-tools==0.46.1 django-treebeard==4.3.1 djangocms-admin-style==1.5.0 djangocms-attributes-field==1.2.0 djangocms-column==1.11.0 djangocms-file==2.4.0 djangocms-googlemap==1.4.0 djangocms-installer==1.2.3 djangocms-link==2.6.1 djangocms-local-navigation==1.4.1 djangocms-picture==2.4.0 djangocms-slider==0.2.5 djangocms-snippet==2.3.0 djangocms-style==2.3.0 djangocms-text-ckeditor==3.10.0 djangocms-video==2.3.0 easy-thumbnails==2.7 et-xmlfile==1.0.1 html5lib==1.1 icdiff==1.9.1 idna==2.8 importlib-metadata==1.7.0 jdcal==1.4.1 jsmin==2.2.2 lxml==4.5.2 odfpy==1.4.1 openpyxl==3.0.5 packaging==20.4 Pillow==7.2.0 pprintpp==0.4.0 premailer==3.7.0 pyparsing==2.4.7 python-slugify==4.0.1 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 six==1.15.0 sorl-thumbnail==12.6.3 soupsieve==2.0.1 sqlparse==0.3.1 tablib==2.0.0 text-unidecode==1.3 typing-extensions==3.10.0.0 tzlocal==2.1 Unidecode==1.1.1 urllib3==1.25.10 webencodings==0.5.1 xlrd==1.2.0 xlwt==1.3.0 YURL==1.0.0 zipp==3.4.1 Here my requirements.txt after upgrade : aldryn-apphooks-config==0.6.0 aldryn-boilerplates==0.8.0 aldryn-categories==1.2.0 aldryn-common==1.0.5 aldryn-forms==6.2.1 aldryn-translation-tools==0.3.0 asgiref==3.4.1 backports.csv==1.0.7 beautifulsoup4==4.9.3 bleach==4.0.0 cachetools==4.2.2 certifi==2021.5.30 chardet==4.0.0 cmsplugin-svg==0.1.2 cssselect==1.1.0 cssutils==2.3.0 defusedxml==0.7.1 dj-database-url==0.5.0 Django==3.2.6 django-absolute==0.3 django-admin-sortable2==1.0 django-appconf==1.0.4 django-appdata==0.3.2 django-bootstrap3==15.0.0 django-ckeditor==6.1.0 django-classy-tags==2.0.0 django-cms==3.9.0 django-cms-tools==0.7.1 django-emailit==0.2.4 django-filer==2.0.2 django-formtools==2.3 django-js-asset==1.2.2 django-macros==0.4.0 django-mptt==0.12.0 django-multiupload==0.5.2 django-parler==2.2 django-polymorphic==3.0.0 django-ranged-response==0.2.0 django-sekizai==2.0.0 django-simple-captcha==0.5.14 django-sizefield==1.0.0 django-sortedm2m==3.0.2 django-standard-form==1.1.1 django-tablib==3.2 django-tools==0.48.3 django-treebeard==4.5.1 djangocms-admin-style==2.0.2 djangocms-attributes-field==2.0.0 djangocms-column==1.11.0 djangocms-file==3.0.0 djangocms-googlemap==2.0.0 djangocms-installer==2.0.0 djangocms-link==3.0.0 djangocms-local-navigation==1.4.1 djangocms-picture==3.0.0 … -
How to sync two database data in django tests?
I am using two databases, default and readonly, as the name suggests that default is used to write and readonly used to read. Till this, it works fine. and Then in my models, I changed database managers for reading from particular database data, as I cannot use Django routers due to the complexity. in models, there is a Manger for readonly database, like this: objects = models.Manger() readonly = objects.db_manager("readonly") And In views, I am using Model.readonly.all(). So far so good. Problem comes in while testing views. def test_event_view(): e = Event.objects.create(self.event_data) url = reverse('event-detail', kwargs={'slug': e.slug}) response = self.client.get(f"{url}?state=Florida") self.assertOK(response) # Should be 2 == status_code/100 Because view is reading from readonly and this test is creating an object in default, so it says event does not exist on readonly database. SO my question is how to handle this situation? -
CreateView switch model
i have a problem with my CreateView. I wish I could have two different models that change based on the url it finds. I also have problems with success_url, I don't know how to pass it a parameter. url.py path('crea-<tipo>', CreaView.as_view(), name="crea") views.py class CreaView(StaffMixin, CreateView, tipo): if tipo == "gruppo": model = Gruppi elif tipo == "esercizio": model = Esercizio fields = '__all__' template_name = 'staff/crea.html' success_url = '/backoffice/lista/<tipo>' -
Unable to customize the primary key pattern in Django
I have 3 models, Student, Course and Fee. I want to create a report which will bring all the data contained by these 3 models, together, with an ID of its own. The models: class Student(models.Model): roll_number=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class CourseChoices(models.Model): courses=models.CharField(max_length=30, blank=True) def __str__(self): return self.courses class Course(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) course=models.ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) amount_to_be_paid=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount_to_be_paid=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.IntegerField() Now, a student may pay his/her fee in installments, so that will create multiple instances in the track report. I want the user to track each transaction with the primary key/id. Below is an example: I have additional model which brings everything together: class Report(models.Model): id = models.IntegerField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) fee = models.ForeignKey(Fee, on_delete=models.CASCADE) def _get_next_id(self): last = Report.objects.all().aggregate(models.Max('id'))['id__max'] print(last) # last = Report.objects.aggregate(max_id=models.Max('id'))['max_id'] if last: last += 1 self.id = "{}{:04d}".format('HB', last) elif not last: last = 1 self.id = "{}{:04d}".format('HB', last) def save(self, *args, **kwargs): if not self.id: self.id = self._get_next_id() super().save(*args, **kwargs) The view for Fee: def fee_view(request): if request.method=='POST': fm_fee=FeeForm(request.POST) if fm_fee.is_valid(): fee=fm_fee.save() Report.objects.create(student=fee.roll_number, fee=fee, course=Course.objects.get(roll_number=fee.roll_number)) fm_fee=FeeForm() return render(request, 'account/fee.html', {'form1':fm_fee}) else: fm_fee=FeeForm() return render(request, 'account/fee.html', … -
Django JWT auth: Why the view returns always AnonymUser?
I am using JWT auth to login users. Username and password are sent in Body, however, in the customized response, an anonymUser is always returned. I think the problem is that in settings.py stands 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', and when I generate a token before and then send it in Headers the user is identified. Bit the thing is, that I cannot use 2 views in order to generate token and decode it, everything has to be in one view and I don't know how to login the user in the view and then get token and decode it. @api_view(('POST',)) def check_token(request): token_refresh = RefreshToken.for_user(request.user) print(request.user) # AnonymUser print(request.user.id) # None print(str(token_refresh.access_token)) data = {'token': str(token_refresh.access_token), 'refresh_token': str(token_refresh)} aT = str.encode(str(token_refresh.access_token)) try: valid_data = TokenBackend(algorithm='HS256').decode(aT, verify=False) print(valid_data) data['uuid'] = valid_data['user_id'] data['validUntil'] = valid_data['exp'] data['clientId'] = 'default' return JsonResponse(data) except ValidationError as v: print("Validation error", v) -
TemplateDoesNotExist at /konfigure
TemplateDoesNotExist at /konfigure index.html Request Method: GET Request URL: http://127.0.0.1:8000/konfigure Django Version: 3.2 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /home/ramil/Desktop/plandeki/env/bin/python Python Version: 3.9.5 Python Path: ['/home/ramil/Desktop/plandeki/trampulin_app', '/home/ramil/miniconda3/lib/python39.zip', '/home/ramil/miniconda3/lib/python3.9', '/home/ramil/miniconda3/lib/python3.9/lib-dynload', '/home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages'] Server time: Wed, 04 Aug 2021 11:10:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/ramil/Desktop/plandeki/trampulin_app/templates/index.html (Source does not exist) django.template.loaders.filesystem.Loader: /home/ramil/Desktop/plandeki/build/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/django/contrib/auth/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/rest_framework/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/trampulin_app/konfigurator/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/trampulin_app/upcservice/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ramil/Desktop/plandeki/env/lib/python3.9/site-packages/cloudinary/templates/index.html (Source does not exist) -
how do I search with Comma-separated values in Django rest framework?
I have values in database like : Injection Mold Injection Mold,PVC Mold Stack Mold PVC Mold I am filtering it through get method. I pass queries like : http://0.0.0.0:8000/api/v1/plastic_mold/filter/?type[]=Stack%20Mold,Injection Mold,Gas Injection Mold,PVC Mold the results I get are from only Single value fields. How do I search and get values from Injection,PVC Mold these, comma seperated values. Here is my code : if 'type[]' in request.query_params: type = request.GET.get('type[]').split(',') #dict(request.query_params)['type[]'] print(type) for item in type: query1.add(Q(type__icontains=item), Q.OR) Please help me out! -
How to setup python app in cpanel on HostGator?
I have developed one website using Django I want to host the website in HostGator but in HostGator c panel there is no setup python in software's what to do how set path in HostGator -
Print all attributes from an object with Django templates
I am a novice programmer, I am learning python and Django on my own. I got stuck in a part of my application: I have many models with many attributes, and I have a window and a template for each of them. The idea is to show in each one, a table with all its content with an sql query in the file view.py objects.all () My code: MODELS.PY from django.db import models class MFuel(models.Model): marca = models.TextField(db_column='Marca', blank=True, null=True) # Field name made lowercase. modelo = models.TextField(db_column='Modelo', blank=True, null=True) # Field name made lowercase. potencia_electrica_kw = models.BigIntegerField(db_column='Potencia_electrica_kW', blank=True, null=True) # Field name made lowercase. fecha_oferta = models.DateTimeField(db_column='Fecha_oferta', blank=True, null=True) # Field name made lowercase. pais_proyecto = models.TextField(db_column='Pais_Proyecto', blank=True, null=True) # Field name made lowercase. proyecto = models.TextField(db_column='Proyecto', blank=True, null=True) # Field name made lowercase. uds = models.FloatField(db_column='Uds', blank=True, null=True) # Field name made lowercase. precio_eur = models.FloatField(db_column='Precio_EUR', blank=True, null=True) # Field name made lowercase. precio_usd = models.FloatField(db_column='Precio_USD', blank=True, null=True) # Field name made lowercase. precio_unitario_eur = models.FloatField(db_column='Precio_Unitario_EUR', blank=True, null=True) # Field name made lowercase. ratio_eur_kw = models.FloatField(db_column='Ratio_eur_KW', blank=True, null=True) # Field name made lowercase. largo_mm = models.FloatField(db_column='Largo_mm', blank=True, null=True) # Field name made lowercase. ancho_mm = models.FloatField(db_column='Ancho_mm', blank=True, null=True) … -
How to list only active users in dropdown menu
I want to list all active users in dropdown list. But all users are listed in the dropdown How can I do it? template <form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-primary btn-sm">Assign</button> </form> forms class AssignForm(forms.ModelForm): class Meta: model = Customer fields = ('user',) views form = AssignForm(request.POST or None) if request.POST: customer_id = request.POST.get('customer_id', None) customer = Customer.objects.get(id=customer_id) user = UserProfile.objects.get(id=request.POST.get('user', None)) customer.user = user customer.save() # form.save() return redirect('user:customer_list') models class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) ...