Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Daphne NotImplementedError after upgrade to Python 3.8
We upgraded an existing project from Python 3.7.2 to Python 3.8 and now we are facing an issue when starting the server with python manage.py runserver. I tried reinstalling the venv, reinstalling Python, updating PIP, recloning the project, restarting the PC (..). Our requirements are as follows: Django channels channels_redis daphne This is the full error traceback after the runserver command: Traceback (most recent call last): File "MYAPPDATAPATH\appdata\local\programs\python\python38\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "MYAPPDATAPATH\appdata\local\programs\python\python38\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "MYPROJECTPATH\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "MYPROJECTPATH\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "MYPROJECTPATH\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "MYPROJECTPATH\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "MYPROJECTPATH\env\lib\site-packages\channels\apps.py", line 6, … -
how can I avoid getting duplicates: account?
I am trying to install pip3 install django-allauth to prevent login before email confirmation , but at moment to setup settings.py. I got the following error, but I dont want to rename all the project name, because it gonna affect the complete project. is there a way to achieve this without too much changes? xxxxxx@xxxxxx:~/Documents/blackowl$ python3 manage.py makemigrations account Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_com mand_line utility.execute() File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/apps/registry.py", line 95, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth' , 'allauth.account' , 'allauth.socialaccount' , 'allauth.socialaccount.providers.github' , 'apps.website', 'apps.account' ] 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', ] ROOT_URLCONF = 'blackowl.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) -
UnboundLocalError - local variable 'ret' referenced before assignment
I did a simple method to calculate the division between two values: def porc_pago_ct(self, *args, **kwargs): for contrato in self.contrato.all(): if contrato.nr_contrato != None: ret = (float(contrato.total_pago_brl)/float(self.valor_total_brl))*100 else: ret = 0 return ret Everything works well until I put this conditional statements. After this I tried many ways, but everytime I got: UnboundLocalError at /lista/2/ local variable 'ret' referenced before assignment What I`m missing here? -
Django database tables created under wrong schema
I created a Django application and connected it to SQL Server with a trusted connection. When I migrate, Django is creating a new schema name (trusted connection username) in the database and adding this on all tables as prefix. By my IT department convention, all tables should be created with the 'dbo' prefix. The most interesting part is: When I access the database from SQL management studio (also with trusted connection), and create a new database, I do not have this issue, it creates as 'dbo.table_name'. Does anybody knows how can I fix it? See below better example and some code. Summary: Django is creating: 'my_username.table_name' I need: 'dbo.table_name' My django settigs.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dabase_name', 'HOST': 'database_host', 'USER': '', 'OPTIONS': { 'driver': "ODBC Driver 17 for SQL Server", 'Trusted_Connection' : 'Yes', } } } One of my models (table) as example: class Sap_module(models.Model): sap_module = models.CharField(max_length=2, unique=True) available = models.BooleanField(default=True) def __str__(self): return self.sap_module -
Django cursor dictfetchall is not returning the dictionary correctly
I'm using the dictfetchall from the Django documentation in order to return a dictionary for use in AJAX GET. def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] In this function: def UserData(request): cursor = connection.cursor() cursor.execute("SELECT user_id, email FROM users_user LIMIT 2") row = dictfetchall(cursor) return HttpResponse(row) And supposedly it should be returning this: [{'user_id': 4, 'email': 'ewoif@rjhior.com'}, {'user_id': 25, 'email': 'efweew@ferfr.com'}] But it is returning this: {'user_id': 4, 'email': 'ewoif@rjhior.com'}{'user_id': 25, 'email': 'efweew@ferfr.com'} No [ ] and no comas , Why? -
Django `get_or_build` similar to `get_or_create`?
I'm curious if there's a way to do something conceptually like a "get_or_build" for an object, without saving it (yet), so you can reference itself to set a field before saving. Similar to Ruby's find_or_create_by or find_or_initialize_by with a block. For instance, given the following model: class User(models.Model): unique_id = models.UUIDField(default=uuid4) first_name = models.CharField() last_name = models.CharField() meta = models.CharField() and an example of creating a User user, created = User.objects.get_or_create(first_name="Jane", last_name="Doe") let's say I wanted to also set the meta column to whatever the default value for unique_id is in this situation, on initialization. I would have to do something like this, since it would be available when initializing the object: user = User.objects.filter(first_name="Jane", last_name="Doe") if not user: user = User(first_name="Jane", last_name="Doe") user.meta = user.unique_id user.save() is there anything like: user, built = User.objects.get_or_build(first_name="Jane", last_name="Doe") if built: user.meta = user.uuid user.save or a way to reference from within get_or_create: user = User.objects.get_or_create(first_name="Jane", last_name="Doe", meta=self.unique_id) -
Django join unmanaged tables
I have a four models which each contains their own data. The models are: Category (contains department_id foreign key) Department (contains data, no foreign key) ProductCategory (join table containing only product_id and category_id) Product (contains data with no foreign key) # models.py (excluded the rest for brevity) from django.db import models class Department(models.Model): department_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'department' class Category(models.Model): category_id = models.AutoField(primary_key=True) #department_id = models.IntegerField() department = models.ForeignKey(Department, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'category' class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.CharField(max_length=150, blank=True, null=True) image_2 = models.CharField(max_length=150, blank=True, null=True) thumbnail = models.CharField(max_length=150, blank=True, null=True) display = models.SmallIntegerField() class Meta: managed = False db_table = 'product' class ProductCategory(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: managed = False db_table = 'product_category' unique_together = (('product', 'category'),) From my endpoint, I need to get all products in a department and return the response in the following format: "rows": [ { "product_id": integer, "name": string, "description": string, "price": string, "discounted_price": … -
Why multiple ajax requests in each other do not execute?
I have multiple ajax functions inside each other, but only the first ajax request is executed and I do not know why! I have added some alert fields to see how far it gets. I am using django environment for this. So for example when the bidnow-BTN is clicked this jquery should execute, but for some reason the after the first ajax request the page actually refreshes and adds something like /?bidPrice=100001 to the end of the url of the page. This should not happen. $("#bidnow-BTN").click(function(){ var varurl = document.URL var itemId = varurl.split(/\//)[4] $.ajax({ url : "{% url 'User ID' %} ", method : "GET", success : function (data) { var varurl = document.URL var itemId = varurl.split(/\//)[4] var username = data.username alert("Got here: " + username) $.ajax({ url : "{% url 'Bidding ID' %} ", method : "GET", success : function (data) { alert("Does NOT reach this point") for(var i = 0;i<data.users.length;i++){ if(data.users[i].username==username) { var id = data.users[i].id } else{ } } $.ajax({ // kinda checked url : "{% url 'List Items' %} ", method : "GET", success : function (data) { var varurl = document.URL var itemId = varurl.split(/\//)[4] for (var i = 0 ; i<data.items.length;i++){ if(itemId … -
Calculating fields with filters in Django
I am extremely new to Django and kinda new to python and programming in general, so i may be asking a dumb question. I am trying to track medications in our inventory at work. Here is my model for the inventory in our safe class Safe(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date_created = models.DateTimeField(auto_now=True) drug_name = models.ForeignKey('components.Drug', related_name='drug_remove', on_delete=models.PROTECT, default=0) amount_removed = models.IntegerField(blank=True, null=True) amount_added = models.IntegerField(blank=True, null=True) incident_number = models.CharField(max_length=20, default=0, blank=True) patient_name = models.CharField(max_length=20, default=0, blank=True) medic_unit = models.ForeignKey('components.MedicUnit', related_name='medic_unit', on_delete=models.PROTECT, blank=True) free_text = models.CharField(max_length=1000, default=0, blank =True) drug_total = computed_property.ComputedIntegerField(compute_from='add_drug') I would like to store the medication total for each drug in the database. I understand from researching this that storing totals isn't best practice in most cases but I believe this is one exception. Obviously the calculated integer field isn't the answer, but none of my research has gotten me any closer to the answer. My guess is that I first need to filter by 'drug_name' and then calculate the added or subtracted drugs from the previous total in a function within my model. Thanks ahead of time for any help. -
Changing model field value to True after expiration time
I am in the process of creating a simple car rental project in Django. I have a view in which the user must enter the value for how many days he wants to rent a car and press the "Rent" button. In this situation the "is_car_available" field of the "Car" model gets False value and it is not possible to rent. @login_required def rent(request, pk): car_to_rent = Car.objects.get(pk=pk) if request.method == 'POST': form = RentingForm(request.POST) if form.is_valid(): days = form.cleaned_data['days'] total_price = car_to_rent.car_price * days reservation = Reservation.objects.create(how_many_days=days, car=car_to_rent, booker=request.user, total_price=total_price) car_to_rent.is_car_availible = False car_to_rent.save() content_for_frontend = { 'car_to_rent': car_to_rent, 'form': form, } return render(request, 'rental/rent.html', content_for_frontend) else: return HttpResponseRedirect('/') The Reservation model has the "expiration_date" method, which is calculated after adding the rental date to the number of days. I would like to see "is_car_available" change to True at the end of the rental. Any ideas how to solve it? -
how can I prevent users login before email confirmation?
I am new in django , and I am trying to configure login based on email confirmation, but however when I use my signup , and I tried to login , then I found a issue that I can login without email confirmation , how can I fix this ? I also modify the models to login with email instead of username. I want to prevent users login before email confirmation . my settings looks like this , and email confirmation uses TLS LOGIN_REDIRECT_URL = '/account/profile' LOGOUT_REDIRECT_URL = '/' DEFAULT_EMAIL_FROM = EMAIL_HOST_USER models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have … -
PDF generation not working after upgrading from Django 1.8 to 2.2
After upgrading Django from 1.8 to 2.2, trying to generate a pdf now sends me to a page that says This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access denied</Message> </Error> Log files show that it requests information from SQL, but other than that no messages are generated at all. My config/base.py file sets the url like this: REPORTS_PATH = '/company/{}/reports/' The code that produces the document is this: from celery import shared_task import os import tempfile import pytz import json import subprocess import datetime from django.conf import settings @shared_task(default_retry_delay=1000, max_retries=10) def create_required_document(company_id, incident_id, document_id): import django django.setup() from core.utils import S3Uploader, download_file_from_s3 from .models import Incident, RequiredDocumentType, CompanyRequiredDocumentType, RequiredDocumentSubmissionEvent, IncidentSentToClinicEvent from company.models import Company company = Company.objects.get(id=company_id) incident = Incident.objects.get(id=incident_id) document = RequiredDocumentSubmissionEvent.objects.get(id=document_id) required_doc_type = document.type company_required_doc_type = \ CompanyRequiredDocumentType.objects.filter(company=company, report_type=required_doc_type)[0] with tempfile.NamedTemporaryFile( mode='w') as config_file, tempfile.NamedTemporaryFile() as input_text_file, tempfile.NamedTemporaryFile() as output_file: template_text = company_required_doc_type.template_text try: input_text_file.write(bytes(template_text, 'UTF-8')) input_text_file.seek(0) except Exception as e: raise e if document.signature_url is not None: signature_file_name = download_file_from_s3(url=document.signature_url) params['signatureFilePath'] = signature_file_name try: json.dump(params, config_file, indent=4, sort_keys=True) config_file.seek(0) except Exception as e: raise e cmd = 'java -jar /home/ec2-user/wim/jPDF/FormTextToPDF.jar {}'.format(config_file.name) process … -
How to insert an image or video in html?
I have a django page that shows me a video loaded from a directory. I have a form with a drop-down list: <form name="formulario" enctype="multipart/form-data" method="POST" action="" name="formulario"> {% csrf_token %} {{ form.as_p }} <select name="type" id="type"> <option selected>Select the type of file</option> <option>Video</option> <option>Picture</option> <option>Gif</option> </select> <br><br> <input type="submit" class="btn btn-success" value="Upload"/> <a href="{% url 'fileupload:delete' %}" onclick="confirm('Are you sure you want to delete the files?')" class="btn btn-success">Delete Files</a> What I intend to do is that if the drop-down list selects video, I will insert a video and if I select a picture, I will insert an image. For example: {% if valor == video %} <video src='{{videofile.videofile.url}}' width="640" height="480" controls autoplay></video> {% endif %} {% if valor == picture %} <img src='{{videofile.videofile.url}}' width="640" height="480" controls autoplay></video> {% endif %} In the project I have a static folder where the files are stored, either images or videos, so the user searches for the image or video, this is saved in the folder and is displayed on the page. How could I do this? Regards. -
Django REST File Upload Error curl: (26) couldn't open file
I am trying to make an API endpoint using Django REST Framework which allows for file uploads. I have implemented a basic APIView to do this as per the Django REST Framework documentation but am still receiving the error curl: (26) couldn't open file file=@/Users/espresso/Documents/Work/Work\ Maps/Extracted\ Maps/abb1.geojson" views.py class FileUpload(APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): file_obj = request.FILES['file'] return Response({"status":"successful"}, content_type="application/json") urls.py urlpatterns = [ url(r'^api/v1/upload/(?P<filename>[^/]+)$', views.FileUpload.as_view(), name='upload'), ] Curl $ curl http://127.0.0.1/dashboard/api/v1/upload/ \ --request PUT \ -H "Content-Type: multipart/form-data" \ -F "file=@/Users/espresso/Documents/Work/Work\ Maps/Extracted\ Maps/abb1.geojson" \ -F "filename=abb1.geojson" -
GraphQL with Django
I have a slight problem understanding how to restrict graphql queries. How can I make sure that a user who is not allowed to see a certain information can not get it through a relationship from a model? I have three different user types which have certain permissions. Each user can only access the information which he's allowed to access from the root query. But I can still access information from a user which he should not see if I have a certain depth of query and use certain relationships? Can someone please tell me how to restrict the query output or how to restrict it in the schema.py? Thanks in advance -
django dates and pandas dates conversion
I am trying to compare dates pulled from my Django database, and dates from a spreadsheet imported and processed using pandas. How can I make them equal for comparison sake? I don't need the time, just the date I do have tz support on in my settings.py, but this is because it is needed in other areas of my application. from django.views import generic from django.views.generic import TemplateView from django.urls import reverse_lazy from django.urls import reverse from .models import ClientJobs from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import datetime, time from datetime import date from datetime import datetime import pandas as pd class uploadView(TemplateView): template_name = 'uploadPage.html' def get(self, *args, **kwargs): #read excel file, turn into dataset, remove date values set to NaT (no date) and set as 0 instead excelFile = (r'C:\Users\matth\testing\Old.xlsx') dataSet = pd.read_excel(excelFile).fillna(0) lastDataSet = ClientJobs.objects.filter(dataSetNumber = 1) oldVisitDate = lastDataSet[0].visitDate newVisitDate = dataSet.iloc[0][1].to_pydatetime() print(oldVisitDate) print(newVisitDate) return super().get(*args, **kwargs) This returns: 2019-04-18 05:00:00+00:00 2019-04-18 00:00:00 As you can see the queried result has tz info, and the pandas result does not. My goal is to compare the dates to see if they are equal. I don't need the time, just the … -
Setting background image via CSS in Django project
I think I'm doing everything pretty right, but it still doesn't work. Here are my structure and html file: {% load static %} <style> body{ margin:0; padding: 0; background: url("{% static 'aztu.jpg' %}"); } </style> -
django admin site override the change_list.html
is their any possible to override the change_list.html? i just want to add another table/listview, models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) admin.py class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') def lrn(self, obj): return obj.Student_Users.lrn -
Django - how to filter though multiple manyTomany relationship layers
Consider the following setup: class ModelA(models.Model): foreign = models.ForeignKey(ModelB, on_delete=models.CASCADE) children = models.ManyToManyField('self', related_name="parent", symmetrical=False, blank=True) class ModelB(models.Model): caption = models.CharField(db_index=True, max_length=50, null=False, unique=True) children = models.ManyToManyField(ModelC, blank=True) class ModelC(models.Model): ...lots of fields Now, given the pk of a ModelA Object, I want to get and filter all the related ModelC Objects. Here is what i'm trying to achieve efficiently: modelC_objects = ModelA.objects.filter(parent__in=[modelA_id]).distinct().foreign.children .filter(pk__lte=last_id) .exclude(is_private=True) .order_by('-pk')[0:100] .prefetch_related("other") ) Obviously that doesn't work. I am currently doing something ugly like this: modelA_objects = ModelA.objects.filter(parent__in=[modelA_id]).distinct() modelC_querysets = [modelA.foreign.children for modelA in modelA_objects] if modelC_querysets: modelC_objects = modelC_querysets[0] modelC_querysets.pop(0) for x in modelC_querysets: modelC_objects = modelC_objects | x filtered = (modelC_objects.filter(pk__lte=last_id) .exclude(is_private=True) .order_by('-pk')[0:100] .prefetch_related("other") ) How can I achieve what I attempted? -
Django advanced query - objects of a Foriegnkey?
I have a Django models where I have this : class Patient(models.Model): FirstName = models.CharField(max_length=264) LastName = models.CharField(max_length=264) Address = models.TextField(blank=True) Telephone_no = models.CharField(max_length=100,blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='patients') class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') original = models.ImageField(upload_to = user_directory_path, validators=[validate_file_extension],verbose_name = 'Image') enhanced = models.ImageField(upload_to=analyses_directory_path, blank=True) segmented = models.ImageField(upload_to=analyses_directory_path, blank=True) class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') pre_analysed = models.ImageField(upload_to=analyses_directory_path, blank=True) analysedimage = models.ImageField(upload_to=analyses_directory_path, blank=True) so I want to make queries based on the current user which is user = request.user this is possible in the patient model case as I can make Patient.objects.filter(user=user) but i can't make it the other 2 models is there any idea how I can do this? I didn't add the user FK as I thought I wouldn't need it but now I do? do i need to add it ? can I make a query without adding the field ? -
How to add category from user interface using Django
I have a problem related with category section: when I rm by db.sqlite3 (I'm using linux terminal), I can't add category manually from user interface (later UI). I have empty section without + to add categories: But when I accessing my admin panel, I can add categories manually without any problems(I don't know why, but this + symbol exist: After this manipulation I can select this category in UI. I need a solution, that would allow user add category from UI, solution, in which not only I can add some categories from admin panel and let users choose from them. I need to add this + sign in my UI. Some code: from views.py def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html', content) post_form.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-primary" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
Django ModelChoiceField doesn't validate the form
The choices are displayed correctly from the queryset. The problem is that the form does not pass the validation block code. I've been trough all posibilities on similiar questions here on stack and nothing suits me. This is my form: class AddContract(forms.Form): ********************* city = forms.ModelChoiceField(queryset=None, widget=forms.Select, required=True,to_field_name='city', initial=0) ********************* def __init__(self, *args, **kwargs): sub_user = kwargs.pop('sub_user', None) super(AddContract, self).__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.filter(sub_user=sub_user) This is my view: if request.method == 'POST' and 'addcontract' in request.POST: addcontract_form = AddContract(request.POST) if addcontract_form.is_valid(): ********** city= addcontract_form.cleaned_data['city'] ********** addcontract_form = AddContract(sub_user=sub_user) -
Change color of form field if it's not the first (default value)
I am trying to change the color of a form field (or put a border around the field) if the value is not the default (first option) and for text fields if there is text in the field. For example, the form has five (5) fields and if any of those fields has a value that is not the very first (default) option or has text in the field if it's a text field, I want to change the color of the field background or put a border around it to denote that the field has changed for the user that is searching. I want to change the color or add a border to all fields in the form. Seems like the best way to do this would be to use Javascript to loop through the form fields and check if the selection is the first option but I am not familiar with Javascript and all of the solutions I have found only check if the value is empty, not if the value is the first value or not for multiple fields. I am using basic HTML and Python/Django from a frontend and backend standpoint respectively. Any advice on the … -
Django Form Wizard: Skip a step but still provide data
I am creating a form using django form wizard. The first step is a user selection, but based upon permissions, some users can only create a form for themselves. If this is the case, there is no reason for them to see the user selection step (as the user will just be the current user). I would like to skip this step, but still provide the data (the current user) to the form. Later, I am accessing that step's data to prefill other fields, so I need to save the data somewhere. I could handle this with multiple if checks seeing if the form data exists, if not, get the current user...etc, but this seems messy. Is there a way to tell the form wizard to not totally skip the step, but just not show it? -
problem with connecting Clever Cloud bucket to django with envronment variable
I have a problem to connect my CC bucket to a django application. My bucket looks as follows: Could you please tell me what I have to define as CC_FS_BUCKET? I thought it is: folder:addon-id.host