Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view sometimes routes to wrong URL
I have a Django project with this layout in the urls.py from django.contrib import admin from django.conf.urls import url as path from mapping import views urlpatterns = [ path('admin/', admin.site.urls), path('map/', views.Map, name='map'), path('address',views.Address_Search,name='address') ] views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse import geocoder import pdb bingkey='mykey' def Map(request): return render(request,'mapping.html') @csrf_exempt def Address_Search(request): try: address=request.POST.get('fname') print(address) g = geocoder.bing(address,key=bingkey) x,y= g.latlng[1],g.latlng[0] print(x,y) return JsonResponse({'id': 1,'x': x, 'y': y,'Address': address}) except Exception as e: print(e) return render(request,'mapping.html') and in templates I have a mapping.html which contains {% block content %} <html> {% load static %} {% load leaflet_tags %} {% load bootstrap4 %} <head> {% leaflet_js %} {% leaflet_css %} {% bootstrap_css %} <title>Sals Food</title> <style type="text/css"> #map {width: 100%;height:800px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'search_bar.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap-4.0.0-dist/css/bootstrap.css' %}" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet" /> <script type="text/javascript" src="{% static 'jquery/jquery-3.3.1.min.js' %}" > </script> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'turf/turf.min.js' %}" > </script> <script type="text/javascript" src="{% static 'basemaps/leaflet-providers.js' %}" > </script> <script> function subForm() { var jsdata = {"fname": $('#fname').val()}; console.log(jsdata); var url = "/address/"; var jqHdr = $.ajax({ async: true, cache: false, type: … -
Why django custom user model giving error when inherited PermissionsMixin?
Whenever I want to inherit PermissionsMixin like UserAccount(BaseAbstractUser, PermissionsMixin) it gives an error, but if I don't inherit PermissionsMixin then my user model work but don't have some fields permissions, is_superuser. What is the right way? Error: ValueError: Invalid model reference 'app.auth.UserAccount_groups'. String model references must be of the form 'app_label.ModelName'. My Custom Model: # app/auth/models.py from django.contrib.auth.base_user import ( AbstractBaseUser, BaseUserManager ) from django.contrib.auth.models import PermissionsMixin from django.utils import timezone from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password=None, **extra_fields): # altmost the same codes here... user.save() return user def create_user(self, email, password=None, is_active=True, **extra_fields): # altmost the same codes here... return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): # altmost the same codes here... return self._create_user(email, password, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=150, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now, editable=False ) last_login = models.DateTimeField(null=True) objects = … -
Django save files from FileField in docker container
I have a model with a FileField. My application is running in a docker container created with a dockerfile. When I save a file it is saved on my local path instead of the containers base root. But when I try to retrieve the file and send it as attachment in an email I get a file not found error. The media root directory is based on the Dockerfile's base root. The email is built and sent in another container as an async task. The Dockerfile looks like this: # pull official base image FROM python:3.9.1-alpine # set work directory #ENV APP_HOME=/code #RUN mkdir $APP_HOME #RUN mkdir $APP_HOME/static #RUN mkdir $APP_HOME/media #WORKDIR $APP_HOME WORKDIR /code # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /code/ RUN apk --update --upgrade --no-cache add \ postgresql-libs make gdal-dev geos-dev g++ python3-dev cairo-dev pango-dev gdk-pixbuf-dev ttf-ubuntu-font-family RUN \ apk add --virtual .build-deps gcc musl-dev postgresql-dev jpeg-dev zlib-dev libffi-dev && \ pip3 install --no-cache-dir -r /code/requirements.txt && \ apk --purge del .build-deps COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # copy project COPY . /code/ I have a docker-compose file to build the image and run the container. It looks like that: … -
super(type, obj): obj must be an instance or subtype of type Django
I work on a small Django App and get an error tells me: super(type, obj): obj must be an instance or subtype of type.I am trying to save the details of the sale in the database but I get this error. ErrorPic Views class VentaCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView): model = Venta form_class = nueva_venta_form template_name = 'venta/venta_form.html' success_url = reverse_lazy('Index') permission_required = 'store_project_app.change_categoria' url_redirect = success_url @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': elif action == 'add': #ventas = request.POST['action'] #ventas = request.POST['ventas'] ventas = json.loads(request.POST['ventas']) #print(ventas) venta = Venta() venta.id_cliente = Cliente.objects.get(id_cliente = ventas['id_cliente']) venta.id_empleado = Empleado.objects.get(id_empleado = ventas['id_empleado']) venta.fecha_venta = ventas['fecha_venta'] venta.forma_pago = Metodo_Pago.objects.get(id_metodo_pago = ventas['forma_pago']) venta.precio_total = float(ventas['precio_total']) venta.save() for i in ventas['productos']: detalle_venta = Detalle_Venta() detalle_venta.id_venta = venta.id_venta detalle_venta.id_producto = i['id_producto'] detalle_venta.cantidad = int(i['cantidad']) detalle_venta.subtotal = float(i['subtotal']) detalle_venta.save() else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) return JsonResponse(data, safe=False) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Crear una Venta' context['entity'] = 'Venta' context['list_url'] = self.success_url context['action'] = 'add' return context -
How to pass a value from a method in a class to another?
I'm using Django Rest Framework and I have two simple view classes: class FirstView(APIView): def post(self, request): random_number = randint(10,99) return Response({'pass': True}) and class SecondView(APIView): def post(self, request): return Response({'random_number': '?'}) and I want to pass the random_number value from FirstView to the SecondView class and return it in the Response. How can I do that? -
Problem with adding js script to the django project
Hi I have a problem with include a js script file to django projects. Script works with tags in html file. Here is my 1st try: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <!--<link rel="stylesheet" href="static/style.css" type="text/css" > --> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <link rel="stylesheet" href="/static/css/main.css"> <script type="text/javascript" src="/static/js/script.js"></script> </head> The 2nd try: {% load static %} <!doctype html> <html lang="en"> <head> {% load static %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <!--<link rel="stylesheet" href="static/style.css" type="text/css" > --> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <link rel="stylesheet" href="/static/css/main.css"> <script src="{% static 'js/script.js' %}"></script> </head> The both tries do not work. Do you have any ideas. Path to js file is static/js/script.js. settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent print("BASE_DIR", BASE_DIR) DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'eeg_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 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', ], }, … -
Render a consumed API on Django to React Front-end
I'm building a Django and ReacJS app. I consumed an API on the backend Django with no Model. It displays the API result in JSON properly on a django HTML page without react, Now how to render it on react frontend alongside other react component. This is the code in Dashboard.JS import React, { useEffect, useState } from 'react'; import Wallet from '../wallet/Wallet'; import withWalletLoading from '../wallet/WithWalletLoading'; import '../../App.css'; import DashboardAPI from './DashboardAPI' import Pricing from '../Pricing' function Dashboard() { const WalletLoading = withWalletLoading(Wallet); const [appState, setAppState] = useState({ loading: false, ngn_balance: null, }); useEffect(() => { setAppState({ loading: true }); const apiUrl = 'wallet/ngn/?format=json'; fetch(apiUrl) .then((res) => res.json()) .then((ngn_balance) => { setAppState({ loading: false, ngn_balance: ngn_balance }); }); }, [setAppState]); return ( <> <WalletLoading isLoading={appState.loading} ngn_balance={appState.ngn_balance} /> {/* <DashboardAPI /> */} <Pricing /> </> ); } export default Dashboard; Even when i use the complete url: http://127.0.0.1:8000/wallet/ngn/?format=json. NB I do get status code 200 on the commandline whenever i visit the react page.. The react page where the code is being called will show properly, then when the API call loads on the page goes blank, wihout showing the API result on the react page, even before and after … -
HttpResponseServerError can't be used in 'await' asgi application when migrated wsgi code to asgi
Getting below error when trying to enable asgi in my Django application AttributeError: 'coroutine' object has no attribute 'has_header' Exception inside application: object HttpResponse can't be used in 'await' expression -
Django Channels Rest sent changes constantly
I'm using Django Channels Rest Framework for list view and additionally, I need to send to the user created/changed instance constantly (i.e. when save() method has been called this instance should be send). Now I have this (the request is sent only once). class ObjectListConsumer(ListModelMixin, GenericAsyncAPIConsumer): serializer_class = ObjectSerializer queryset = Object.objects.order_by('-created_at') permission_classes = (permissions.AllowAny,) What is the best way to do this? Thanks for your time and help. -
Django No static or media file displayed on heroku server ( production ) with whitenoise
so the problem is that my media and static images aren't displayed at all... I know there are a lot of "similar questions" but since i tried almost all of them and none slved my problem, i figured maybe there is an issue with my settings.py file so here it is : ( btw everything works fine over localhost ) settings.py from pathlib import Path import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 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 = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'website', 'gallery', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'inp_website.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 = 'inp_website.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR,'db.sqlite3'), … -
ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend in CentOS7
I have already tried out all the suggestions in other posts. I am trying to connect SQL Server to Django on a Linux CentOS 7 with a virtual environment. I am getting the following error: ) from e_user django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' The setting are the following: Django==2.1.15 django-bootstrap3==14.2.0 django-db-tools==0.0.1 django-filter==2.4.0 django-mathfield==0.1.0 django-model-utils==4.1.1 django-mssql-backend==2.8.1 django-pyodbc-azure==2.1.0.0 django-tables2==2.3.4 django-widget-tweaks==1.4.8 importlib-metadata==1.7.0 pyodbc==4.0.30 pytz==2020.5 sql-server.pyodbc==1.0 sqlparse==0.4.1 zipp==3.4.0 This is my odbcins.ini file: [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1 UsageCount=1 This is the odbc.ini Driver = ODBC Driver 17 for SQL Server Server = IP Database = dbNAME Trace = Yes TraceFile = /tmp/odbc.log And my settings.py DATABASES = { 'default': { 'ENGINE' : 'sql_server.pyodbc', 'NAME': 'dbNAME', 'HOST' : 'IP', 'PORT' : '8000', 'USER': 'username', 'PASSWORD': 'passwrd', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I have tried out to reinstall django-pyodbc-azure as they suggested here Django python 'sql_server.pyodbc' isn't an available database backend but it didn't work for me. I also tried to reinstall the ODBC driver. Appreciate your help Thanks -
Django error import ProhibitNullCharactersValidator
When I run my django app raise this error, i this this is an error related with versions, Im using python 3.6 and Django 1.11.10: from rest_framework_swagger.views import get_swagger_view File "/home/eddy/Documentos/apps/django/multas/venv/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 3, in <module> from rest_framework.renderers import CoreJSONRenderer File "/home/eddy/Documentos/apps/django/multas/venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 22, in <module> from rest_framework import VERSION, exceptions, serializers, status File "/home/eddy/Documentos/apps/django/multas/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 29, in <module> from rest_framework.fields import get_error_detail, set_value File "/home/eddy/Documentos/apps/django/multas/venv/lib/python3.6/site-packages/rest_framework/fields.py", line 15, in <module> from django.core.validators import ( ImportError: cannot import name 'ProhibitNullCharactersValidator' Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x7f7046347f98> this is my requirements.txt cx-Oracle==6.2 Django==1.11.10 pytz==2017.3 django-settings-export ==1.2.1 Pillow==5.1.0 zeep==2.5.0 pylokit==0.8.1 reportlab==3.5.5 templated-docs==0.3.1 django-debug-toolbar==1.9.1 djangorestframework-datatables==0.4.0 rarfile==3.0 django-rest-swagger==2.2.0 python-dateutil==2.7.3 in this code raise error: from django.core.validators import ( EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, ProhibitNullCharactersValidator, RegexValidator, URLValidator, ip_address_validators ) -
save foreign key object django forms
I am facing a problem and I am unable to solve it on my on so I need your help. I am saving profile object using django form and its working perfectly fine on my local system but when I deploy it on server it gives me an error saying: Cannot assign "'demo'": "Profile.company" must be a "Company" instance. demo is company name i am getting from frontend Model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) Form.py class ProfileForm(forms.ModelForm): company = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "Company", "class": "form-control" } )) class Meta: model = Profile fields = ('company',) Views.py company = Company.objects.filter(company_name=request.POST["company"]).first() form = SignUpForm(request.POST) p_form = ProfileForm(request.POST) if form.is_valid() and p_form.is_valid(): u_user = form.save() p_form = p_form.save(commit=False) p_form.user = u_user p_form.company = company p_form.save() -
Set initial value in a form in Django
I have a model in my application: models.py: class bdAccesorios(models.Model): fdClienteAcc=models.CharField(max_length=35) fdProveedorAcc=models.CharField(max_length=60) fdSkuAcc=models.CharField(max_length=30) fdNombreAcc=models.CharField(max_length=60) fdCostoAcc=models.DecimalField(max_digits=8, decimal_places=2) fdUnidadAcc=models.CharField(max_length=30) fdExistenciaAcc=models.IntegerField() fdAuxAcc=models.CharField(max_length=60, default="0") Then, I have a form to add new entries to the model class fmAccesorios(ModelForm): class Meta: model=bdAccesorios fields='__all__' What I can't accomplish is that the form starts with an initial value, so far what I have done in my views is this, but the field shows blank views.py def vwCrearAccesorio(request): vrCrearAcc=fmAccesorios(initial={'fdClienteAcc':"foo"}) ###Here is the problem ### if request.method == "POST": vrCrearAcc=fmAccesorios(request.POST) if vrCrearAcc.is_valid(): vrCrearAcc.save() return redirect('/') else: vrCrearAcc=fmAccesorios() return render(request,"MyApp/CrearAccesorio.html",{ "dtCrearAcc":vrCrearAcc }) MORE INFO: I know that I can use the following code in my form to set initial values def __init__(self, *args, **kwargs): super(fmAccesorios, self).__init__(*args, **kwargs) self.fields['fdClienteAcc'].disabled = True self.fields['fdClienteAcc'].initial = "foo" But I can't use that, because I need the variable "foo" to change dynamically, my ultimate goal is to use the request.user.username variable and then use that variable to get another value from another model -
ImportError: attempted relative import with no known parent package, from .models import User, Blog, Topic
Here is a stucture of my app >db __init__.py (nothing is there) models.py (contains models User, Blog, Topic for django orm) query.py (contains functions with queries) query.py: from .models import User, Blog, Topic (I've tried to import User, Blog, Topic from models in query.py like "from db.models import User, Blog, Topic", "from myproject.db.models import ...", anyway result is the same) Please, help me. I don't know why this is happened -
Filter problem in DJango with Soft Delete
I implemented a soft delete for DJango based on the link below: https://adriennedomingus.medium.com/soft-deletion-in-django-e4882581c340 I have a model Client with a list of Account. When I remove the account: Account.objects.filter(id=1).delete() Account.objects.filter(id=1) # <- returns empty Client.objects.filter(accounts__id=1) # <- returns the client The client should returns empty (like hard delete). Is there any solution to this filter problem? -
Django Page Not Found / No Post matches the given query
I won't go to blog/develops but I get this error: Page not found (404) No Post matches the given query. 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. I don't understand why I am getting this error and how can I solve it. This is my urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name="post_list"), path('<str:adres>/', views.post_detail, name='post-detail'), path('develops/', views.develop_list, name='develop_list') ] This is views.py file: from django.shortcuts import render , get_object_or_404 , redirect from .models import Post from .forms import EmailAbonelikForm def post_list(request): best_post = Post.objects.filter(best=True) posts = Post.objects.filter(best=False, dev = False) return render(request, 'blog/post_list.html', {'posts':posts , 'best_post':best_post}) def post_detail(request, adres): posts = get_object_or_404(Post , adres=adres) if request.method == 'POST': form = EmailAbonelikForm(request.POST) if form.is_valid(): form.save() return redirect('post_list') else: form = EmailAbonelikForm() return render(request, 'blog/post_detail.html', {'posts':posts , 'form':form}) def develop_list(request): posts_dev = Post.objects.filter(dev=True) return render(request, 'blog/develop_list.html', {'posts_dev':posts_dev}) How can I see blog/develops. -
AttributeError: module 'articles.views' has no attribute 'about'
I've been following The Net Ninja Django tutorial on YT (as closely as possibly), but I've hit bit of a snag adding my app (articles) url to the views.py of my main project (website). I keep receiving this error: File "C:File\Path\ToProjects\web_app\website\articles\urls.py", line 6, in <module> url(r'^about/$', views.about), AttributeError: module 'articles.views' has no attribute 'about' I've got Python 3.6 and my pip freeze output is as follows: appdirs==1.4.4 asgiref==3.3.1 distlib==0.3.1 Django==3.1.5 filelock==3.0.12 importlib-metadata==3.1.1 importlib-resources==3.3.0 pytz==2020.5 six==1.15.0 sqlparse==0.4.1 virtualenv==20.2.1 zipp==3.4.0 urls.py in project folder: from django.contrib import admin from django.urls import path, include from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^articles/', include('articles.urls')), url(r'^about/$', views.about), url(r'^$', views.homepage), ] views.py in app folder: from django.http import HttpResponse from django.shortcuts import render def article_list(request): return render(request, 'articles/article_list.html') urls.py from app folder: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.article_list), ] Output of my directory structure Any help is very welcome! -
Why is the data from the combobox not assigned in the variables of my data structure?
I am trying to save the record of the sale with the data that the employee assigns, however, it is not assigning them in the corresponding variables. {id_cliente: undefined, id_empleado: undefined, fecha_venta: "20/01/2021", forma_pago: undefined, precio_total: "4000"} But if you save the ones that are not combobox JS $('form').on('submit', function (e) { e.preventDefault(); ventas.items.id_cliente = $('input[name="id_empleado"]').val(); ventas.items.id_empleado = $('input[name="id_empleado"]').val(); ventas.items.fecha_venta = $('input[name="fecha_venta"]').val(); ventas.items.forma_pago = $('input[name="forma_pago"]').val(); ventas.items.precio_total = $('input[name="precio_total"]').val(); console.log(ventas.items) var parametros = new FormData(); console.log(parametros); parametros.append('action', $('input[name="action"]').val()); console.log($('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); console.log(JSON.stringify(ventas.items)); submit_with_ajax(window.location.pathname, 'Notificación', '¿Esta seguro de realizar la siguiente acción?',parametros, function () { location.href = 'crear_venta'; }); }); -
unable to save venue field
model.py class venue(models.Model): name = models.CharField('Venue name',max_length=120) address = models.CharField(max_length=300) zip_code = models.CharField('zip/post code',max_length=120) phone = models.CharField('contact phone',max_length=20, blank=True) web = models.URLField('web Address', blank=True) email_address = models.EmailField('Email Address', blank=True) admin.py from django.contrib import admin from .models import venue admin.site.register(venue) unable to save data into fields, its occuring OperationErrors -
Does passing a json file as argument makes the rendering html template lose performances?
I have an html webpage: quiz.html returned by the urls.py script of a django application. The questions are just words that are rendered as a ul list of input boxes which I want to transform into related photos where I would be able to do a multi selection click on them. As the ul-input combination looks very heavy I wanted to transform it into a json file that I would pass as an argument of the related function in urls.py wouldn't make me lose performance and if it was a good practice? <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <div class="row"> <div class="col-lg-5 mr-auto order-lg-2"> <div class="recommendations"> <form action = "/getmatch" method="POST"> <p> <label>Your gender</label> <label><input type="radio" name="gender" value="女香">Female</label> <label><input type="radio" name="gender" value="男香">Male</label> </p> </div> <div> <p> <dl class="dropdown"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> <!-- <p class="multiSel"></p> --> </dt> <dd> <div class="mutliSelect"> <ul> <li> <input type="checkbox" name='note' value="甜美" />Sweet</li> <li> <input type="checkbox" name='note' value="温柔" />Gentle</li> <li> <input type="checkbox" name='note' value="优雅" />Elegant</li> <li> <input type="checkbox" name='note' value="成熟" />Mature</li> <li> <input type="checkbox" name='note' value="性感" />Sexy</li> … -
password reset with configuration SMTP
This is my SMTP configuration for my web page. #SMTP (Simple Mail Transfert Protocole) Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*****************' EMAIL_HOST_PASSWORD = '*************' I created a web page using python and Django where the user has to login before. When the user has forgotten his password, he has the possibility to reset his password. to reset his password, the user has to enter his email then the link will be sent to his email provided during his registration. *but when the user enters his email then clicks on send, instead to send the link into his email account, the link is redirect/ sent, to the "EMAIL_HOST_USER".* Problem/Error How should I configure the SMTP (Simple Mail Transfert Protocole) so that the user receives the link of the password reset into his email account provided during his registration? please help me. -
Django Rest Framework not showing form fields for PATCH/PUT request
I have a Django project that is using Django Rest Framework. For some reason, when I go to one of my endpoints (to make a PATCH/PUT request), I am not seeing any of the form fields in the browsable API. Here is the code for the resource: models.py from django.db import models class Patient(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) diagnosis = models.CharField(max_length=200) primary_doctor = models.ForeignKey('Doctor', related_name='patients', on_delete=models.CASCADE, null=True) born_on = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{0.first_name} {0.last_name}".format(self) views.py from rest_framework.views import APIView from rest_framework.generics import RetrieveUpdateDestroyAPIView from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from ..models.patient import Patient from ..serializers import PatientSerializer class Patients(APIView): def get(sef, request): patients = Patient.objects.all()[:10] serializer = PatientSerializer(patients, many=True) return Response(serializer.data) serializer_class = PatientSerializer def post(self, request): patient = PatientSerializer(data=request.data) if patient.is_valid(): patient.save() return Response(patient.data, status=status.HTTP_201_CREATED) else: return Response(patient.errors, status=status.HTTP_400_BAD_REQUEST) class PatientDetail(APIView): def get(self, request, pk): patient = get_object_or_404(Patient, pk=pk) serializer = PatientSerializer(patient) return Response(serializer.data) serializer_class = PatientSerializer def patch(self, request, pk): patient = get_object_or_404(Patient, pk=pk) serializer = PatientSerializer(patient, data=request.data['patient']) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): patient = get_object_or_404(Patient, pk) patient.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py from rest_framework import … -
Django model multiple inheritance
I am using Django 3.1 to build a rudimentary events notification app. Here are my models models.py class Event(models.Model): # WHAT just happened ? (i.e. what kind of event) # these three fields store information about the event that occured content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,related_name='%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # WHO caused it ? (this could also be the system user) actor = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, on_delete=models.CASCADE,related_name='%(class)s_user') # WHEN did it happen ? created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['content_type', 'object_id', 'actor'],name='%(class)s_unique_name')] class Welcome(Event): pass class Goodbye(Event): pass views.py (simplified) def say_welcome(request): data = get_params_from_request(request) Welcome.objects.create(data) def say_goodbye(request): data = get_params_from_request(request) Goodbye.objects.create(data) My question is that will I be able to carry out CRUD functionality on the Welcome and Goodbye models and then also be able to query ALL events through the Event model? -
(django) Showing posts according to interests of users
I am pretty new to Django and still learning it, but I have to create something like medium.com. I want to show posts to users according to their interests. I added an interests field with a checkbox in a sign-up form. And of course, I added a category to the Post model. So, how can I show (to logged-in users only) publications that they interested in? Here is my models.py file in posts app from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): CATEGORY = ( ('sport', 'Sport'), ('science', 'Science'), ('it', 'IT'), ('art', "Art"), ) title = models.CharField(verbose_name="Title for publication", max_length=50) category = models.CharField(verbose_name="Category", choices=CATEGORY, max_length=50) author = models.ForeignKey("accounts.User", verbose_name="Author:", on_delete=models.CASCADE) body = models.TextField(verbose_name="Body for publication") pub_date = models.DateTimeField(verbose_name="Date:", auto_now_add=True) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title And here is my vies.py file in posts app from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Post from django.urls import reverse_lazy class PostListView(ListView): model = Post template_name = "index.html" def get_queryset(self): return Post.objects.order_by('-pub_date') class PostDetailView(DetailView): model = Post template_name = "./posts/post_detail.html" class PostCreateView(CreateView): model = …