Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Javascript: How To Use Class Name With Template Tag Inside As Identifier in Function
I am using a for loop to print out all of the posts on my site and each post will have a form that allows users to add that post to a list. I am trying to use ajax to do this so that there is no page refresh. The ajax function works on the first post but on all of the others there are issues. i think that the issues are due to each post having the same class name that is being used to identify it, so this is why i want to use the forloop counter in the class name so that each one has a unique identifier. Here is some relevant code: Javascript: #this is where i want the class to have a tag inside $('.collection_save_form').submit(function(e){ e.preventDefault() const url = $(this).attr('action') const post_id = $(this).attr('name') const collection_id = $(this).attr('id') const text = $(`.saved_text${collection_id}`).text() var saveElement = document.getElementById(`save_btn${collection_id}`); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, 'collection_id': collection_id, }, success: function(response){ if (saveElement.classList.contains("saved")){ saveElement.classList.remove("saved") $(`.saved_text${collection_id}`).text('Save') } else if (!$(this).hasClass("saved")) { saveElement.classList.add("saved") $(`.saved_text${collection_id}`).text('Saved') } }, error: function(response){ console.log('error', response) } }) }) Code with the form: {% for item in posts %} #irrelevant post data … -
In spite of the fact that I have created the django project in the same conda environment it is showing the ImportError: Couldn't import Django?
I haven't even restartted the system. But I do have other conda environments with django version=1.* and 2.. I am facing this issue in 3. version of django. Can switching between these versions of django through conda environments can cause this problem? Because I am facing this problem often. Whatever the case maybe, please help me fix this. File "C:\Users\vinniiee\Desktop\django_blog_project\django_blog_project\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Django duplicating block.super content
using in template inheritance as in the docs here I'm getting duplication as shown: In the above photo the commented Google Tag Manager text has been duplicated. Obviously I would like to put the actual tag manager in there, but it's a simpler example for SO this way. Anything I put in my child template tag is duplicated when I call {{ base.super }} I'm using Oscar, so here's my inheritance scheme. oscar/base.html #from oscar module #relevent sections only {% load i18n %} {% load static %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="{% block html_class %}no-js{% endblock %}"> <head> {% block tracking %} {# Default to using Google analytics #} {% include "oscar/partials/google_analytics.html" %} {% endblock %} </head> my base override # located in my procject at 'oscar/base.html' {% extends 'oscar/base.html' %} {% block tracking %} {{ block.super }} <!-- Google Tag Manager --> <!-- End Google Tag Manager --> {% endblock %} Below is anything else I think could be involved. Any troubleshooting tips that would help me debug this would be welcome. my view from django.http import HttpResponse from django.views.generic.base import TemplateView class BaseTestView(TemplateView): template_name = "oscar/base.html" urls.py from myurls import BaseTestView urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), … -
How to transfer data from HTML button to Django?
I want to make adjustable pagination, three buttons created: 10, 20 and 50 news per page. My html Django template element that in charge of pagination is {% autopaginate news 10 %}, where 10 is number of news per page. Also i can set in in views and use any variable {% autopaginate news variable %}. How to transfer meaning of some button to this variable? Or how to do adjustable pagination in another way? -
Django - allow only one user user/visitor(IP) per view(page)
I would be so grateful if someone could point me in the right direction. Im making a webapp in django where you can move around a webcam. The problem is that maybe 2 or 3 people at once can connect to the website and they all control the camera simultaneously. How could i make the page(view) where you move the camera, accessible to only one user/visitor and limit their time to about 3minutes. After 3 minutes it would cancel the current users session and move on to the next user in the line and so on.. Ideally it would show other users the time they have to wait, till they can control the camera. So.. user1 would be moving the camera(for 3mins), user2 would wait for 3 minutes and user3 would have to wait 6 minutes till his turn. I have tried some stuff with django.contrib.auth but cant get it to work. Anybody? Thanks a lot! -
Getting error 'SMTPSenderRefused at /accounts/password_reset/' when using mailgun sandbox for django in python
I'm trying to send password reset email using mailgun sandbox for django with python (PyCharm app) and I get this error when I try resetting my password. in settings.py, EMAIL_HOST = "smtp.mailgun.org" EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") EMAIL_USE_TLS = True Where I have user and password in as environmental variables. The error I am getting is SMTPSenderRefused at /accounts/password_reset/ (550, b'5.7.1 Relaying denied', 'webmaster@localhost') -
how do I change the date format on selectDate django widget?
I have a date field of a form and I want it to have a format like '21 jan 2020' but I can't find a way to pass it on the selectDate widget class MemoryForm(ModelForm): class Meta: model = Memory fields = ["date"] labels = {"date": ""} widgets = { 'date': SelectDateWidget(attrs={"class": "time", "date_format":'%m/%d/%Y'}), } I've tried others attrs instead of "date_format":'%m/%d/%Y' like "months":'%m' , or "months_field":'%m' but none seemed to work the output was always '21 january 2021' -
API Transition : From GraphQL to REST (with Django)
For my current project (stack = Django + API + Vuejs), up to now I used GraphQL for my API (over Django, with graphene-django). But this library and other linked one (such as the one that handles JWTs) are quite abandoned, with bugs and weird things so to be more confident in the future I decided to switch to the well-known Django DRF. The thing is, I'm now quite used to GraphQL system of queries and mutations, which is (maybe because I'm used to it) quite simple in its design and when it comes to start with DRF, I feel kinda lost. Indeed, I think I understood the easiest way is to use both ModelSerializer and ModelViewSet but... I feel it's hiding lots of things under the hood. Like it has default methods (list(), retrieve(),...). What if I want to controll all this by defining only the necessary ? Moreover, I have really specific needs. For instance, update is not just giving all the arguments, update the model and TADAAA. For specific fields I have to perform specific actions. (e.g.: if a particular field is modified, send a mail,...) Maybe the best way for my use case is to use … -
How do I point to Node in a dockerized Django project using django-pipeline?
I'm trying to add django-pipeline to a dockerized Django 3.1 project. However, when I run collectstatic I receive the following error: pipeline.exceptions.CompressorError: b'/usr/bin/env: \xe2\x80\x98node\xe2\x80\x99: No such file or directory\n' My settings.py file includes: PIPELINE = { 'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'COMPILERS': ('pipeline.compilers.sass.SASSCompiler',), 'YUGLIFY_BINARY': str(BASE_DIR.joinpath('node_modules/.bin', 'yuglify')), 'SASS_BINARY': str(BASE_DIR.joinpath('node_modules/.bin', 'sass')), 'STYLESHEETS': { 'twirlmate': { 'source_filenames': ( 'pages/scss/styles.css', ), 'output_filename': 'css/styles.css', }, }, } And my package.json includes: { ..., "dependencies": { "sass": "^1.32.5", "yuglify": "^2.0.0" } } I have other local Django projects that use pipeline, but not Docker, and they work fine, so I'm wondering if it has to do with Node not being installed in the container? Any thoughts/help is appreciated. -
Uploading files impossible on Heroku with Python?
Heroku doesn't allow you to upload files, they rather you upload them to a cloud storage service such as Amazon s3. But, in order to upload a file to s3 using Python the file needs to be saved as you need the string path...? -
How can i make, flex or grid work with this template in django?
I want my website to display the videos on three columns, i've tried some answers i found online but none of them work. This is the template. this is the css. And this is the result. -
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