Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django formset template loop through fields disables delete featuer
Thank you for being here. I am not able to delete objects in django formset While i am looping through the fields in templates the. I can see the deletion box but when i hit submit the page refreshes and the object is exist. template.html {% for form in request_equipment_form %} <div class="card" style="width: 100% "> <div class="card-body"> <div class="d-flex flex-row" style="width:100%"> {{form.equipment}} {{form.quantity}} {{form.DELETE}} {{form.ORDER}} </div> </div> {% endfor %} But when i do not loop through the fields the delete feature works like charm {% for form in request_equipment_form %} <div class="card" style="width: 100% "> <div class="card-body"> <div class="d-flex flex-row" style="width:100%"> {{form.as_p}} </div> </div> {% endfor %} views.py if formset.is_valid(): instances = formset.save(commit=False) for d_obj in formset.deleted_objects: d_obj.delete() if not instances: return redirect(request.META.get('HTTP_REFERER')) for instance in instances: instance.user = request.user instance.flight = flight instance.station = flight.station instances = formset.save(commit=False) for instance in instances: instance.save() print(instance.date) return redirect(request.META.get('HTTP_REFERER')) -
Integrate BigBlueButton in Django
i installed BigBlueButton in my Django project and i create a meeting using the admin page. That's the meeting model showed in admin page. Meeting Name Meeting ID Created at Is running Actions Metting 2 Aug. 27, 2021, 4:17 p.m. False Create join link Start Now Metting 1 Aug. 27, 2021, 4:06 p.m. False Create join link Start Now But whenever i try to start a meeting an exception raise: RuntimeError at /admin/django_bigbluebutton/meeting/2/join/ No active exception to reraise Request Method: GET Request URL: http://127.0.0.1:8000/admin/django_bigbluebutton/meeting/2/join/ Django Version: 3.2.4 Exception Type: RuntimeError Exception Value: No active exception to reraise Exception Location: C:\Users\Galaxynet\AppData\Local\Programs\Python\Python39\lib\site-packages\django_bigbluebutton\bbb.py, line 221, in start this is the code of start function: def start(self, name, meeting_id, **kwargs): """ Start meeting with provided info. Most of BigBlueButton info is provided now. TODO: will add more configs for bigbluebutton later! """ call = 'create' attendee_password = kwargs.get("attendee_password", self.attendee_password) moderator_password = kwargs.get("moderator_password", self.moderator_password) # Get extra configs or set default values welcome = kwargs.get('welcome_text', _('Welcome!')) record = kwargs.get('record', BBB_RECORD) auto_start_recording = kwargs.get('auto_start_recording', BBB_AUTO_RECORDING) allow_start_stop_recording = kwargs.get('allow_start_stop_recording', BBB_ALLOW_START_STOP_RECORDING) logout_url = kwargs.get('logout_url', BBB_LOGOUT_URL) webcam_only_for_moderators = kwargs.get('webcam_only_for_moderators', BBB_WEBCAM_ONLY_FOR_MODS) voice_bridge = 70000 + random.randint(0, 9999) # Making the query string query = urllib.parse.urlencode(( ('name', name), ('meetingID', meeting_id), ('attendeePW', … -
where do these "not-found" wagtail errors come from?
This is a chunk of my HTTP logs from django v3.2 running wagtail. Looks as though django is trying to tell me where the missing media is but not able to. Because this is a thicket page with gallery sub-images of "featured pages" the view source in my browser doesn't reveal the image file attempt, but I am assuming it is the same issue as OP's with misconfigured MEDIA_ROOT. Strangely, not seeing any errors in the page's linked images when I bring the child page up in wagtail admin. Anyone have an idea why the missing image won't bubble up to the HTTP logs, or what causes the "media/not-found" substitution for the "real" item causing the 404, or how to unravel the error stack? I've found multiple instances of "not-found", but only in the wagtail "site-packages" /lib/python3.8/site-packages/wagtail folder. None of them give me an indication of why the page (or usually image) causing the 404 isn't returned in the HTTP logs but just the "not-found" URL. I could see what the missing image was (part of a block), and it actually wasn't missing, but possibly a cached copy of the page was causing the "not-found" error to be substituted. [25/Aug/2021 … -
How do I switch a dictsort in Django with a click of a button?
I'm trying to make a button that whenever someone clicks on it it'll change my dictsort to sort by a different attribute instead. Here's my code. I don't have any errors but the button isn't doing anything. I want the dictsort to switch to sorting by date if someone clicks on the button instead of sorting by authors which is the default. Thanks in advance. <button type="submit" onClick="{change text.for-loop|dictsort:'date'}"></button> <ol class="text"> {% for paragraph in paragraphs|dictsort:"authors" %} <div>{{paragraph.text}}</div> {% endfor %} </ol> -
How to add google 2factor authenticator in Django login?
is it possible to add google 2factor authenticator in Django login? if yes then how to add it? does any django package have for add google 2factor authenticator in django login? Many website using google 2factor authenticator in their login process. User need to install Google 2factor authenticator app in their phone and new code is generating after every few seconds. I am not interested to add otp login which send code to user phone via sms. I am looking somethings like google 2factor authenticator which generating code after every few seconds. -
Como evitar el resubmit de formulario al refrescar la pagina en django
buenas estoy haciendo una pequeña app de notas al guardar el formulario el views.py me devuelve a la misma pagina hasta hay todo bien, pero cuando actualizo la pagina me aparece un mensaje diciendo que el formulario sera enviado nueva mente def guardar(request): notas = noteblock.objects.all() note = formularionotes(request.POST) if note.is_valid(): note.save() return render(request,'notes.html',{'notas':notas}) alquien porfavor me explica como hago que esto no pase -
I have extended the default User table named UserProfile and want to access info from Product model but shown integrity error
UserProfile table: (Extended table of default User) from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE`enter code here` class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) k_name = models.CharField(max_length=100, default="krishok Name", null=True) k_address = models.CharField(max_length=300, default="Goes Krishok Address Here", null=True, blank=True) k_national_id_no = models.CharField(default="1", max_length=50) k_phone = models.CharField(default="01778956098", max_length=20) k_email = models.EmailField(default="xxx@gmail.com", max_length=254) k_image = models.ImageField(default = '', upload_to = 'upload/pkrishokImage/') national_id = models.ImageField(default= '',upload_to = 'upload/IDImage/') Product model code: from Store.models.userprofile import UserProfile from django.db import models from .categories import Category from .unit_type import Unit_Type class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) unit= models.ForeignKey(Unit_Type, on_delete=models.CASCADE, default=1) Unit_price = models.IntegerField(default=0) #k_name = models.ForeignKey(UserProfile, on_delete=models.CASCADE)#this is the problem quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to = 'upload/productsImg/') @staticmethod def get_all_products(): return Product.objects.all() #Filtering by Category Id: # this method will bring all products by its categoryID @staticmethod def get_all_products_by_id(category_id): if category_id: return Product.objects.filter(category = category_id) else: return Product.get_all_products() #i am trying to get id from extended user table called UserProfile model and want to get access of #all data from Product model, so that i am trying to written my foreignKey at product table from UserProfile table but it's give me integrity … -
Align django crispy form with html headings
I have made a dynamic django crispy form in which users can add additional rows I only want headings on the first row i.e.: not: I have been able to remove the headings using a form helper and was then just going to add the headings separately in html but these do not align correctly: Does anyone have an idea as to either get it so only the first row has labels things align correctly? forms.py class MedFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( Div( Div('med_name', css_class='col-3',), Div('dose', css_class='col-3',), Div('form', css_class='col-3',), Div('adherence', css_class='col-3',), css_class='row', ), Field('query', placeholder=kwargs.pop('query_placeholder', 'random text')), ) self.form_show_labels = False self.render_required_fields = True html <table id="currentmeds_table" border="0" cellpadding="0" cellspacing="5"> <thead> <tr> <div class="row" class="form-group"> <div class="col-3"> Medication </div> <div class="col-3"> Dose (mg) </div> <div class="col-3"> Formulation </div> <div class="col-3"> Adherence </div> </div> </tr> </thead> <tbody> <td> {% for form in currentmed_formset %} {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE }}{% endif %} {% crispy form med_formsethelper %} {% endfor %} </td> </tbody> </table> {{currentmed_formset.management_form}} -
How to Uninstall the Django-admin from Windows
By mistake, I installed Django-admin to my Windows instead of Virtualenv. Can anyone help me uninstalling this Django_admin from Windows?This is the version of Django-admin installed -
Django, HTML templates isn't rendering with debug True
My HTML templates are not rendering with I have my debug turned off/Debug False It throws a "Server Error 500" But if I try rendering a HttpResponse it works. My whole project works completely fine when I have my debug on True Please reply if you can help me. settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['{{ProjectName}}.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', # Custom Apps 'authSystem', 'posts', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'src.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', ], }, }, ] WSGI_APPLICATION = 'src.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') … -
Linux python django site-packages not recognized in envelope
I have tried to create envelope on my linux pop os system using miniconda. When I activate it, I can install packages using pip, but when I run my django instance it doesn't find the modules. If I type which python is shows the miniconda path correctly. I can look in the site-packages folder and see the packages installed. I've tried installing django-anymail and corsheaders and they are both not being found. It does find my locally installed apps. If I use the command line and open python and then import, it does not recognize my modules installed in the virtual envelope either. I thought it was a problem with conda, so I also created an envelope using python's native method: python3 -m venv I have the same problem with it finding pip install site-packages. Is there a command I can run to show all available packages? -
Model-wide validation for a Field type in Django ie., validate that all DecimalField of a model is greater than 0
I have three Decimal fields that all have the same validator: ` class MyModel(models.Model): one = models.DecimalField(validators=[great_than_zero]) two = models.DecimalField(validators=[great_than_zero] three = models.DecimalField(validators=[great_than_zero] ` Is there a pythonic way to enforce this validator for the entire model, so that no Decimal Field can have a negative number. If I know that all of my Decimal fields will be positive, it would be nice to not right the same piece of code for each one. -
cursor.fetchone() returns None when it shouldn't
So basically, I wanted to use an sqlite3 database to store data in my django project. Unfortunately, this view returns None for some reason. Code: def req_count(request): db = sqlite3.connect(db_path) cursor = db.cursor() cursor.execute("SELECT * FROM reqcount_data") db.commit() reqs = cursor.fetchone() db.commit() return HttpResponse(reqs) Also please tell me where a db.commit() is redundant. NOTES: I am using Windows 10 I am using Python 3.8 I am using Django 3.2.6 -
What did my teacher mean by 'db.sqlite3' will fall short in bigger real word problems?
I am very new to programming and this site too... An online course that I follow told me that it is not possible to manage bigger databases with db.sqlite3, what does it mean anyway? -
How to post a file to Django/DRF using python requests
I have the following code to post a json dataset/file to a Django/DRF API db. I get the error message '{"ohlc":["No file was submitted."]}' what am I doing wrong ? test_url = "http://localhost:8000/stocks/aapl/price/" test_file = { "aapl": open("./ohlc_aapl.json", "rb") } payload = x.to_dict(orient='records') r = requests.post(test_url, files=test_file, json=payload) -
database error after Heroku deployment for django app
I made a simple API using the Django REST framework and consumed the API with ajax. This is my first time using Heroku, after I deployed the project it tries to save the data to a relation called "api_task" which causes an error. I have debug on True and this error shows when I try to add a new task to my todo app: relation "api_task" does not exist LINE 1: INSERT INTO "api_task" ("title", "completed") VALUES ('new t... this is my model class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title ajax call for creating and updating new tasks let method = 'POST'; let url = 'http://127.0.0.1:8000/api/task-create/'; if (activeItem){ method = 'PUT'; url = `http://127.0.0.1:8000/api/task-update/${activeItem.id}/`; activeItem = null; } const title = document.getElementById("title").value fetch(url, { method:method, headers:{ 'Content-Type': 'application/json', 'x-CSRFToken': csrfToken }, body:JSON.stringify({'title':title}) }) .then(response =>{ buildList() document.getElementById('form').reset() }) -
Django - add required auto-generated `uuid4` to existing project
I'm trying to add internal_code to a Django Model in the existing project. internal_code = models.CharField(max_length=128, default=uuid.uuid4, unique=True) The problem is that when running migrate, Django raises IntegrityError: DETAIL: Key (internal_code)=(b24f1ca6-bd90-4c91-87b0-5f246a4057e1) is duplicated. I understand that this problem exists only during migrate as it is generated just once. Is there a way to avoid this behavior without having to do this?: set field to null=True migrate add RunPython that will populate all the existing objects internal_code fields set field to null=False -
¿Por que al crear un projecto nuevo de django en visual studio 2019, se crea con la vesion 2.1.2 y no la mas actual?
Tengo instalado django 3.2.6, pero al crear el proyecto desde la opcion que da visual estudio, se crea con la version 2.1.2 Django settings for DjangoWebProject4 project. Based on 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ -
Django condition in save method
I got storage places wich have the field amount and article. If i call save() on one place i want to set the article field to None. Whats is the best approach for this ? I already tried this: def save(self, *args, **kwargs): if self.amount == 0: self.article = None super(LagerPlace, self).save(*args, **kwargs) -
Page Not Found 404 Django & Python
I am having the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in Decoder.urls, Django tried these URL patterns, in this order: form.html [name='form1'] hl7 [name='hl7'] The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Its my first time writing code using Django `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('hl7rest.urls')), ]` and this other file from . import views from django.urls import path urlpatterns = [ path('form.html', views.render_form_View, name='form1'), path('hl7', views.hl7_web_view ,name='hl7'), ] -
Render template tags when passing as variable in django
I want to pass some html as a string in a variable to a template, which also includes a link: <a href= {%url: 'app:page'%}> If I pass the variable though, the template tags are not invoked. If I use {{variable | safe}} to escape the restrictions, still it is not being called. I think I have a major error in my thinking, or is it just not possible to do this? -
On click, the button checks checkbox in another html
I tried to follow this example; Set to true state a checkbox in a different page(javascript) but can't get it to work, not sure how to fix it? Getting error message; Request Method: GET Request URL: http://localhost:8000/profileusers/register.html?chk=1" First Page - terms.html <div class="row"> <a href="{% url 'register' %}" target="_blank"> <input type="button" name="acceptButton" class="btn accept-button" value="Accept" id="acceptButton" onclick="registerCheck(this.id)"> </a> <a href="{% url 'register' %}"> <input type="button" name="declineButton" id="declineButton" class="btn decline-button" value="Decline"> </a> </div> <script> function registerCheck(clicked_id) { if (clicked_id === 'acceptButton') { window.location.href = "register.html?chk=1"; } } </script> Second Page - register.html <div class="form-check"> <input class="form-check-input" type="checkbox" id="terms-box" name="terms-box"> <label class="form-check-label" for="flexCheckDefault"> &nbsp; <a href="{% url 'terms' %}" class="link-terms">Terms & Conditions</a> </label> </div> <script> var url = window.location.href.split("?"); if (url[1].toLowerCase().includes("chk=1")) { $('#terms-box').attr('checked', true); } </script> -
Ajax with Django creates duplicate content
I had asked a previous question, but the answer was not sufficient. I am trying to render graphs in a Django template using change of a dropdown using Ajax. But this creates duplicate content in the UI. I am not sure why this is happening. Here is my code Django view def home(request): if request.method=='POST': year = request.POST['year'] df, cus_dict = generate_df(year) year_choro = createStormDataGraph(year, cus_dict) context = {'graph': year_choro, 'year': year} return render(request, 'index.html', context=context) default1 = default() context = {'default': default1} return render(request, 'index.html', context=context) def ajax(request): return render(request, 'ajax.html') home template <form action="{% url 'home' %}" method='post' class='center' id='year-form'> {% csrf_token %} <div class="line-break"></div> <select class="form-select form-select-lg mb-3 dropdown-btn" aria-label="Default select example" name="year" id='dropdown-btn'> <option value="none" selected disabled hidden> Select a year </option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select> </form> <div id="message"></div> <div class="graph center" id='graph'> </div> ajax template <body> {% if graph %} {{ graph.0|safe }} {% else %} no graph was provided {% endif %} </body> javascript <script type="text/javascript"> $('#dropdown-btn').on('change', function () { var frm = $('#year-form'); $.ajax({ type: frm.attr('method'), url: "{% url 'home' %}", data: frm.serialize(), success: function (data) { console.log('success') $(graph).html(data) }, error: function (data) { $("#message").html("Something went wrong!"); } … -
Cant get data from view to django template
Problem as in title. I can not get data from view to template I get <QuerySet [{'id': 3, 'order_user_id': 13, 'ordered': False, 'total': Decimal('0.00')}]> when i use {{ order }}. I would like to get OrderedItems and Total from Order Model. How can i do that? views.py def cart(request): order = Order.objects.values() context = {'order': order} return render(request, 'shop/cart.html', context) models.py: class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Order(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11) class Item(models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) cart.html {% extends 'shop/base.html' %} {% block content %} <div class="container"> {% include 'shop/navbar.html' %} <div> {{order}} {{order.total}} </div> </div> {% endblock content %} -
nm, address = addr ValueError: not enough values to unpack (expected 2, got 1), Django Rest Framework
I am working on a personal project that is an E-Commerce made with Django Rest Framework and Vue.js. I have created a contact form and when I try sending it, it creates an error: /venv/lib/python3.9/site-packages/django/core/mail/message.py", line 96, in sanitize_address nm, address = addr ValueError: not enough values to unpack (expected 2, got 1) It seems like it needs some kind of additional value that it doesn't get from my views.py. This is my Serializer: from rest_framework import serializers from .models import Contact class ContactForm(serializers.ModelSerializer): class Meta: model = Contact fields = ( 'first_name', 'last_name', 'phone', 'email', 'subject', 'message', ) This is my Views.py: from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from django.core.mail import send_mail from django.template.loader import render_to_string from .models import Contact from .serializers import ContactForm @api_view(['POST']) def contact_form_post(request): if request.method == "POST": serializer = ContactForm(data=request.data) if serializer.is_valid(): first_name = serializer.validated_data['first_name'], last_name = serializer.validated_data['last_name'], phone = serializer.validated_data['phone'], email = serializer.validated_data['email'], subject = serializer.validated_data['subject'], message = serializer.validated_data['message'] print(first_name, last_name, phone, email, subject, message) context = { 'first_name': first_name, 'last_name': last_name, 'phone': phone, 'email': email, 'subject': subject, 'message': message } send_mail( subject, render_to_string('emails/contact.txt', context), email, ['emailThatItryToUse@gmail.com'], fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None ) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return …