Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validating model formsets in createview
i really need your help. I have trouble validating a model_formset form. when i post empty values i get the error below. here is the link to my snippet. https://pastebin.com/9u54M5FW # models.py class MilkProduce(models.Model): for_farmer = models.ForeignKey(Farmer, null=True) cow = models.ForeignKey(Cow) amount = models.DecimalField(decimal_places=2, max_digits=9) cycle = models.PositiveIntegerField(default=1) timestamp = models.DateTimeField(default=timezone.now) date = models.DateField(default=timezone.now) def __str__(self): return "Cow Produce" # forms.py class MilkProduceForm(forms.ModelForm): class Meta: model = MilkProduce fields = ('cow', 'amount') widgets = { 'cow': forms.Select(attrs={ 'class': 'ui fluid dropdown search', }) } class BaseMilkProduceFormset(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseMilkProduceFormset, self).__init__(*args, **kwargs) self.queryset = MilkProduce.objects.none() # views.py class CreateMilkProduceView(CreateView): template_name = 'farmers/milproduce_create.html' def get_form(self, form_class=None): extra = int(self.kwargs.get('cows')) MilkProduceFormSet = modelformset_factory( MilkProduce, MilkProduceForm, formset=BaseMilkProduceFormset, extra=extra) return MilkProduceFormSet def get_success_url(self): return reverse('milk:index') I need a way to validate data and if the form is not valid it should return the errors just as the normal forms work. -
How to stream opencv frame with django frame in realtime?
I'm trying to use raspberry pi capture the image from USB camera and stream it with Django framework I have tried to use StreamingHttpResponse to stream the frame from Opencv2. However, it just shows 1 frame and not replacing the image. How can I replace the image in real time? Here is my code. from django.shortcuts import render from django.http import HttpResponse,StreamingHttpResponse import cv2 import time class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(frame) time.sleep(1) def index(request): # response = HttpResponse(gen(VideoCamera()) return StreamingHttpResponse(gen(VideoCamera()),content_type="image/jpeg") -
Do not render blank line where Django template tag is?
Is there a way to not render blank line where django-tempte tag is? For instance the following template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> Will render to such HTML: ## blank line here <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> Is there a way to make it render simply to: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> -
Select only specific field from related object django
I have these two models: class Command(models.Model): client = models.ForeignKey(Client) carrier = models.ForeignKey(Carrier, null=True, blank=True) and class Client(models.Model): name = models.CharField(max_length=10) somme other fields ... I have one object of the Command class let's call it command I want to access to the name of the client of this command I can do : command.client.name But the SQL expression generated is going to retrieve all the fields of the Client models while I only need name I can do that to solve this problem: from client.models import Client name = Client.objects.only("name").get(command=command).name But this is quite long to type, any fast way to do it ? something like command.client.only("name").name ? -
Python putting . before module name while importing
While importing modules in python does it make a difference if we put a "." infront of the module name and does it have an advantage ? Example in django docs : from .models import Question Is it different than from models import Question that one ? -
Filtering out the database for multiple foreign key
Here's my Model class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") How can I filter out the messages between two users? I did something like this, it's giving the messages separately, I couldn't filter out them in one list as we see on social sites. data1 = Message.objects.filter(sender_id=id, receiver_id=request.user.id) data2 = Message.objects.filter(receiver_id=id, sender_id=request.user.id) Please help me with this code. Thanks in advance! -
Is there a simple way to mock many static methods in python/Django?
I'm coming from a Ruby/Rspec world where it is very simple to mock and setup tests/expects() statements to test static methods. I was wondering if there is a simple way to test same things in Python. Please disregard what the code is actually doing (i have changed many names in it) I have the following code: def create_models(pr_dict): facility = FacilityCreator.doit(pr_dict) p = PCreator.doit(facility, pr_dict) pr = PRCreator.doit(p, p.recent, pr_dict) models_affected = {'f': f, 'pr': pr,} return models_affected -
Can't create database with default postgresql docker image
Official site says, that if you wanna build postgresql databse just put varibles POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB. I put them into .env file and write in docker-compose file env_file: ./.env, but then django says: django.db.utils.OperationalError: FATAL: database "languages" does not exist. It means I should write .sql script with commands. Questions: Writing .sql sript is the only way to make it work? How can I write it and where to put it if I don't want explicitly write sensetive info like password, I wanna use .env file as i will store .sql script in public repo? My .env file DEBUG=True SECRET_KEY=... POSTGRESQL_DATABASE=languages POSTGRESQL_USERNAME=admin POSTGRESQL_PASSWORD=pass POSTGRESQL_ADDRESS=postgres POSTGRES_DB=languages My docker-compose file: version: '3' services: web: build: ./web env_file: ./web/microservice/.env volumes: - ./web:/code/ depends_on: - postgres command: python manage.py runserver 0.0.0.0:8000 nginx: build: ./nginx/ ports: - "80:80" - "443:443" volumes: - ./web/static:/code/static depends_on: - web postgres: image: postgres:latest ports: - "5432:5432" env_file: ./web/microservice/.env volumes: - /var/lib/postgresql/data/ My Dockefile: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD ./requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt ADD . /code/ EXPOSE 8000 CMD ["/usr/local/bin/gunicorn", "translation_microservice.wsgi", "-w", "2", "-b", ":8000", "--access-logfile", "-", "--capture-output"] -
render_to_string doesn't render object attributes
I'm trying to render email usi9ng render_to_string but it behaves like context wasn't object. It renders object.__unicode__() itself but not object.id etc. email/text_emails/user/new_reservation.txt {% load i18n %} {% block content %} {% blocktrans %} Dear customer, thank you for your reservation. Reservation information: Reservation location: {{ reservation.location.name }} Reservation ID: {{ reservation.id }} Reservation Object: {{ reservation }} {% endblocktrans %} {% endblock %} shell_plus In [1]: from django.template.loader import render_to_string, get_template In [2]: reservation = Reservation.objects.first() In [3]: reservation.id Out[3]: 3028 In [4]: render_to_string('email/text_emails/user/new_reservation.txt',{'reservation':reservation}) output u'\n\n\n\nDear customer,\n\nthank you for your reservation.\n\nReservation information:\n\nReservation location: \nReservation ID: \nReservation Object: Viede\u0148 Letisko -&gt; Viede\u0148 mesto (2017-09-16 17:51:00)\n\n' As you can see the only thing rendered is {{ reservation }}. Do you know where is the problem? -
How to get a unique modal header for each stock?
I am trying to create a virtual stock market where I have different modals displaying information about each stock. But the template renders as such that I am unable to get a unique modal-header for each stock. Even after clicking on the 'CIPLA' stock I get "Buy HDFC" as the modal header. Here is my django template. {% for stock in user.stocks.all %} <li class="list-group-item"> <b>{{ stock.stock_name }}</b> <p id="curr">Current price : {{ stock.current_price }}</p> Bought at : {{ stock.buy_price }} <button class="btn" id="buy" data-toggle="modal" data-target="#buy-modal">Buy</button> <!--Modal for buy--> <div id="buy-modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Buy {{ stock.stock_name }}</h4> </div> <div class="modal-body"> <form method="post" action="/stocks/{{ user.id }}/{{ stock.stock_name }}/buy/" > {% csrf_token %} <label for="quantity">Quantity</label> <input type="number" id="quantity-buy" name="quantity"> <button class="btn" id="confirm-buy" type="submit" >Buy</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> I have ended it with {% endfor %}. -
I wanna load results.html when I put vote button
I am making a web site by seeing Django tutorial. I wanna load results.html when I put vote button is in detail.html ,but now index.html is loaded.detail.html is {% extends "polls/base.html" %} {% load bootstrap3 %} {% block contents %} <h1>{{ question.question_text }}</h1> <!--{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}--> <form action="{% url 'polls:poll_vote' question.id %}" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Vote" /> </form> {% endblock %} When I put vote button is this code <input type="submit" value="Vote" />, I wanna show results.html . views.py is from django.shortcuts import render from django.urls import reverse_lazy from django.utils.html import mark_safe from .models import Question from django.http import HttpResponse from django.shortcuts import Http404 from django.shortcuts import get_object_or_404,redirect from .models import Choice from django.views.generic import TemplateView from django.views.generic import DetailView from django.views.generic import ListView from .forms import MyForm from .forms import VoteForm from django.views.generic import FormView from django.views.generic.detail import SingleObjectMixin from django.shortcuts import resolve_url from django.contrib import messages # Create your views here. def index(request): return render(request,'polls/index.html',{ 'questions': Question.objects.all(), }) def vote(request,pk): question = get_object_or_404(Question,pk=pk) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError,Choice.DoesNotExist): return render(request,'poll/detail.html',{ 'question':question, 'error_message':"You didn't select a choice", }) else: selected_choice.votes += 1 selected_choice.save() return redirect('index') return … -
How to detect python / django backdoors in Linux server
I have to detect any python / django backdoors on my server, since it's the second time that the system won't boot at all! Are there any utils like chkrootkit, for django related backdoors? This is an emergency! Any help would be apreciated! -
django post_delete() signal handler doesn't work
I am trying to make it so that the 'num_posts' field of a blog object is decremented every time a post belonging to that blog is deleted, and incremented every time a post is created. I was able to implement the overloaded save method easily enough: def save(self, *args, **kwargs): '''After saving a new post, increment the num_posts value in the relevant blog.''' super(Posts, self).save(*args, **kwargs) self.blog_id.num_posts += 1 tmp = self.blog_id tmp.save() But for whatever reason, the logic does not work when deleting a Posts object. I'm following best practices by using signal handlers in a handlers.py file in a signals submodule. I then import the submodule in my ready() method in my TasksConfig(Appconfig) method in apps.py I don't seem to be getting any syntax errors, or any errors at all. The num_posts field on the relevant blog simply fails to decrement. Here is the relevant code: From my handlers.py: from django.db.models.signals import pre_delete from django.dispatch import receiver from webcomics.models import Pages, Posts, Blogs @receiver(pre_delete, sender=Pages) def handle_page_delete(sender, **kwargs): obj = kwargs['instance'] if(obj != None): tmp1 = obj.prev_id tmp2 = obj.next_id if(tmp1 != None): tmp1.next_id = tmp2 obj.prev_id = None if(tmp2 != None): tmp2.prev_id = tmp1 obj.next_id = None … -
Deserialize query string to querydict (sent by AJAX)
I'm sending a Modelform via AJAX (by POST) to a view. There's is no error but the ModelForm saved creates an empty item in my model. I've checked the debugger for request.POST: There is the key as sent corresponding to what was sent by AJAX but it's not a QueryDict but a String of the form: keyinrequestpost = 'csrfmiddlewaretoken=pA.....zutQ&FirstField=BlaBlad&SecondField=BlaBla&ThirdField=BlaBla' Apparently, doing then: MyModelForm(request.POST['newword']) is not working since it's not a QueryDict? I thought the conversion was automatic?? How can I deserialize this to get a QueryDict usable by MyModelForm() ? my AJAX: $(document).ready(function(){ $('#newword_form').bind('submit', function(e){ var newword_form = $('#newword_form') newword_form_serialized = newword_form.serialize(); $.ajax({url: '/create_newword/', type: 'POST', dataType: 'json', data:{csrfmiddlewaretoken: '{{ csrf_token }}', 'newword': newword_form_serialized } , success: function(data){ ... and my view: if 'newword' in request.POST.keys(): # the form has been posted f = MyModelForm(request.POST['newword']) if f.is_valid(): word = f.save() return render(request, ... -
How to use angular 2 with django
I have been learning Django and I can now build simple applications with it. But I really love the appeal of Angular. Right now, I am working on a Django project and I want to use Angular2+ as the front end. My question is, how can I combine the two frameworks? That is, use Django as back end and Angular as frontend. I have searched the internet for help. All I see is how to use AngularJS and Django. I have followed these two tutorials: http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html and https://thinkster.io/django-angularjs-tutorial. What I need is instruction or guide on how to use Django and Angular, not AngularJS as I have never learned AngularJS. I understand a bit of Angular 2 and I know there is a difference between it and AngularJS. I'd be very grateful if anyone could help me on how to use Django and Angular together or direct me to helpful resources. Thank you. -
docker-compose setup not running in ECS
I'm getting exasperated with deploying my nginx/django/redis/postgres setup to ECS. I have a docker-compse setup that is working perfectly in development on my local machine. However, the containers in ECS immediately stop after starting the task. I would be so happy to find out what I'm doing wrong here. I assume it is the nginx config, but don't know. See my setup: Dockerfiles - web FROM alpine # Initialize RUN mkdir -p /data/web WORKDIR /data/web COPY requirements.txt /data/web/ # Setup RUN apk update RUN apk upgrade RUN apk add --update python3 python3-dev postgresql-client postgresql-dev build-base gettext libffi-dev RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt # Clean RUN apk del -r python3-dev postgresql # Prepare COPY . /data/web/ EXPOSE 8000 - nginx FROM nginx RUN apt-get update && apt-get install openssl -y RUN mkdir -p /etc/letsencrypt/archive/mydomain.org/ RUN mkdir -p /etc/letsencrypt/live/mydomain.org/ COPY letsencrypt /etc/letsencrypt/archive/mydomain.org/ RUN ln -s /etc/letsencrypt/archive/mydomain.org/cert1.pem /etc/letsencrypt/live/mydomain.org/cert.pem RUN ln -s /etc/letsencrypt/archive/mydomain.org/chain1.pem /etc/letsencrypt/live/mydomain.org/chain.pem RUN ln -s /etc/letsencrypt/archive/mydomain.org/fullchain1.pem /etc/letsencrypt/live/mydomain.org/fullchain.pem RUN ln -s /etc/letsencrypt/archive/mydomain.org/privkey1.pem /etc/letsencrypt/live/mydomain.org/privkey.pem RUN rm /etc/nginx/conf.d/default.conf COPY conf /etc/nginx/conf.d/ redis and postgres come from offical images. This is my docker-compose.yml file: version: '2' services: web: restart: always build: ./web/ links: - postgres:postgres - redis:redis env_file: - db.env - … -
NoReverseMatch at /polls/ Why does error happen at line 0?
I am making a web site by seeing Django tutorial.I got an error, NoReverseMatch at /polls/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. It was told like Error during template rendering In template /Users/hasuikeyuri/djangostudy/templates/base.html, error at line 0 Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. I really cannot understand why error happens at line 0. base.html(it is in template folder) is {% load staticfiles %} {% load bootstrap3 %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Starter Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <style type="text/css"> body { padding-top: 50px; } </style> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'index' %}">Tutorial</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="{% block nav_polls %}{% endblock %}"><a … -
Can the next page be designated as a self-modal area in the modal−div area?
Inside the template, the login foam zone was mapped inside the modal pill. If normal login is normal, it is normally moved to home.However, if it is not registered or a positor occurs Outside the Modal Div area, mark the foam with respect to the custom form.I would like to call a Page which is remanuded to the Modal Div area in the event of an unregistered user and a photoelectricity. It can be a difficult question because it is a translator. Can I fix this problem? My sauce is below me. Additional posts can be posted if necessary. mysite.urls.py from django.conf.urls import url,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^accounts/',include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) view.py from blog.models import Post from django.views.generic.base import TemplateView from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm from django.core.urlresolvers import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model UserModel = get_user_model() # --TemplateView class HomeView(TemplateView): template_name = 'mysite/home.html' def get_context_data(self, **kwargs): User = get_user_model() context= super(HomeView, self).get_context_data(**kwargs) context['post_like'] = Post.objects.all() return context class AboutView(TemplateView): template_name = 'mysite/about.html' class UserCreateView(CreateView): template_name = 'registration/register.html' form_class = UserCreationForm success_url = reverse_lazy('register_done') class UserCreateDoneTV(TemplateView): template_name = 'registration/register_done.html' class … -
Django foreign key(ManyToMany) field isn't added to DB table
class Organization(models.Model): mLeader = models.ForeignKey(User) mName = models.CharField(max_length=30, default='-') mTel = models.CharField(max_length=15, default='-') mAddress = models.TextField(default='-') mType = models.CharField(max_length=1, default='A') # A : Daycare Center, B : private educational institute, C : Church, D : ... owner = models.ForeignKey('auth.User', related_name='Organization') def __str__(self) : return self.mName class OrganizationLeader(models.Model): #private info mUser = models.ForeignKey(User) owner = models.ForeignKey('auth.User', related_name='Leader') # mName = models.CharField(max_length=30, default='-') class BusLine(models.Model): mOrganization = models.ForeignKey(Organization) mName = models.CharField(max_length=30, default='-') mIsPrivate = models.BooleanField(default=True) mCreated = models.DateTimeField(auto_now_add=True) mIsCycle = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', related_name='lines') class Meta: ordering = ('mCreated', ) class BusStation(models.Model): mName = models.CharField(max_length=30, default='-') mCreated = models.DateTimeField(auto_now_add=True) mOrder = models.IntegerField(default=None) mIsStart = models.BooleanField(default=False) mIsEnd = models.BooleanField(default=False) mBusLine = models.ManyToManyField('BusLine', blank=True, null=True) #변수명이 고정돼있어 접미사 붙이지 않음 mpoint = models.PointField(default=None) objects = models.GeoManager() Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6) Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6) owner = models.ForeignKey('auth.User', related_name='stations') class Meta: ordering = ['mOrder'] class Bus(models.Model): mDriver = models.ForeignKey(User) mDriving = models.BooleanField(default=False) mCurrentStation = models.IntegerField(default=0) mCreated = models.DateTimeField(auto_now_add=True) mName = models.CharField(max_length=100) mBusLine = models.ForeignKey('BusLine', on_delete=models.CASCADE, blank=True, null=True) mArrive = models.BooleanField(default=False) #LSB Data #변수명이 고정돼있어 접미사 붙이지 않음 mpoint = models.PointField(default=None) objects = models.GeoManager() Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6) Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6) owner = models.ForeignKey('auth.User', related_name='buses') def save(self, *args, **kwargs): self.Latitude … -
Django admin - wrong DateTime format
I can't figure out how to change DateTime format in Django admin. I've set all format settings I can and set locale to 'sk-SK' which is Slovakia. We don't use AM/PM at all. settings.py: LANGUAGES = ( ('sk', 'Slovak'), ('en', 'English'), ) LANGUAGE_CODE = 'sk-SK' LOCALE = 'sk-SK' TIME_ZONE = 'Europe/Bratislava' USE_I18N = True USE_L10N = True USE_TZ = False DATE_INPUT_FORMATS = ('%d.%m.%Y',) DATE_FORMAT = 'd.m.Y' TIME_INPUT_FORMATS = ('%H:%M',) TIME_FORMAT = 'H:i' But I still see this in admin: Do you know what to do? -
Django + Celery + Supervisord + Redis error when setting
I am going through the setting of the following components on CentOS server. I get supervisord task to get the web site up and running, but I am blocked on setting the supervisor for celery. It seems that it recognizes the tasks, but when I try to execute the tasks, it won't connect to them. My redis is up and running on port 6380 Django==1.10.3 amqp==1.4.9 billiard==3.3.0.23 celery==3.1.25 kombu==3.0.37 pytz==2016.10 my celeryd.ini [program:celeryd] command=/root/myproject/myprojectenv/bin/celery worker -A mb --loglevel=INFO environment=PATH="/root/myproject/myprojectenv/bin/",VIRTUAL_ENV="/root/myproject/myprojectenv",PYTHONPATH="/root/myproject/myprojectenv/lib/python2.7:/root/myproject/myprojectenv/lib/python2.7/site-packages" directory=/home/.../myapp/ user=nobody numprocs=1 stdout_logfile=/home/.../myapp/log_celery/worker.log sterr_logfile=/home/.../myapp/log_celery/worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 1200 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq(redis) is supervised, it will start first. priority=1000 The process starts and when I go to the project folder and do: >python manage.py celery status celery@ssd-1v: OK 1 node online. When I open the log file of celery I see that the tasks are loaded. [tasks] . … -
custom template tag with multiple arguments
I want to format a date in the future based on a time delta: from django import template from datetime import datetime, timedelta, time register = template.Library() @register.simple_tag def tomorrow(format): tommorow = datetime.now() + timedelta(days=1) return tommorow.strftime(format) def dayfuture(dday, format): dayfuture = datetime.now() + timedelta(days=dday) return dayfuture.strftime(format) This works: {% tomorrow "%A, %d %b, %Y" %} But I've had no luck with dayfuture Also, is it possible to have multiple custom template tags in the same file. I've had no luck registering a second one. I'm using django 1.11 pythone 3.4 -
django1.11 TypeError: context must be a dict rather than RequestContext
my code:` enter code heredef contact(request): if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): message = '感谢您的来信。' user_name = form.cleaned_data['user_name'] user_city = form.cleaned_data['user_city'] user_school = form.cleaned_data['user_school'] user_email = form.cleaned_data['user_email'] user_message = form.cleaned_data['user_message'] ctx = { 'user_name':user_name, 'user_city':user_city, 'user_school':user_school, 'user_email':user_email, 'user_message':user_message, } else: message = "请检查您输入的信息是否正确" else: form = forms.ContactForm() template = get_template('contact.html') request_context = RequestContext(request.POST) request_context.push(locals()) html = template.render(dict(request_context)) return HttpResponse(html) But it has some mistakes because of the Django version: TypeError: context must be a dict rather than RequestContext. How can I modify my code to handle this error(my english is poor,sorry) -
Dividing a SplitArrayField in Django template
in my Django form I´m using a SplitArrayField to create a matrix of integers and it works like a charm when getting all the values and processing them. class SimplexForm(Form): CHOICES = [('Maximizar', 'Maximizar'), ('Minimizar', 'Minimizar')] tipo = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(), label="Tipo de función") def __init__(self, *args, **kwargs): variables = kwargs.pop('variables') restricciones = kwargs.pop('restricciones') super(SimplexForm, self).__init__(*args, **kwargs) self.fields["funcion"] = SplitArrayField(forms.IntegerField(),size=variables, label="Función objetivo") self.fields["restricciones"] = SplitArrayField(SplitArrayField(forms.IntegerField(),size=variables+1,label="Restriccion"),size=restricciones,label="Restricciones") My problem is that when the fields are rendered all of them are displayed in a line. I´ve already tried this way but without results: <div class="fieldWrapper"> {{ formulario.restricciones.errors }} <label for="{{ formulario.restricciones.id_for_label }}">Restricciones:</label> {% for campo in formulario.restricciones %} <p> {{ campo }} </p> {% endfor %} </div> This is how it´s currently displayed: SplitArrayField in browser So is there a way I can split that train of fields with Django template? Thanks in advance. -
django.core.exceptions.validationerror '' value must be a decimal number
I have a Decimal Field in my model : models.py from django.db import models from django.utils import timezone from datetime import datetime from decimal import Decimal class Simulation(models.Model): projectAmount = models.DecimalField(max_digits=19, decimal_places=2, verbose_name='Amount', blank=True, default=Decimal(0), ) This field is filled with an html form (forms.py was not right for me in this project) and this views.py views.py from django.shortcuts import get_object_or_404, render from decimal import Decimal from .models import Simulation def simulation_create(request): if request.method == 'POST': projectAmount = request.POST.get('projectAmount', '0.00') Simulation.objects.create( projectAmount = projectAmount ) When submitting the form with an empty value, I got this error : django.core.exceptions.ValidationError: ['Value must be a decimal number'] I was expecting my default value to prevent this kind of error. Any idea how can I make this thing right ? Thanks