Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Doesn't django implement Content Security Policy by default?
In a RoR project I had <%= csp_meta_tag %> in the main html file. I was trying to build a conceptual app in Django with the knowledge I had at RoR, but when searching for Django Content Security Policy, only a extension appears (https://django-csp.readthedocs.io/en/latest/). There is no documentation regarding the topic so, is it possible that Django does not solve this common security issue by default? Also, I only found this SO question about this. -
How can I use Wagtail Forms for a Headless CMS? ( without Template )
According to the documentation, Wagtail API is read-only ( POST Method not allowed ). Hence, the only way to use Forms from the Sidebar Menu is using Templates, so the client is capable of making post requests against the API internaly. But that´s not headless. To be headless the API must be capable of receiving form data by providing a URL. Wagtail Docs - API "The Wagtail API module exposes a public, read only, JSON-formatted API which can be used by external clients (such as a mobile app) or the site’s frontend." ... At this point I´m not having the slightest clue, that means at a last resort I have to rethink my stack, although so far I have been very satisfied with Wagtail as headless CMS together with Nuxt as Client. Any ideas to avoid this measure would be much apprechiated. -
POST 400 Bad Request in React/Axios/Django
I'm building a website with React, with a Django backend. I have a button that when clicked runs the following function (I want to be able to send post requests from an AuthContext to be able to share the context with all my components): async function handleLogIn(e) { e.preventDefault(); const data = { email: "nultero", password: "password123", }; const headers = { "Content-Type": "application/json" }; const api = axios.create({ baseURL: "http://localhost:8000", }); try { const { resp } = await api.post("users/token/", data, { headers: headers, }); localStorage.setItem("@ezbps:JWToken", resp); console.log(resp.data); } catch (err) { console.error(err); } } Here are the console errors I get: POST http://localhost:8000/users/token/ 400 (Bad Request) dispatchXhrRequest @ xhr.js:177 xhrAdapter @ xhr.js:13 dispatchRequest @ dispatchRequest.js:52 Promise.then (async) request @ Axios.js:61 Axios.<computed> @ Axios.js:87 wrap @ bind.js:9 handleLogIn @ index.js:43 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ react-dom.development.js:237 invokeGuardedCallback @ react-dom.development.js:292 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306 executeDispatch @ react-dom.development.js:389 executeDispatchesInOrder @ react-dom.development.js:414 executeDispatchesAndRelease @ react-dom.development.js:3278 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287 forEachAccumulated @ react-dom.development.js:3259 runEventsInBatch @ react-dom.development.js:3304 runExtractedPluginEventsInBatch @ react-dom.development.js:3514 handleTopLevel @ react-dom.development.js:3558 batchedEventUpdates$1 @ react-dom.development.js:21871 batchedEventUpdates @ react-dom.development.js:795 dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568 attemptToDispatchEvent @ react-dom.development.js:4267 dispatchEvent @ react-dom.development.js:4189 unstable_runWithPriority @ scheduler.development.js:653 runWithPriority$1 @ react-dom.development.js:11039 discreteUpdates$1 @ react-dom.development.js:21887 discreteUpdates @ react-dom.development.js:806 dispatchDiscreteEvent @ react-dom.development.js:4168 Error: Request failed … -
generate barcodes with crud information in python
This is a control access for builders with double check to enter the work area, first with the official ID then the barcode to verify the information. I already built a crud using Python, Django and Postgresql without the barcode because still don't know how to connect the data with the EAN code. How can I connect this information with the codebar to show on modal window? -
Getting ValuError: Field 'id' expected a number but got a html
I am a newcomer, about 10 days into a self-taught Django, and I am building a Django (v3.2) app. The main view in the app is a list of countries (view: CountryListView, template: countries_view.html). When I click on a country in that list, a detail view is brought up to see detailed country data (CountryDetailView and country_detail.html). In CountryDetailView, there are navigation buttons: either back to CountryListView, or 'Edit', which shall bring the user to CountryEditView, where the country parameters can be changed & saved. However, when I click on 'Edit', I get the following error: Request Method: GET Request URL: http://127.0.0.1:8000/manage_countries/countries/country_edit.html/ Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'country_edit.html' I am guessing this might to do something with values returned (or rather expected but not returned) from CountryDetailView, but what they are? And how to make CountryDetailView to return the object id? (I am using plain integer id's in my model) views.py class CountryListView(LoginRequiredMixin, ListView): model = Countries context_object_name = 'countries_list' template_name = 'manage_countries/countries_view.html' class CountryDetailView(LoginRequiredMixin, DetailView): model = Countries template_name = 'manage_countries/country_detail.html' class CountryEditView(LoginRequiredMixin, UpdateView): model = Countries template_name = 'manage_countries/country_edit.html' success_url = reverse_lazy('manage_countries:countries_view') urls.py path('', CountryListView.as_view(),name='countries_view'), path('countries/<pk>/', CountryDetailView.as_view(), name='country-detail'), … -
Django Migrations not updating Heroku PostgreSQL database
I've been stuck on an issue for a while where I have a model that I've created locally (class User(AbstractUser)), ran "python manage.py makemigrations" and "python manage.py migrate", which also works and interacts correctly with the django server when run locally. When I push this to heroku however, I receive an error response to certain api requests which essentially say "relation "app_user" does not exist". I assumed this was because somehow the postgreSQL db didn't receive the migrations when the app was deployed to heroku. After logging into the db I noticed that it had a few other tables, including "auth_user" (I assume this is a default django table), but not "app_user". I have done "heroku run bash" and "python manage.py migrate" in an attempt to migrate the changes to the postgreSQL db, but this doesn't have any effect. I'm not sure if this will be useful but the postgreSQL server I'm using is the standard Heroku Postgres Hobby Dev add-on. My questions are: Should running "python manage.py migrate" on heroku update the postgreSQL database? If so, how does this work? Given that the migrations are all on heroku, how can I manually update the postgreSQL with the migrations? -
Django Add default value to model field having the value of another field
I want to add a field to my django model and I want its default value to be equal to the primarykey value (id), but I want it to apply to all already existing records in my database. class ModelB(models.Model): id= models.IntegerField() index = models.IntegerField(default=" i want something here to get id value") I found previous questions covering this but the answers only give a solution where you have to add a method that adds the value on save. In my case I want this value to be applied to previously saved records also. Please if you have an idea I'd appreciate your help, thanks. -
Django not saving ModelForm data
I've looked at other questions but I can't find the root of my problem. I'm making a checkout view which should save an address with a customer. It creates an Address object, with a customer referenced but isn't saving any of the form data. It just has an Address object with empty fields other than the customer field. models: class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=200) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) postal_code = models.CharField(max_length=15, null=True, blank=True) class Meta: verbose_name_plural = "addresses" class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total def get_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class Meta: verbose_name_plural = "orders" forms.py class AddressForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) class Meta: model = Address fields = ['name','line_1', 'line_2', 'state', 'postal_code', 'country' ] payment.py (view) import stripe from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, JsonResponse from django.urls … -
How to configure the Index.fcgi path?
I'm finishing with setting up my Django project on my hosting using ssh. i am following an article to be able to install it correctly. Some of the steps I had to follow are as follows: Create the . htaccess file with the settings of the FCGI Handler and redirection to the index.fcgi file that will be created: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] and Create the index.fcgi file in the root of your application with the following content: #!/home/CONTA/.virtualenv/bin/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home/CUENTA/mydjango") os.environ['DJANGO_SETTINGS_MODULE'] = "mydjango.settings" WSGIServer(get_wsgi_application()).run() Already having those two files in the public html and opting the permissions to the index.fcgi using chmod 0755 At the time of me see if it is running using the following command ./index.fcgi, tells me that there is no file or directory. Which leads me to assume that I need to set a path within the index.fcgi or . htaccess but I do not know what I need to change since in the article only comes that. Thank you -
How to update fields of currently logged in user with data from stripe webhook ex) subscription, customer in django?
import stripe from django.http import HttpResponse from django.conf import settings from django.contrib.auth.decorators import login_required from django.http.response import JsonResponse from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model I need help with getting the currently logged in user to update their subscription and customer fields, to what gets returned from stripe. Any help would be very appreciated. @csrf_exempt def payment_confirmation_webhook(request): endpoint_secret = 'wh***********************' payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] subscription = session.get('subscription') customer = session.get('customer') else: print('failed') return HttpResponse(status=200) I tried this but I don't have an id to look for since its stripe who is hitting the endpoint so obviously I can't use request.user.id user = get_user_model().objects.get() -
Why When i try to open a link using object id then it's not working in django 3.2?
I am using django 3.2 and i am trying to learn how i can print models.py data on my html page. During this i wanted to add a href tag on home page that will redirect to about page with object id and display the other details. But it's not working. App Name is greeting_app greeting_app/urls.py from . import views urlpatterns = [ path('', views.home, name="home"), path('/about/<int:pk>/', views.about, name="about"), ] greeting_app/models.py from django.db import models from django.db.models.enums import Choices # Create your models here. gender_choice = ( ("0", "Nothing"), ("1", "Male"), ("2", "Female"), ) class basicinformation(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() gender = models.CharField(choices=gender_choice, max_length=10) description = models.TextField() def __str__(self): return self.name greeting_app/views.py from django.shortcuts import render, HttpResponse from .models import basicinformation # Create your views here. def home(request): information = basicinformation.objects.all() return render(request, 'index.html', {"info":information}) def about(request, id): data = basicinformation.objects.get(id=id) return render(request, 'about.html', {"data":data}) -
Django: How to clean a model with inlines?
I created an app that implements a quiz. I got a glitch, however, when I tried to clean a model. models.py class Question(models.Model): def clean(self): options = Option.objects.filter(question=self) correct = 0 for option in options: option.save() print(option) if option.correct == True: correct += 1 print(correct) if correct > 1: raise ValidationError(_('Please only input 1 correct answer.')) if correct <= 0: raise ValidationError(_('Please input 1 correct answer.')) #limit questions if options.count() > 4: raise ValidationError(_('Only 4 maximum amount of options!')) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="question") correct = models.BooleanField(default=False, verbose_name="Correct?") The problem I figured is that when the site tries to save each question, it saves each model Question before saving each Option. -
Different ways to add an app to settings.py
There are two ways to add an app to Django's settings.py: 'appname.apps.AppnameConfig', and 'appname', I know for third-party apps installed through pip, it is not possible to use the first method. But what's the pros and cons of each method? -
Django Extended page is not rendering image as expected
Basically, I am trying to build a website similar to one from W3Schools. However, the image does not get rendered unless I add like 500px top padding. Here is the link to the sample page: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_templates_startup base.html {% load static %} <!DOCTYPE html> <html lang="en"> <link rel="icon" href="{% static 'images/favicon.ico' %}" type="image/x-icon"> <head> <title>{% block title %}{% endblock %}</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <style> body, h1, h2, h3, h4, h5, h6 { font-family: "Raleway", sans-serif } body, html { height: 100%; line-height: 1.8; } .w3-bar .w3-button { padding: 16px; } </style> <body> <!-- Navbar (sit on top) --> <div class="w3-top"> <div class="w3-bar w3-white w3-card" id="myNavbar"> <a href="/"><img src="{% static 'images/logo.png' %}" style=" position: absolute; height: 60px; padding: 5px; left: 100px"></a> <!-- Right-sided navbar links --> <div class="w3-right w3-hide-small"> {% if request.user.is_authenticated %} <a href="{% url " home " %}" class="w3-bar-item w3-button">Feed</a> <a href="/" class="w3-bar-item w3-button">Messages</a> <a href="{% url " dashboard " %}" class="w3-bar-item w3-button">Account</a> <a href="{% url " logout " %}?next=/" class="w3-bar-item w3-button">Logout</a> {% else %} <a href="{% url " login " %}" class="w3-bar-item w3-button">Log In</a> <a href="{% url " register " %}" class="w3-bar-item w3-button">Register</a> {% endif %} … -
Django filter objects before deadline
I have a list of jobs. I want to display only the jobs whose deadline of application has not been crossed yet compared to today's date. in my model.py, I have a model for Job. It has a field called job_deadline which is a DateField. How do I get all the jobs which are active? It should be something like Jobs.objects.filter(job_deadline > date.today()). But this does not work -
Saving Model with Generic Relation throws Exception when saving inside transaction atomic
I have this model where i save fees that should billed at a later stage. Since several Models could generate fees I set up a Generic Relation. class Fee(models.Model): content_type = models.ForeignKey(ContentType, blank=True, null=True, related_name='fees', on_delete=models.CASCADE) object_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) content_object = GenericForeignKey() class FeeType(models.IntegerChoices): SALES_CREDIT = 1, 'Sales Credit' MANAGEMENT = 2, 'Management Fee' BROKERAGE = 3, 'Brokerage Fee' PLATFORM = 4, 'Platform Fee' MARKETING = 5, 'Marketing Fee' DISCOUNT = 6, 'Discount' NOFEE = 99, 'No Fee' fee_type = models.IntegerField(choices=FeeType.choices) fee_date = models.DateField(auto_now_add=True) due_date = models.DateField(editable=False) creditor = models.ForeignKey('users.Company', on_delete=models.CASCADE, related_name='fee_credit') debitor = models.ForeignKey('users.Company', on_delete=models.CASCADE, related_name='fee_debit') quantity = models.PositiveBigIntegerField() rate = models.DecimalField(max_digits=10, decimal_places=4) class RateType(models.IntegerChoices): PERCENTAGE = 1, 'Percentage' NOMINAL = 2, 'Nominal' rate_type = models.IntegerField(choices=RateType.choices, default=1) taxes_due = models.BooleanField(default=True) including_taxes = models.BooleanField(default=True) tax_rate = models.DecimalField(max_digits=4, decimal_places=2) total_amount = models.DecimalField(max_digits=12, decimal_places=2, editable=False) total_taxes = models.DecimalField(max_digits=12, decimal_places=2, editable=False) total_amount_incl_taxes = models.DecimalField(max_digits=12, decimal_places=2, editable=False) billed = models.BooleanField(default=False) paid = models.BooleanField(default=False) And I have a function living in a celery task that prepares the data to be saved into said model: @shared_task def log_fee(model, fee_type, creditor_pk, debitor_pk, quantity, rate_type, rate=None, taxes_due=True, including_taxes=True, tax_rate=None, fee_date=None): from fees.models import Fee from users.models import Company logger.info(f'{model} {fee_type} {creditor_pk} {debitor_pk} {quantity} {rate_type} {rate} {taxes_due} … -
What tech stack to use for a project using multiple API I/O processes in background?
I am unable to decide what technology would be better to use for my project. The project has the following purpose. I will be using a 3rd party API service for 2 major purpose Creating, updating, and deleting events. Fetching past changes made. So at any point in time, I can start a new service, that will be creating new events for me by loading data from an excel file and, this service would now be running in the background (also having the functionality to pause/stop the service at any time). Multiple such services of creation from different excel files will run simultaneously in the background. Similar to the above service, I will create a fetch service to fetch data in regular intervals indefinitely and dump that data in an excel file. Again, this service will also run in the background and can be paused/stopped. Multiple such services will also run in the background. Now, for the project, I have 2 questions regarding what Tech Stack I should use. Should I go for a Django based web app or should I go for NodeJs based webapp? If I choose Django, what are the ways I can achieve concurrency and parallelism? … -
Django and Django channels
I have one django project, which uses django channels as well. Now I want to separate django channels into a separate project. Means, one applicaton will have two django projects, Django for http request. (Django http) Django for websocket request. (Django async) But, the problem is, if I separated both of these projects, How django async project will use models?? Note:- I want common database between both projects. -
Como hacer para que el admin de Django me cargue un combo-box , según uno anterior [closed]
Tengo estos modelos en la clase geolocalizacion. @admin.register(DivisionTerritorial) class DivisionTerritorialAdmin(BaseImportExportModelAdmin): """ Administrador modelo DivisionTerritorial """ search_fields = ['nombre'] list_filter = ['municipio', 'tipo_division'] list_display = ['nombre', 'tipo_division', 'municipio', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion'] readonly_fields = [ 'creado_por', 'fecha_creacion', 'ip_creacion', 'modificado_por', 'fecha_modificacion', 'ip_modificacion', 'eliminado_por', 'fecha_eliminacion', 'ip_eliminacion' ] resource_class = DivisionTerritorialResource fieldsets = ( ( None, { 'classes': ('suit-tab suit-tab-general',), 'fields': ( 'nombre', 'tipo_division', 'municipio', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion' ) } ), ) inlines = [BarrioInline,] suit_form_tabs = ( ('general', _('Divisiones territoriales')), ('Barrio', _('Barrio')), ) @admin.register(Barrio) class BarrioAdmin(BaseImportExportModelAdmin): """ Administrador modelo Barrio """ search_fields = ['nombre'] list_filter = ['municipio', 'zona_ubicacion'] suit_list_filter_horizontal = ('municipio', 'zona_ubicacion') list_display = ['nombre', 'municipio', 'division_territorial', 'zona_ubicacion', 'latitud', 'longitud', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion'] fields = ['nombre', 'zona_ubicacion', 'municipio', 'division_territorial', 'latitud', 'longitud', 'fecha_creacion', 'fecha_modificacion','fecha_eliminacion'] readonly_fields = [ 'creado_por', 'fecha_creacion', 'ip_creacion', 'modificado_por', 'fecha_modificacion', 'ip_modificacion', 'eliminado_por', 'fecha_eliminacion', 'ip_eliminacion' ] raw_id_fields = ['municipio'] resource_class = BarrioResource Estan unidos por una Fk y necesito que cuando los llame en otro modelo estos aparezcan segun la fk anterior. enter image description here Entonces necesito que si elijo un Departamento en la siguiente casilla me liste los municipios pertenecientes a ese departamento. Vi en todo lado que se podría realizar con Ajax pero no se como usarlo aquí en el admin, … -
my form sends GET instead of POST, i have created a form which get input and i would like to send it to the database
i asked this question but was not properly asked. i'm working on my e-commerce project using django. i created form which should take input and update it into the database but unfortunately it is not sending any data to the database and although i specified the action to POST but i'm getting GET and POST together in my terminal here is the result i get: [16/Jun/2021 18:09:23] "POST /cart/addcomment/1 HTTP/1.1" 302 0 [16/Jun/2021 18:09:23] "GET /en/cart/addcomment/1 HTTP/1.1" 302 0 URL: /media/product_images/iphone-compare-models-202010_GEO_US_eDOyoqO.jpeg URL: /media/product_images/iphone-compare-models-202010_GEO_US_eDOyoqO.jpeg [16/Jun/2021 18:09:23] "GET /en/cart/shop/iphone-12-pro/? **models.py:** class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) rate = models.IntegerField(default=1) ip = models.CharField(max_length=20, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject **views.py:** def addcomment(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): data = Comment() # create relation with model data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.rate = form.cleaned_data['rate'] data.ip = request.META.get('REMOTE_ADDR') data. product_id = id current_user = request.user data.user_id = current_user.id data.save() # save data to table … -
How i can create a delete button in django python?
I'm new to Django and i try my best to resolve this problem. So i try to create a delete button on my template. I create my view and i create my url but it doesn't work. So here my views : def book_delete(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == 'POST': book.delete() return redirect('/') return render(request, "livre/newbook_form.html", {'form': book}) My urls from . import views from django.conf.urls import url urlpatterns = [ url(r'^livre/(?P<pk>[0-9]+)/$', views.book_delete, name='book_delete') ] My template <form action="liste" method="POST">{% csrf_token %} <table> <th>Titre</th><th>Auteur</th><th>Nombre de pages</th><th>Supprimer</th> {% for Book in Book %} <tr> <td>{{ Book.title }}</td> <td>{{ Book.author }}</td> <td>{{ Book.num_pages }}</td> <td> <form action="{% url 'book_delete' Book.id %}" method="POST"> {% csrf_token %} <input type="button" value="{{Book.id}}"/> </form> </td> </tr> {% endfor %} </table> </form> I don't know why it doesn't work. Can you help me ? -
Alguna de convertir estas querys a json? [closed]
estoy buscando alguna manera de hacer que mi codigo al momento de enviar un "GET" con postman me devuelva algunas querys que tengo en la BD pero en forma de archivo json, Alguna idea? Muchas gracias! dejo parte del codigo... import json from typing import Container from website.serializer import ProductoSerializer from django.http import HttpResponse from django.core.serializers import serialize from django.shortcuts import render from django.http.response import HttpResponseRedirect, HttpResponse, JsonResponse from django.views.generic import CreateView, UpdateView, DeleteView, ListView, TemplateView from django.urls import reverse_lazy from .models import Cliente, Producto from django import forms from django.views import generic from rest_framework.parsers import JSONParser from django.views.decorators.csrf import csrf_exempt from rest_framework import status from django.core.serializers import serialize # Create your views here. def home(request): return render(request, 'website/home.html') def clientes(request): return render(request, 'website/clientes.html') # vista instrumentos def producto(request): return render(request, 'website/producto.html') def otros(request): return render(request, 'website/otros.html') class ClienteCreate(CreateView): model = Cliente #form_class = clientes fields = '__all__' template_name = 'website/cliente_form.html' success_url = reverse_lazy('clientes_list') class ClienteUpdate(UpdateView): model = Cliente #fields = ['nombre','telefono','email','direccion','usuario','contrasenia'] fields = '__all__' success_url = reverse_lazy('clientes_list') class ClienteDelete(DeleteView): model = Cliente success_url = reverse_lazy('clientes_list') class ClienteDetailView(generic.DetailView): model = Cliente class ClienteListView(generic.ListView): model = Cliente template_name = 'website/clientes_list.html' #Producto CRUD class ProductoCreate(CreateView): model = Producto fields = '__all__' template_name … -
disabling/enabling a field in Django form depending on a value of another field in the same form
Asking a beginner's question. I have a ModelForm object with a quite large number of fields. I want some of these fields to assume to be editable or not editable, based on a value of some other field (in the same form): For example: split_words = forms.BooleanField() split_words_min_length = forms.IntegerField(min_value=1,max_value=140) I would like split_words_min_length field to be disabled (or not displayed), if split_words is set to False (unchecked). What would be a clean way how to achieve this? -
Displaying one value and sending another to backend with HTML <select> and <option> tags
I'm making a note-taking web app. The rich text editor includes a drop-down menu containing the names of each of the user's notebooks, so that the user can choose where the note will go. So far so good. The problem is that, in theory, the user could name two notebooks the same thing. So when the user chooses a notebook, the frontend ultimately needs to send the ID slug associated with that specific notebook to the backend, so that Django can choose which notebook to associate the note with without ambiguity. The problem is that I don't know how to make the HTML <select> and <option> tags do what I want them to. I tried putting in one value between the HTML tags (so that it's displayed) and passing the ID as the tag's value attribute, but this doesn't seem to work: setNotebooks(notebookList.map(item => { return ( <option value={item.notebook_id}> {item.name} </option> ); When I set notebooks in the way I showed above, it comes back as undefined. In the example, notebookList is an array of objects containing each notebook's attributes. I tried wrapping each <option> tag in the <select> one in a higher-order component with its own state that would … -
Django static files not working for other templates except index
I am developing an agency web app with django templates & static files. But I am having trouble with loading static files on pages other than index. Here's my folder heirarchy. Again, I am having no problems loading static files on my index page. Here's code of my additional page services.html (one I am trying to load static files on): {% extends 'base.html' %} {% load static %} {% block content %} ... ... ... {% endblock %} My base.html is working totally fine with the homepage index.html. I've included this on my settings.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And, my views.py and urls.py files are working fine too. Also my CSS file is correctly linked to the services.html file. I can tell this from the inspection. Here's the error list shown on inspection. Help will be appreciated. Thank you.