Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude a worker from the pool available to the beat scheduler?
I have a Django app running on Heroku, with several production instances (different versions of the app, run with different env variables). I am using Celery with Redis and CloudAMQP. The contents of my Procfile: release: python manage.py migrate web: gunicorn {appname}.wsgi worker: celery -A {appname} --concurrency=3 worker beat: celery -A {appname} beat The beat is only used in app A. Only app B is currently using a worker (those dynos are only used in those particular apps). What I'm trying to do is start an app C. It needs a worker to run tasks invoked in the code, but that worker cannot be used to run scheduled tasks - they should all be run from app A. As I understand it, beat uses any free worker from the available pool. Is there a way to exclude a worker provided in app C from those used by beat? -
How to connect Pandas Table with Django Paginator
I created a table that extracts data from two files that are submitted via form. I take this file and display the table. I wanted to add pagination too, but I have a problem with the request that I can't identify. My problem is that when the request on /? Page = 2, it returns to the screen of submitting the file. Is there any other way to do this? This is the function in views.py def czech_margin (request): lines_for_page = None paginator = None data = none if request.method == 'POST' and request.FILES ['myfile']: myfile = order.FILES ['myfile'] myfile2 = request.FILES ['myfile2'] df = treatData (myfile, myfile2) json_records = df.reset_index (). to_json (orient = 'records') print (json_records) date = [] data = json.loads (json_records) #Paginator get data! = None: paginator = Paginator (date, 20) page = request.GET.get ('page') if request.GET.get ('page') is Not None else 1 lines_for_page = paginator.get_page (page) #data = data.to_html () return render (request, 'checa_margem.html', { 'table': lines_for_page }) -
Proper project structuring
I've recently started as the sole developer on a Django project. I'm currently working on updating an endpoint to including validation for incoming PDF documents. The simple validation function follows: def is_valid_certification(stream: BytesIO) -> bool: pdf = PdfFileReader(stream) page: PageObject for page in pdf.pages: if page.extractText().find("<search string>") != -1: return True return False My question is, where is the most pythonic place to store this bit of code? Keeping all the logic within the POST handler seems messy and it's not generic enough to be considered a utility. -
Why command "python manage.py migrate" after success work lock console?
I try to solve following task. I have Django app and I want to start it using Docker. As 'db' I add a container with PostgreSQL or MySQL. In my case I need run "python manage.py migrate" before "python manage.py runserver", so I wrote in docker-compose.yml file in fiels "command" folloving string:sh -c "sleep 20 && python manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000 --noreload". But after applying all migrations command "python manage.py migrate" doesn't stop and doesn't give to run "python manage.py runserver". some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK If I use: docker-compose exec web python manage.py migrate we have same result: some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK After pressing Ctrl + C, we get the following error: ^CException ignored in: <module 'threading' from '/usr/local/lib/python3.7/threading.py'> Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 1307, in _shutdown lock.acquire() KeyboardInterrupt Settings of docker-compose.yml: version: "3.7" services: db: image: postgres restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres … -
How to get the Expense id and passing it to Django view function
I'm struggling with finding the correct way to pass {{expense.id}} to a view function inside Django so that based on the id, I can update the expense detail. Expenses are coming from a model which relates by 'ForeignKey' to the Projects coming from another Model. I need the expense ID before submitting another form which take cares of updating that transaction. view.py def updateTransaction(request, project_slug): id: ? form.py class ExpenseForm(forms.Form): title = forms.CharField() deposit = forms.IntegerField() witdraw = forms.IntegerField() model.py class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='expenses') title = models.CharField(max_length=100) deposit = models.IntegerField(default = 0, null = True) witdraw = models.IntegerField(default = 0, null = True) created_at = jmodels.jDateField(auto_now_add = True, null = True) -
Django & PostgreSQL MemoryError + script not working correctly
I'll start by explaining the architecture of the project. There is a bot on aiogram, through which orders are created. Orders consist of lines (item), price, and order affiliation IDs. Task: The script will process all unpaid orders, and if the order has not been paid for more than N minutes, the product rows are returned to the product table, and the order is deleted. My implementation: while True: users = MyUser.objects.all().exclude(bot_username='null') now = timezone.now() for admin_user_obj in users: for order in User_purchase.objects.raw('SELECT id, time_created, chat_id, balance_to_return FROM user_purchases WHERE is_paid=FALSE and belongs=%s LIMIT 5', [admin_user_obj.id]): if order.time_created + timezone.timedelta(minutes=admin_user_obj.booking_time) < now: try: bot_user = Bot_user.objects.get(belongs=admin_user_obj.id, chat_id=order.chat_id) if order.balance_to_return: bot_user.balance += order.balance_to_return bot_user.active_orders -= 1 bot_user.save() send_order_canceled(order, admin_user_obj) for z in User_purchase.objects.raw('SELECT id, strings, item FROM user_purchases WHERE id=%s', [order.id]): add_strings(z.item, z.strings) except: pass order.delete() SQL queries because MemoryError is thrown otherwise. After launching and monitoring the logs, the script starts spamming me with the product line: enter image description here And the client told me that his 1 line of goods turned into 23 million, and several lines in the reservation turned into 7 million lines. To say that it surprised me is to say nothing. models.py class User_purchase(models.Model): … -
Passing in context variables to form
I want to pass in the parent_username variable in the below view function to the LevelTestModelForm, so that I could fill in one of the form inputs as that variable automatically. Here is the view: def LevelTestView(request, pk): parent_username = User.objects.get(pk=pk).username form = LevelTestModelForm() if request.method == "POST": form = LevelTestModelForm(request.POST) if form.is_valid(): form.save() return reverse("profile-page") context = { "form": form } return render(request, "leads/leveltest.html", context) I hope you guys could help. Thanks a lot. -
How to Optimize queries inside for loop in Django
I have a legacy code of application on which I am working. I installed Django debug toolbar and noticed nearly 1600 queries being executed on a single page of the application on a single request. After observing the trace of Django debug toolbar I noticed that the view function has nested queries inside for loop which calls model method. And further model method has another for loop inside first for loop calling another model method. Now after reading about django query optimization on the internet I learnt that this is very bad practice. But after spending 2 days on it I am not able to figure out how to optimize it. I am not able to figure out any alternate method with which I can replace that for loop with a query which brings all the data in one query. Below I am posting the Models, respective model methods and views which are being called. views.py def course_modules(request, course_id, msg=None): user = request.user course = Course.objects.get(id=course_id) learning_modules = course.get_learning_modules() context = {"course": course, "user": user, "msg": msg} course_status = CourseStatus.objects.filter( course=course, user=user ) context['course_percentage'] = course_status.first().percent_completed context['modules'] = [ (module, module.get_module_complete_percent(course, user)) for module in learning_modules ] if course_status: course_status … -
change django_migrations schema
Is there any way to change the schema for the django_migrations table? I want to move all Django related tables to another schema named django, I already used Database routers class DjangoAppRouter: route_app_labels = {'auth', 'contenttypes', 'admin'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'django' return None class PrimaryRouter: def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), }, 'django': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=django' }, 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), } } DATABASE_ROUTERS = ['bilikStudio.db-router.DjangoAppRouter', 'bilikStudio.db-router.PrimaryRouter'] but this is not working for django_migrations. any suggestions? -
Settting up templates directory error (Django)
Whenever I run python manage.py runserver I get: Below are the relevant parts of my Settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) --------- 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', ], }, }, ---- WSGI_APPLICATION = 'mysite.wsgi.application' I would appreciate it if someone could help as I am confused as to why such simple things are not working for me! -
Django Form. View form with models of logged user
I'm doing simple to do app in django. I wan't user to have possibility to add borads and task (task is specified for board). When user is adding task (form created with ModelForm ) there is posibility to choose from diferent boards but the form is showing all boards - for all users. I want it to show only boards of currently logged user. How can I do this? Would appreciate some help. models.py: class Board(models.Model): board_name = models.CharField(max_length=50) day = models.DateTimeField(default=timezone.now) board_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.board_name class Task(models.Model): task_name = models.CharField(max_length=100) done = models.BooleanField(default=False) not_done = models.BooleanField(default=False) task_board = models.ForeignKey(Board, on_delete=models.CASCADE) def __str__(self): return self.task_name forms.py: class TaskForm(forms.ModelForm): class Meta: model = Task user = User.objects.get(username='admin') fields = ['task_name', 'task_board'] views.py def add_task(request): if Board.objects.filter(board_user=request.user).exists(): form = TaskForm(request.POST) # problem nadal nierozwiązany if request.method == "POST": form.instance.task_board.user = request.user if form.is_valid: form.save() return redirect('tasks-view') else: return redirect('tasks-view') return render(request, 'todo/task_form.html', {'form': form}) -
Django - Use annotation in query - Related Field got invalid lookup
In my manager, I've overriden get_queryset to annotate sqft_annotated value. class RealestateManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( sqft_annotated=Coalesce('sqft_a', 'sqft_b', 'sqft_c') I use this value frequently but now, in this query, it raises error (probably because it isn't annotated): _a = Q(realestates__home_type__in=[constants.HOME_TYPES.HOME_TYPE__SINGLE_FAMILY, constants.HOME_TYPES.HOME_TYPE__FARM], realestates__sqft_annotated__gte=1100, ...) _b = Q(<QUERY>) _c = Q(<QUERY>) leads_query = Q(Q(_a | _b) | ~_c) Category.objects.annotate(lead_count=Count('realestates', filter=leads_query)).annotate( lead_perc=Case(When(lead_count=0, then=0), default=(Count( 'realestates', filter=leads_query) / float(total)) * 100)) ERROR Related Field got invalid lookup: sqft_annotated Can I somehow use the sqft_annotated in such query? PS: Tried to set base_manager_name in class Meta - didn't help. -
how to show djago validation error message in html template?
I set max_length limit for my every form filed. I want when any user exceed max length limit then contact-form will not be submitted and showing an error message. such as if any user forget to fill name filed then it will show name is required or if it exceed max length limit then it will show "maximum 300 character allowed". here is my code: #forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=300) email = forms.EmailField(max_length=300) subject = forms.CharField(max_length=1000) message = forms.CharField(max_length=3000) #models.py from django.db import models from django.utils import timezone # Create your models here. class Contact(models.Model): current_time = models.DateTimeField(blank=True, null=True,default=timezone.now) name =models.CharField(max_length=300) subject =models.CharField(max_length=1000, default="") email =models.EmailField(max_length=300) message = models.TextField(max_length=3000) views.py @csrf_exempt def home_view(request,*args,**kwargs): if request.method == "POST": contacts = ContactForm(request.POST) if contacts.is_valid(): name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] post = Contact(name=name,email=email,subject=subject,message=message) post.save() context= {'message_name':name} return render(request, 'index.html',context) else: print('not submittd') fm = ContactForm() context= {'form':fm} return render(request, 'index.html',context) here is html code of my contact from: <section class="contact section" id="contact"> <h2 class="section-title">Contact</h2> {% if message_name %} <div class="centerTest"> <h1> Thanks {{ message_name }} for your message. We will get back to you very soon</h1> </div> {% else %} <div … -
How do i raise a validation error on django parent form with child formsets?
I have a Django form with 6 formsets. I want to check if a condition exists and if it does then raise a validation error for the overall form. I know how to raise errors for each of those 6 formsets but I can't figure out how to do it for the master/parent form. The master/parent form contains no fields. Any pointers in the right direction would be much appreciated. -
Heroku: properly set up procfile to run scraper on a daily basis
I just deployed my first app Django app and have it set up on a Hobby dyno via Heroku. One main part of the app is that it runs a webscraper via a management command on a (semi)daily basis which scrapes roughly 160K records and puts them into a Heroku database. Once the data is scraped the app is pretty static, but I am still noticing some instances where it loads quite slowly. My question is, since I am quite new to Heroku or hosting any live app, what is the best way to set this job up to be sure I am using worker dynos to execute it? I tried to read Heroku docs on background jobs etc but it didn't really help me too much. I am honestly not even sure if my Procfile is set up properly to use worker dynos to run my scraper, or it's being run on the web one? The basic structure of my app is as follows; all of the code set up to run the scraper via a management command is held in the scraper app. Project - scraperapp - homepage - otherapps - settings - VENV - Procfile - requirements.txt … -
How to build filter class using django-filter that allows to query by multiple values of one model field
I have to build endpoint that must allow to filter by multiple values. It must looks like this: http://example.com/page?field=1&field=2&filed=3 and allow to execute such or similiar query + validate the list MyModel.objects.filter(field__in=[1,2,3]) django-filter(https://django-filter.readthedocs.io/en/stable/) library looks promising but in the documentation I have not found an easy way to do something so simple. How can I achieve this? -
Django Multiple Image Upload Using form
This can upload single image. But i want to upload multiple image like insta do. In instagram multiple images are stored in a slider. I don't understand files = request.FILES.getlist('image') how can i iterate this this list Views.py file @login_required def index(request): images = Image.objects.all() users = User.objects.filter(is_superuser=False) prof = Profile.objects.get(user=request.user) actions = Action.objects.exclude(user=request.user) following_ids = request.user.following.values_list('id', flat=True) if request.method == "POST": form = ImageCreateForm(request.POST, request.FILES) files = request.FILES.getlist('image') if form.is_valid(): description = form.cleaned_data["description"] image = form.cleaned_data["image"] new_item = form.save(commit=False) new_item.user = request.user new_item.save() create_action(request.user, 'Uploaded Image', new_item) messages.success(request, "Image Added Successfully") return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) if following_ids: # If user is following others, retrieve only their actions actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile').prefetch_related('target')[:10] return render(request, "account/index.html", { 'section': 'index', 'images': images, 'prof': prof, 'actions': actions, 'users': users, 'form': form, }) forms.py file from django import forms from urllib import request from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image class ImageCreateForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Image fields = ('description',) def clean_url(self): image = self.cleaned_data['image'] valid_extensions = ['jpg', 'jpeg'] extension = image.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The Given URL does not match valid image extensions.') return image … -
Django - adding another check to my login
I'm creating a single page application that uses Django's session authentication on the backend. Django is using django-allauth for everything authentication-related. I would like to add an additional step to my login where the user inputs a code and Django must verify that code too, other than password and username. How can i do that? Note that i'm using Django as an API, so i don't need to edit the form and add another field, i only need to add another check to the authentication backend, so something very easy: if the code is right, than proceed to check username and password too, else return an error. The problem is that i don't know where to add this check. I think i need to work on the authentication backend, but i'm stuck here. Here is an example of the login data that django receives: {'login': 'test', 'password': 'testPass12', 'testToken': '123abc'} So basically, other than checking login and password like it already does now, it should check if testToken is equal to a specific value. Here is the allauth authentication backend: class AuthenticationBackend(ModelBackend): def authenticate(self, request, **credentials): ret = None if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: ret = self._authenticate_by_email(**credentials) elif app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.USERNAME_EMAIL: … -
Django database data not showing in Templete
I have a class HardBook that inherits from Book: class Book(models.Model): title = models.CharField('Book Title', max_length=200) image = models.ImageField('Book Cover', upload_to='covers') description = models.CharField('Description', max_length= 350) class HardBook(Book): quantity = models.IntegerField('Quantity') I want to display the field data in a table, I want to show title, image and quantity. Everthing is displayed except quantity. {% for hardbook in hardbooks %} <tr> <td> <div class="cover-image" style="background-image:url({{hardbook.image.url}});"></div> </td> <td>{{hardbook.title}}</td> <td>{{hardbook.quantity}}</td> </tr> {% endfor %} -
dynamic form fields repeate the value of index[0]
'i have two table on different servers, both the table has same fields, i need to to compare the table in order to ensure that the data is synced and both the server has same data. in case of, mismatch will prepare a new table where i will endorsed the missing data. to clarify it further table1: emp_name , roll_no, (table on main server) table2: emp_name , roll_no. (table on standby server) i need output of the rcords that are in table1 but not in table2. and i will store the missing records in table3 like. missing_record_list: emp_name , roll_no. i will have almost 2 lakh records. i am writing this program in django. please reply with suitable solution. thanks -
Reverse for 'decrease-product-in-cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/decrease\\/(?P<product_id>[^/]+)\\/$']
please help i am geting this error when i added quantity it is really frustrating because it has been 2 days and i am trying to solve it here is my html: {% extends "base.html" %} {% load static %} {% block content %} <div class="container my-4"> <h2 class="text-center my-4">Your Cart</h2> <table class="table"> {% if cart.products.exists %} <thead> <tr> <th scope="col">Product</th> <th scope="col">Quantity</th> <th scope="col">Price</th> <th scope="col" class="text-center">Amount</th> <th scope="col"></th> </tr> </thead> {% endif %} <tbody> {% for product in carts %} <tr> <td>{{ product.products.title }}</td> <td> <a href="{% url 'cart:decrease-product-in-cart' item.item.id %}"><span class="badge badge-dark mr-2"><i class="fas fa-minus"></i></span></a> <span>{{ product.items.quantity }}</span> <a href="{% url 'cart:increase-product-in-cart' item.item.id %}"><span class="badge badge-dark ml-2"><i class="fas fa-plus"></i></span></a> </td> <td>{{ item.item.price|floatformat:2 }} $</td> <td class="text-center">{{ item.get_total|floatformat:2 }} $</td> <td class="text-right"> <a class="btn btn-danger" href=""><i class="far fa-trash-alt"></i></a> </td> </tr> {% empty %} <div class="alert alert-info" role="alert"> The cart is empty </div> {% endfor %} {% if order.promo_code_applied %} <tr> <td colspan="3"></td> <td class="text-center text-success"> Discount: <span class="font-weight-bold">-{{ order.promo_code_discount|floatformat:2 }} $</span> </td> </tr> {% endif %} <tr> <td colspan="3"> <a class="btn btn-warning" href="{% url 'products:list' %}">Back to Home Page</a> </td> {% if order.items.all %} <td class="text-center"> Total: <span class="font-weight-bold ml-1">{{ order.get_total_amount|floatformat:2 }} $</span> </td> <td> <a class="btn btn-info … -
Cannot fetch API data after deploying application to Heroku (works perfectly locally)
I cannot fetch the data from my Django Rest API publicly after deploying to Heroku. It works perfectly locally. When I click on the heroku webpage -> Inspect -> Console, says "Failed to load resource: net::ERR_CONNECTION_REFUSED" & "Uncaught (in promise) TypeError: Failed to fetch". The API is located publicly on heroku and it CORRECTLY has all my data (https://xxxxxxxxxx.herokuapp.com/api). I'm using Django backend and ReactJS frontend. Settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['xxxxxxxxxxxxx.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'backend', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'xxxxxxxxxxxxx.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'reactapp/build'), ], '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', ], }, }, ] WSGI_APPLICATION = 'xxxxxxxxxxxxx.wsgi.application' # Database … -
Select a valid choice. That choice is not one of the available choices - Django
When i want to add new Question and Choices to this question i have this: Select a valid choice. That choice is not one of the available choices. Thats my models: class Question(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice Thats my Forms class ChoiceForm(ModelForm): class Meta: model = Choice fields = ('question',) widgets = {'question': forms.TextInput} Thats my views: def addPolling(request): ChoiceFormSet = inlineformset_factory(Question, Choice, fields=('choice',), extra=3, can_delete = False) formset = ChoiceFormSet() form = ChoiceForm() if request.method == 'POST': question = request.POST.get('question') form.fields['question'].choices = [(question, question)] form = ChoiceForm(request.POST) formset = ChoiceFormSet(request.POST) print(request.POST) if form.is_valid() and formset.is_valid(): print(request.POST) -
Unable to import model form model of another app
This is code of transactions.model here i am trying to import WalletUser model form WalletUser.models import uuid as uuid from django.db import models from walletApp.WalletUser.models import WalletUser class Transaction(models.Model): STATUS_TYPES = ( ('C', 'Compleat'), ('S', 'Success'), ('I', 'Incompleat'), ('A', 'aborted'), ) uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, db_index=True) status = models.CharField(choices=STATUS_TYPES, default='N', max_length=3) created_on = models.DateTimeField(auto_now_add=True, null=False) user = models.ForeignKey(WalletUser) amount = models.FloatField() def __str__(self): return self.uuid I am getting this error /Users/shoaib/Documents/walletTransactionSystem/walletApp/walletApp/settings.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
HTML Script Function not returning List of Checked Items
I am using Django to receive Checked Items from HTML. Then, Django will run loop on array to delete all checked items from the list. Here is my code from HTML. It seems like HTML is not returning all checked ITEMS. SCRIPT <script> function MakeCheckList(){ checkedList = $('input:checkbox:checked[name="checkedbox"]').map(function() { return $(this).val(); }).get(); $('input#checklist').val(checkedList); } </script> HTML <div class="row"> <button class="taskDelete" name="taskDelete" formnovalidate="" type="submit" onclick=MakeCheckList();"><i class="fa fa-trash-o icon"></i>Delete</button> </div> <ul class="taskList"> {% for todo in todos %} <!-- django template lang - for loop --> <li class="taskItem"> <input type="checkbox" class="taskCheckbox" name="checkedbox" id="{{ todo.id }}" value="{{ todo.id }}"> </li>