Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django audio recording issue: receiving Bad Request error
I am really new to Django and also building an application. I am building an audio journaling application with Django. I am trying to make a recorder with Django, and I have receive a bad request error. The code: views.py @login_required def record_audio(request): print("11",request.method) print("1") if request.method == 'POST': print("2") if 'blob' not in request.POST: print(request.POST) print("3") return HttpResponseBadRequest('Missing audio-blob parameter') print("4") now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") print("5") filename = f"{request.user.username}_{now}.wav" print("6") file_path = os.path.join(settings.MEDIA_ROOT, filename) # Save the audio file to the server print("7") with open(file_path, 'wb') as f: f.write(request.POST['blob'].encode()) return HttpResponse(status=204) # Return a 204 No Content response else: print("8") return render(request, 'recording/record.html') record.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>Recorder</h1> <section class="experiment" > <br> <h3> Send Message: Speech to text </h3> <button id="start-recording">Start</button> <button id="pause-recording" disabled>Pause</button> <button id="resume-recording" disabled>Resume</button> <button id="stop-recording" disabled>Stop</button> </section> <section class="experiment"> <div id="audios-container"></div> </section> {% include "chat_script.html" %} <script src="https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js"></script> <script src="{% static 'js/jquery-1.12.3.js' %}"></script> <!-- <script src="{% static 'js/bootstrap.min.js' %}"></script> --> <!-- <script src="{% static 'js/script.js' %}"></script> --> <!-- <div> <audio id="audio-player" controls></audio> </div> --> {% endblock %} urls.py path('record-audio/',views.record_audio,name="record_audio"), chat_script.html <script> function captureUserMedia(mediaConstraints, successCallback, errorCallback) { navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback); } var mediaConstraints = { audio: true }; document.querySelector('#start-recording').onclick = … -
Django sessions not saving data from form, no error or apparent reason
I have a view with different 'stages' (as I wanted to keep the same URL without resorting to something like AJAX), which takes data from a form, does some processing, and then would save that data to the database. Because I can't forward some data via POST, I wanted to save that data in a session. For some reason, this is not working - at all. I can see the data being extracted from the form, and I can forward that via POST, but attempting to save or retrieve it to a session either results in blank data, or a KeyError. This is the view I am using (very trimmed down, but the error is reproducible) def processpayment(request, *args, **kwargs): if request.method == 'POST': form = paymentDetailsForm(request.POST) amount = request.POST.get('amount', False); stage = request.POST.get('stage', False); if (stage == "checkout"): return render(request, "payment.html", {'form': form, 'amount': amount, 'stage': stage}) if (stage == "complete"): return render(request, "payment.html", {'amount': request.session['amount'], 'stage': stage, 'name': request.session['name']}) if (amount == "custom"): if form.is_valid(): amount = form_data.get('amount') name = form_data.get('name') request.session['amount'] = amount request.session['name'] = name request.session.modified = True return render(request, "payment.html", {'form': form, 'stage': stage, 'amount': amount}) return render(request, "payment.html", {'amount': amount, 'stage': stage}) else: return … -
Django - How to make a relationship in Django that is related to a multiple ManyToManyField model
I am a django beginner. I have two models here that are used in another model as a ManyToManyField : In models.py : class Likelihoods(models.Model): Likelihood = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Consequences(models.Model): Consequence = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Inherent_risks(models.Model): Likelihood = models.ManyToManyField(Likelihoods, related_name= 'InherentRisk_Likelihood') Consequence = models.ManyToManyField(Consequences, related_name= 'InherentRisk_Consequence') After this, i added it to another model in order to create a form name Hira. class Hira(models.Model): Activity = models.CharField(max_length=255) Risk_Description = models.TextField(default="***") PBS = models.ManyToManyField(PBS) Physical_control = models.CharField(max_length=255) Administrative_control = models.CharField(max_length=255) Instrumented_control = models.CharField(max_length=255) Inherent_Risk = models.ForeignKey(Inherent_risks, on_delete=models.CASCADE, related_name='Inherent_risk' ) The form.py : class HiraForm(ModelForm): class Meta: model = Hira fields = '__all__' The question : The form i am getting I can't choose both a likelihood and a consequence (not even any data). What am I doing wrong ? -
How to use django oram to implement oracle wm_concat query
In oracle, I can use wm_concat to implement row-to-column conversion, as follows: SELECT * FROM STU_TEST name project Alice Machine Learning Alice Data Science Bob Web Development Bob Mobile Development Carol Data Science Carol Cloud Computing David Artificial Intelligence SELECT NAME,wm_concat(PROJECT) FROM STU_TEST GROUP BY NAME name wm_concat(PROJECT) Alice Machine Learning,Data Science Bob Web Development,Mobile Development Carol Data Science,Cloud Computing David Artificial Intelligence I want to implement this query using django orm, I tried the following, without success. 它返回了错误:cx_Oracle.DatabaseError: ORA-00937: not a single-group group function from django.db.models import CharField, Value from django.db.models.functions import Concat from django.db.models.aggregates import Count from myapp.models import StuTest from django.db.models import Func class GroupConcat(Func): function = 'LISTAGG' template = '%(function)s(%(expressions)s, \',\') WITHIN GROUP (ORDER BY %(expressions)s)' results = StuTest.objects.values('name').annotate(project_concat=GroupConcat('project')).order_by('name') for result in results: print(result['name'], result['project_concat']) How to implement this query? (In the actual environment, group by may not only include the name field, but also other fields) -
HTML element src attributes sends concatenated string to server
I have a ReactJs and Django project setup. I send a GET request to my localhost for localhost/index, the server running my Django project returns index.html which is correct. The index.html has a html element with src value "asset/script.js". It sends a request to Locahost/index/asset/script.js instead of Localhost/asset/script.js. Sometimes it sends the first path, sometimes the last path. why? Debugging, not sure whyt it doesnt work -
How to do pagination in Django? I have TypeError
I want to do pagination on my site. I do API-call to supplier's website. I get data, deserialize and save it in my model, then get those objects for view them. Also I get all unique names for query into model and error in that function. When I press "Next page" everything breaks. Before pagination everything works. view.py def search(request): url_for_search = 'http://ws.armtek.ru/api/ws_search/search?format=json' template = 'profiles/search.html' if request.method == 'GET': # API-call searched = request.GET.get('searched') headers = { 'Authorization' : basic_auth(login, password)} params = {some_params} res = requests.post(url_for_search,headers=headers,data=params) if 200 <= res.status_code < 300 : # Deserialize serializer = ProfileSerializer(data=res.json()['RESP'],many = True) serializer.is_valid() serializer.save() # Getting data names = get_unique_names(res.json()) number_products = len(res.json()['RESP']) products = Profile.objects.filter(NAME__in = names).distinct()[:number_products] # Pagination p = Paginator(Profile.objects.filter(NAME__in = names).distinct()[:number_products],10) page = request.GET.get('page') page_obj = p.get_page(page) return render(request, template, {"products":products, "page_obj":page_obj, 'searched':searched}) else: return HttpResponse('Error') get_unique_names() def get_unique_names(res_json): names = set([ item['NAME'] for item in res_json['RESP']]) return names ERROR in that line: names = set([ item['NAME'] for item in res_json['RESP']]) I dont want to do. Maybe I should do it with ListViev? but i don't sure, that it's gonna help -
unable to retrieve the refresh data from django view to html
I have issue fetching the data to html with Ajax , however I am getting correct output in my django view. Scenario: I have two filter on webpage 1st is to select the Project and 2nd is date range. 1st Scenario: whenever I am selecting the project I am able to get proper output to webpage but whenever I am trying to select the dates with project , I am able to get the output in my django view but not able to fetch the same to HTML. below is the script I am trying for ajax. <script> document .getElementById("inputproject") .addEventListener("change", function () { document.getElementById("project-form").submit(); }); //Date range as a button $("#daterange-btn").daterangepicker( { ranges: { {% comment %} Today: [moment(), moment()], {% endcomment %} Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment().endOf("month")], "Last Month": [ moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month"), ], }, startDate: moment().subtract(29, "days"), endDate: moment(), }, function (start, end) { // Update the selected date range in the span element $("#selected-range").html( start.format("YYYY-MM-DD") + " - " + end.format("YYYY-MM-DD") ); // Get the selected project from the form const project = $("#inputproject").val(); // Create an object with … -
Djang-select2 breaking adaptive page
Im using django-select2 and i have 2 loading js files "select2.full.min.js" and "django_select2.js" and if they`re both enabled it breaks my adaptive page and i got this: If i turn off one of them in chrome developer tools pages works fine but i cant understand what`s the problem Im loading this with form.media.js template.html {% block content %} {{ form.media.css }} <div class="container mt-3"> <form action="{% url 'create_worklog' %}" method="post"> {% csrf_token %} <p class="mb-3">{{ form.worklog_date.label }}:</p> <div class="input-group " id="id_worklog_date" data-td-target-input="nearest" data-td-target-toggle="nearest"> {% render_field form.worklog_date|add_class:"form-control" type='text' data-td-target="#id_worklog_date" %} <span class="input-group-text" data-td-target="#id_worklog_date" data-td-toggle="datetimepicker"> <i class="fas fa-calendar"></i> </span> </div> <div class="mt-3 mb-3"> <p class="mb-3">Контрагент:</p> {% render_field form.contractor_counter|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Объект:</p> {% render_field form.contractor_object|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Разделы:</p> {% render_field form.contractor_section|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Описание:</p> {% render_field form.description|add_class:"form-control" %} </div> <div class="form-footer text-center"> <button type="submit" class="btn btn-primary w-50">Создать</button> </div> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> {{ form.media.js }} {% endblock %} -
Django inline formset missing_management_form error when deleting item
I am using an inline formset in a Django project and I keep getting a "missing_management_form" error when I submit the form. This happens only when I trying to delete item and hit Save button, it works well if I add new items. Exact error message: {'missing_management_form': 'ManagementForm data is missing or has been tampered with. Missing fields: %(field_names)s. You may need to file a bug report if the issue persists.'} Here is my code: # views.py from django.views.generic.edit import CreateView, UpdateView from django.db import transaction from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.shortcuts import get_object_or_404 from .forms import OrderForm, OrderItemFormset from .models import Order, OrderItem class OrderCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Order form_class = OrderForm template_name = 'add_order.html' success_message = "Order created successfully!" def form_valid(self, form): context = self.get_context_data() order_item_formset = context['order_item_formset'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if order_item_formset.is_valid(): order_item_formset.instance = self.object order_item_formset.save() return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: order_item_formset = OrderItemFormset(self.request.POST, instance=self.object) else: order_item_formset = OrderItemFormset(instance=self.object) data['order_item_formset'] = order_item_formset return data def get_success_url(self): return reverse('edit_order', kwargs={'pk': self.object.pk}) class OrderUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Order form_class = OrderForm template_name = 'edit_order.html' success_message = "Order updated … -
is virtual environment only for development or even for running application
I am using ubuntu 22.04 with python 3.10.6 version. My Django application currently works on python 3.7 version and it gives issues in 3.10 version. I want to use virtual environment with python 3.7 version to make application run. If i run the application with Gunicorn for production, will it run 3.7 version of virtual environment of machine version of 3.10? My project uses Gunicorn, nginx and django. -
I am facing this issue in django framework
-while I am making a project in django django -admin startproject hello -I am facing this issue in django , while using this command server is not working -python manage.py runserver -server show this error: -python: can't open file 'manage.py': [Errno 2] No such file or directory -
How to get the date of last change from multiple Django models?
The environment is Django 4 and Python 3.10+. In the application there are multiple data models, each with 'created' and 'modified' DateTimeFields. I need to get the timestamp of last data modification - either creation of new object or modification of a existing one, for cache invalidation. Currently the code checks for the newest creation timestamp and is like this: from django.db.models import Max qs_1 = Model_1.objects.all() qs_2 = Model_2.objects.filter(active=True).order_by('created') qs_3 = Model_3.objects.filter(active=True).order_by('created') last = max(list((itertools.chain(list(queryset.aggregate(Max('created')).values()) for queryset in (qs_1, qs_2, qs_3) if queryset.count()))))[0] My questions are as follows: The expression to get the last creation date is quite convoluted. Is there a way to compute the latest timestamp over multiple models using the ORM alone? It can be done in pure SQL, so it should be possible in the ORM. How do I extend it to also compare the modified fields of the models? -
How can I access and insert values into a database in django?
This is my code: import sqlite3 def add(email, password): conn = sqlite3.connect('database.sqlite3') conn.execute(f"""insert into Users('email', 'password') Values('{email}', '{password}')""") conn.commit() conn.close() @csrf_exempt def save_enq(request): if request.method == 'POST': email = request.POST.get('email') passw = request.POST.get('password') add(email, passw) print("Done!") return render(request, 'index.html') # there is more code but it is irrelevant This is my DB: And this is my error: please help me, I am new to programming. Thank you. :) -
Is there any way to change python version in virtual environment on Windows PC?
The Python version of my windows pc is 3.10.9 but Client's live project python version is 3.8.0. I installed python 3.8.0 for the project but all the other project that I made with python3.10.9 got error. To use many version of python at windows pc is complicated you know. So I want to know is there any option to change my python in virtual environment for the project if I will install again python3.10.9? -
Django Forms two models with foreign key
I am trying to implement the booking function in my Django project. I have two models, one for the customer (Fordonsregister) and one for the service (FordonsService), a one to many relationship as one customer (ID is vehicle registration number: "regnr" which is the primary key in the customer model and the foreign key in the service model (code below). When a customer wants to book they click on a certain service (generated from the service types model (ServiceTypes, below) and get redirected by the urls.py to that specific service url. I would then like the customer to fill out only certain fields. The customer should only fill out the primary key, the foreign key in the form should be auto filled. the "typ" in the service model should be autto filled as the URL is different for the chosen service type. The models: from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] verbose_name = 'Kunder' verbose_name_plural = … -
I can't load a .joblib file to my views.py on my django project
My .joblib file is in the same directory as views.py literally next to each other but views.py cannot load it and once I runserver FileNotFoundError is thrown. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import joblib @csrf_exempt def test(response): if response.method == 'POST': age = int(response.POST['age']) gender_str = str(response.POST['gender']) if gender_str == 'Male': gender_value = 1 else: gender_value = 0 openness = int(response.POST['openness']) neuroticism = int(response.POST['neuroticism']) conscientiousness = int(response.POST['conscientiousness']) agreeableness = int(response.POST['agreeableness']) extraversion = int(response.POST['extraversion']) personality_values_1 = [[gender_value, age, openness, neuroticism, conscientiousness, agreeableness, extraversion]] theModel = joblib.load('PersonalityTestLogisticRegression.joblib') prediction = theModel.predict(personality_values_1) prediction_value = prediction[0] return render(response, "main/Review_Test.html", {'prediction':prediction_value}) I tried everything I can and I'm new to django. Pulling my hair rn. -
Cannot assign member "image_url" for type "Article" "Literal['http://default']" is incompatible with "property"
impot_data: from blog.models import Article def run(): for i in range(5,15): article= Article() article.title="Article num° #%d" % i article.desc="description article num° #%d" % i article.image_url ="http://default" print("opération réussie ") -
django.db.utils.OperationalError: no such column: users_classroom.class_code When attempting to Migrate
This is my first Django project, and I am attempting to add the attribute class_code to Classroom, and class_code is a random 6 character string that I plan to use to allow users to join a classroom using it. I attempted to make it random using the code from the following post:https://stackoverflow.com/a/67546412/20015529 and followed this django document:https://docs.djangoproject.com/en/4.1/howto/writing-migrations/#migrations-that-add-unique-fields. I modified the instructions to use the random string as opposed to a uuid due to the length of uuid's. When attempting to migrate, I recieve the following error: "django.db.utils.OperationalError: no such column: users_classroom.class_code". Here are my Django Files. my project name is Project and the app name is users. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile, Classroom from home.models import Announcements class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data['email'] # if User.objects.filter(email=email).exists(): # raise forms.ValidationError('That email is in use. Please Log in or use a different Email') return email class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class ClassJoinForm(forms.ModelForm): class Meta: model = … -
changing the src of an image using javascript for a django website
I'm creating a website using django. At the front end I want to change slides every x seconds. My approach was to change the src of the image every x seconds using javascript Here's how I went about it: //Javascript function newSlide() { var imageTemplate = document.querySelector(".slide-img"); setInterval({ imageTemplate.setAttribute("src", "{% static 'images/newSlideImage.png' %}") }, x); } <!-- html --> <img class="slide-img" src="image.png"> I thought this would change the image for me but it didn't work at all. When I checked my console, it said I couldn't load the file and returned 404 error. error: "failed to load resource: the server responded with a status of 404 (Not Found)" However the initial image loaded perfectly despite using the same syntax {% %} -
failure to deploy by django webapp on heroku
Good day, I'm trying to deploy by django webapp on heroku but i'm facing the following problem. The conflict is caused by: The user requested botocore==1.23.50 awsebcli 3.20.3 depends on botocore<1.24.0 and >1.23.41 boto3 1.26.59 depends on botocore<1.30.0 and >=1.29.59 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts ! Push rejected, failed to compile Python app. ! Push failed And my requirement.txt is the following... asgiref==3.6.0 awsebcli==3.20.3 boto3==1.26.59 botocore==1.23.50 cement==2.8.2 certifi==2022.12.7 charset-normalizer==2.0.12 colorama==0.4.3 contourpy==1.0.7 cycler==0.11.0 distlib==0.3.6 dj-database-url==1.2.0 Django==4.1.4 django-crispy-forms==2.0 django-heroku==0.3.1 django-storages==1.13.2 filelock==3.9.0 fonttools==4.38.0 future==0.16.0 gunicorn==20.1.0 idna==3.4 jmespath==0.10.0 kiwisolver==1.4.4 matplotlib==3.6.3 numpy==1.24.1 packaging==23.0 pathspec==0.9.0 Pillow==9.4.0 platformdirs==2.6.2 psycopg2==2.9.5 psycopg2-binary==2.9.5 pyparsing==3.0.9 python-dateutil==2.8.2 PyYAML==5.4.1 requests==2.26.0 s3transfer==0.6.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.3 termcolor==1.1.0 tzdata==2022.7 urllib3==1.26.14 virtualenv==20.17.1 wcwidth==0.1.9 whitenoise==6.4.0 What am i missing? -
Current path does not match path patterns error
I'm pretty new to Django and I've been following this page step-by-step: https://docs.djangoproject.com/en/4.1/intro/tutorial01/. However, when I try to call the polls app using localhost:8000/polls, a page not found error shows up. I don't have too much of an idea how to fix this, since I'm pretty new. I remember seeing how VS was complaining about the module admin not working but I resolved it by just reinstating the python interpreter. I also tried to re=run the server and reloading VS but it didn't really help. All of my modules match the one in the tutorial. -
Using custom queries with Django annotate
In annotate. When counting records, how can I use a custom query to narrow down what to count? class User(models.Model): name = models.CharField(max_length=50) class Tweet(models.Model): user = models.ForeignKey("User", related_name="tweet") favorite = models.IntegerField(default=0) is_active = models.BooleanField(default=False) objects = TweetQuerySet.as_manager() class TweetQuerySet(models.QuerySet): def buzzed(self): return self.filter( is_active=True, favorite__gte=100 ) # I want to count only the tweets returned using the buzzed query. users = User.objects.annotate(tweet_count=Count("tweet")) Thanks in advance. -
message.success not showing
I'm trying to set up success messages for whens u user successfully logs in. But it is not working for me. I Have tried both in and out of block, both don't work. View: def UserLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,("You were successfully logged in...")) return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) Main.html: {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show alert-main" role="alert"> <p style="color: darkgreen;">{{ message }}<p> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% block content %} {% endblock %} -
Cant loging in django app service using auth
I develope a website using django, nginx and docker in an azure container registry and app service. when i run the image using docker desktop it runs properly, but when i try to login in appservice in only redirect me to login page. I want to use the default database of django proyect. I am using a simple auth as follow from django.contrib.auth.decorators import login_required @login_required def home(request): username = request.user.username context = {'username': username} return render(request, 'Home/home.html', context) I added in my settings the follow AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = 'auth.User' ROOT_URLCONF = 'sitioindicadores.urls' and also CSRF_TRUSTED_ORIGINS = ['https://*.abc.net/','https://*.127.0.0.1'] SESSION_COOKIE_DOMAIN='https://abc.azurewebsites.net/' my nginx and docker are: server web:8000; } server { listen 80; location / { proxy_set_header Host $host; proxy_pass http://app_server; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { autoindex on; alias /app/static/; } } and FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY sitioindicadores . RUN pip install -r requirements.txt COPY nginx.conf /etc/nginx/sites-available/default RUN python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate EXPOSE 80 CMD ["gunicorn", "--bind", "0.0.0.0:80", "sitioindicadores.wsgi:application"] i dont know why it runs ok in docker but not in the web. I'd appreciate … -
Form filtering in Django?
error: 'RegisterlesonForm' object has no attribute 'id' form class RegisterlesonForm(forms.ModelForm): class Meta: model = Registerleson fields = ['leson', 'book', 'discount'] widgets = { 'leson': forms.Select(attrs={'class': 'form-control'}), 'discount': forms.NumberInput(attrs={'class': 'form-control'}), 'book': forms.Select(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super(RegisterlesonForm, self).__init__(*args, **kwargs) self.fields['leson'].queryset = Registerleson.objects.raw( "SELECT * FROM classes_classes WHERE classes_classes.id not IN (SELECT leson_id FROM member_registerleson WHERE student_id = %s )", {self.id})