Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logic and where to put it?
I am new to Django, but I recently created my first application. I am wondering if I put my logic in the wrong places. From the Django book, I got that logic should but put into the views and data in models. But I have recently read that views should be as small as possible and let models handle the logic. My problem is my views handle all my logic while my models only handle data going to and from my database. Have I messed up when creating this app, and if so, how would I fix it? -
Open PDF Stored in SQL Server Table as type image using Python
We have a table that stores PDFs (and other doc types) in an image datatype field on SQL Server 2014. How can I extract the contents of the field, and display the .pdf in a web browser? It appears as though I need to read the data, write it to a file on the server, then open it, but I am not sure what tool to use. PIL looked good, but the docs state that it can only write to a PDF, not read. Using Django/Python on Ubuntu 14.04. Thank you -
Django Admin CSRF Verification Failed when debug=False
I'm building a Django (1.9.6) app, hosted on Heroku with gunicorn with a Let's Encrypt SSL certificate. When I try to save a model in admin I'm greeted with a Forbidden 403 error, with the message "CSRF verification failed. Request aborted. More information is available with DEBUG=True." If I set debug to True I no longer get the error. My settings.py file has: ALLOWED_HOSTS = ['localhost', '.example.com'] MIDDLEWARE_CLASSES = [ '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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['localhost', '.example.com'] SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True I've tried playing around with different settings including CSRF_COOKIE_DOMAIN and I've cleared my cache and cookies. I've also tried resetting my (PostgrSQL) database but I still can't save models. -
Django JavaScript Translation gettext is not defined
My javascript function contains the following: document.getElementById("example").innerHTML = gettext("This is an example"); My urls.py looks like: urlpatterns = [ url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^admin/', admin.site.urls), url(r'^', include('project.urls')), url(r'^login/$', auth_views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name = 'login'), url(r'^logout/$', auth_views.logout, {'next_page': '/login'}), url(r'^i18n/', include('django.conf.urls.i18n')), ] And in my template I have: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> The translation above using gettext() does not work. A Reference Error comes up saying gettext() is not defined. However, in the same javascript file i have: var monthNames = [gettext("January"), gettext("February"), gettext("March"), gettext("April"), gettext("May"), gettext("June"), gettext("July"), gettext("August"), gettext("September"), gettext("October"), gettext("November"), gettext("December")]; And that does not prompt a reference error. The month translations work but the example one does not. -
Database is storing new information in new rows
In my project I have a user answering 10 questions and giving them a result at the end. Currently, i have created a Django project which asks the questions via radio buttons and stores them in a database then moves the user on to another page to answer the next question. I've just noticed that my database is storing the information like this below Is taking the question which is answered and putting it in 1 - Question1 then moving the user to do the next one which is the inputs into 2- Question2. I would like it only use one column and then store the answers in the next row across eventually being able to set my own ID. How would this be possible? (can show my view/models/forms.py files if needed. -
Bootstrap theme is not loading in django
I am trying to make a layout for a bookstore app... I have installed bootstrap through command line and I am trying to load simplex theme. I am getting this error TemplateSyntaxError at /store/ 'bootstrap_styles' received some positional argument(s) after some keyword argument(s) Also, when I delete that line of code and try to execute it I get error of {% endblock %} this.. TemplateSyntaxError at /store/ Invalid block tag: 'endblock' Here is my base.html {% extends 'bootstrap3/bootstrap3.html' %} {% load staticfiles %} {% load bootstrap3 %} {% load bootstrap_themes %} {% bootstrap_styles theme='simplex' type ='min.css' %} {% block bootstrap3_extra_head %} <link href = "http://fonts.googleapis.com/css?family=Open+Sans:400,300,700" rel = "stylesheet" type="text/css"/> <link href = "{% static 'base/css/style.css' %}" rel = "stylesheet" type="text/css"/> {% endblock %} {% block bootstrap3_title %} {%block title %} Welcome to Pick A Book !! {%endblock %} {% endblock %} { block bootstrap3_content %} <nav class = "navbar navbar-inverse navbar-fixed-top"> <div class = "container"> <div class = "navbar-header"> <button type="button" class ="navbar-toggle" data-toggle="collapse" data-target = "#navbar"> <span class = "icon-bar"> </span> <span class = "icon-bar"> </span> <span class = "icon-bar"> </span> </button> <a href="{% url 'index' %}" class = "navbar-brand"> Pick A Book</a> </div> <div id = "navbar" class … -
{Python} {Django} {UUID} How to create a 8 digit (XXXXXXXX) Unique Id in python?
I am making a web app for practice, it is a job portal. I want to create 8 digit unique IDs for job which will be visible to the end user. Ids can have numbers and alphabets. Pattern needs to be 8 digits without hyphens or dashes like XXXXXXXX. I know there is UUID thing in python. But they seem to generate the id in their specific format. Is there a way to get the id in my required format? If not can someone please guide me on how to go about it? Thanks in advance. -
Form not saving data to database Django
Creating a simple application that takes form input and generates a word document. So far the document is generated fine but I would like this same form data to be saved in database incase needed for future regeneration of a document. views.py def instruction_view(request): model = Instruction form = InstructionForm(request.POST or None) if form.is_valid(): form.save(commit=True) doctype = form.cleaned_data['format'] filename = fill_template( 'odtemp/INSTRUCTIONS.odt', form.cleaned_data, output_format=doctype) visible_filename = 'instructions.{}'.format(doctype) return FileResponse(filename, visible_filename) else: return render(request, 'instructions.html', {'form': form}) models.py class Instruction(models.Model): instructions = CharField(max_length=1000, blank=True, null=True) client = CharField( max_length=1000,blank=True, null=True) order = CharField(max_length=1000, blank=True, null=True) ref = CharField(max_length=1000, blank=True, null=True) telephne = CharField(max_length=1000, blank=True, null=True) -
Understanding django forms and their effects on databases(i.e. how to modify or construct the best forms)
I am relatively new to using python/django to build websites as well we as building website all together so I am trying to understand what I am doing. I am building a website where the main function is an online form in which a user can input data which is then saved to be printed out as a .csv later. The form is an online registration for an event. So what I am currently doing is building a form as such below. from django import forms from .models import Register class RegisterForm(forms.ModelForm): class Meta: model = Register fields = ['name','age','email','birthdate'] labels = {'name': 'Name','age':'Age','email':'Email','birthdate':'Date of Birth'} where the model Register it is pulling from looks like this: from __future__ import unicode_literals from django.db import models class Register(models.Model): """register some text""" name = models.CharField(max_length=200) age = models.CharField(max_length=3) email = models.EmailField(max_length=200) birthdate = models.DateField() def __str__(self): """Return a string representation of the model.""" return self.name where my views.py looks like: def register(request): if request.method != 'POST': form = RegisterForm() else: form = RegisterForm(data=request.POST) if form.is_valid(): write_csv(form) #form.save() return HttpResponseRedirect(reverse('grap_main:index')) context = {'form': form} return render(request, 'grap_main/register.html', context) I have run into problems when trying to add attributes to the Register model and … -
updating user who changed model
I am working on a django project in which I have a model user. I want to get the details of when the user model was created and when was it enabled. Enabling a user can be done by any user after it is created. My user model is something like this: class User(models.Model): employee = models.ForeignKey(Employee) address = models.CharField(max_length=200) created_by = models.CharField(max_length=30, default='', null=False) enabled_by = models.CharField(max_length=40, default='', null=False) My approach on this: def save(self, *args, **kwargs): data = json.loads(serializers.serialize("json", [self, ]))[0] pk = self.pk data["fields"]["id"] = self.id changed = 0 if pk is not None: self.enabled_by = self.created_by.username super(RainPolygon, self).save(*args, **kwargs) But I end up getting both created_by and enabled_by field same. Can someone help me here. Thanks :) -
Invite user signup and add new user to a given object's ManyToManyField
There is a ManyToManyField(User) in my List class. How can one user send invitations to his List objects to others? By others I mean users who are not registered yet. The goal is to send invite and after registration new user is automatically assigned to the above ManyToManyField. Preferably initiations by email. models.py class List(models.Model): name = models.CharField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) items_list = models.ForeignKey(List) def __str__(self): return self.name -
How can I do a for loop for each element received,to execute a queryset in in Django?
I want to run a query set for each id_tipo_unidad received in the GET function maybe it is not clear but I try to explain you. I have this metod in my views: def get (self, request, tipo_venta, minimo, maximo, id_tipo_unidad, format=None): if id_tipo_unidad > '0': unidad = Unidad.objects.filter(id_tipo_unidad=id_tipo_unidad) print("inmuebles"); serializer = UnidadSerializer(unidad, many=True) return Response(serializer.data) This is part of jquery code that send a request to my APIREST $.get(/JSON/+bandera+"&"+min+"&"+max+"&"+extra, function (data) { rest of code } extra send id_tipo_unidad but in some cases this can send multiple id_tipo_unidad. So I want that for each id_tipo_unidad received run this query set: unidad = Unidad.objects.filter(id_tipo_unidad=id_tipo_unidad) print("inmuebles"); serializer = UnidadSerializer(unidad, many=True) return Response(serializer.data) -
Django filter values by two columns
My models.py is: class FormObject(models.Model): pattern = models.TextField(primary_key=False) # TODO: JSONField with postgres db name = models.TextField(default='Test', primary_key=False) description = models.TextField(blank=True, primary_key=False) owner = models.ForeignKey(User) results = models.TextField(blank=True, primary_key=False) # TODO: JSONField # hash which works like link ulink = models.TextField(unique=True, null=False, primary_key=True, default=get_uuid4) form_id = models.IntegerField(default=0, primary_key=False, unique=False) version = models.IntegerField(default=0, primary_key=False) class Meta: unique_together = (('owner', 'form_id', 'version'), ) I'm getting QuerySet using User object user.formobject_set.all() And I want to filter values in following way: version will be max and id will be unique For example, few objects in set (only id and version will be used to filter them): id=1 version=0 id=2 version=0 id=3 version=0 id=3 version=1 id=3 version=2 And result should be id=1 version=0 id=2 version=0 id=3 version=2 -
Multiple messages.error Django
I would like to catch incorrect information using Django messages. I have one message.error that works properly, but when I add more potential messages, they won't work. Here is my code: def order_approve(request): if request.method == 'POST': form = Approved(request.POST or None) success = False if form.is_valid: order = request.POST.get('order') department = request.POST.get('department') name = request.POST.get('name') notes = request.POST.get('notes') check = department if check == 'wrong': #I have a coloumn that is '-----' for placeholding messages.error(request, 'Please select a valid department') else: if department == 'sales': approved = PDFStat.objects.filter(quote_num=order).values_list('sales_approved', flat=True) if approved == True: messages.error(requet, order + ' has already been approved by Sales') else: PDFStat.objects.select_related().filter(quote_num=order).update( sales_name = name, sales_approved = True, sales_date=datetime.today()) HomeTable.objects.filter(quote_num=order).update( last_app = 'Sales') if notes != '': object1 = PDFStat.objects.select_related().filter(quote_num=order) for a in object1: if a.sales_notes == None: PDFStat.objects.select_related().filter(quote_num=order).update( sales_notes = notes) else: a.sales_notes = a.sales_notes + " " + notes a.save() messages.success(request, 'The quote has successfully been approved by ' + name + ' in ' + department) form = Approved() success = True return render(request, 'approved.html', {'form': form}) else: form = Approved() return render(request, 'approved.html', {'form': form}) My first messages.error works fine but when it gets down to the if approved == True regardless … -
how can I build flexible data model in django
I am a beginner using django, I want to build a flexible data model like this:(see the picture) Uses can add new attribute (attr 4, 5..) without changing the database (do not add new columns)data model pic How can I realize it in model, view and form with the function of creating Item and searching items on selected attrs? The main problem confused me is that I cannot link form with model since the attribute is actually values not truly attributes. -
Django child inherited object can't see M2M parent attributes
I have the following models: from django.contrib.sites.models import Site class Entity(models.Model): name = models.CharField('Name', max_length=64) desc = models.TextField('Description',) tags = models.ManyToManyField(Tag,related_name='companies') sites = models.ManyToManyField(Site) class Company(Entity): founded_date = models.DateField(blank=True, null=True, help_text='Enter in YYYY-MM-DD format.') employee_amount = models.IntegerField('Number of Employees',blank=True, null=True) class Employee(models.Model): user = models.OneToOneField(User) entity = models.ForeignKey('companies.Entity', blank=True, null=True) I am trying to save the company for the first time (add) and update (edit). I am doing that in my view with: try: company = Company.objects.get(employee=get_employee(request.user)) form = CompanyForm(request.POST, request.FILES, instance=company) except: form = CompanyForm(request.POST, request.FILES) if form.is_valid(): company = form.save(commit=False) if action == 'add': try: entity = Entity.objects.get(name=company.name) company = entity.company employee.entity = entity employee.save() except: pass company.save() employee.entity = company employee.save() employee.entity.sites.add(current_site) company.save_m2m() When I do this I get the error: 'Company' object has no attribute 'save_m2m' How can this be when the parent "Entity" has this value and the child "Company" should have access to it? -
Django cart is updating sub total on addition of the product but when the product is deleted subtotal is not updating
Cart App models.py from decimal import Decimal from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save, post_save from products.models import Variation # Create your models here. class CartItem(models.Model): cart = models.ForeignKey("Cart") item = models.ForeignKey(Variation) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __unicode__(self): return self.item.title def remove(self): return self.item.remove_from_cart() def cart_item_pre_save_receiver(sender, instance, *args, **kwargs): qty = instance.quantity if qty >= 1: price = instance.item.get_price() line_item_total = Decimal(qty) * Decimal(price) instance.line_item_total = line_item_total pre_save.connect(cart_item_pre_save_receiver, sender=CartItem) def cart_item_post_save_receiver(sender, instance, *args, **kwargs): instance.cart.update_subtotal() post_save.connect(cart_item_post_save_receiver, sender=CartItem) class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) items = models.ManyToManyField(Variation, through=CartItem) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2) def __unicode__(self): return str(self.id) def update_subtotal(self): print "updating..." subtotal = 0 items = self.cartitem_set.all() for item in items: subtotal += item.line_item_total self.subtotal = subtotal self.save() views.py from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404, JsonResponse from django.shortcuts import render, get_object_or_404 from django.views.generic.base import View from django.views.generic.detail import SingleObjectMixin # Create your views here. from products.models import Variation from carts.models import Cart, CartItem class CartView(SingleObjectMixin, View): model = Cart template_name = "carts/view.html" def get_object(self, *args, **kwargs): self.request.session.set_expiry(0) #5 minutes cart_id = self.request.session.get("cart_id") if cart_id == None: cart = … -
Django javascript translation giving error on page load
This is what my urls.py looks like: js_info_dict = { 'domain': 'djangojs', 'packages': ('project',), } urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('project.urls')), url(r'^login/$', auth_views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name = 'login'), url(r'^logout/$', auth_views.logout, {'next_page': '/login'}), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns('', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), ) This is what I have in my html: <script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script> I have run django-admin makemessages -d djangojs -l fr and made my changes to the djangojs.po file. I then ran django-admin compilemessages. I see the the djangojs.mo file. When I go to my site, it is giving me an AttributeError that points to the line of HTML code above. How do I go about fixing this? -
Filtering django DatetimeField__date not working
According to this document that was added on v1.9 we can able to query a DateTimeField by date without time. Examples are: Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1)) But it is not working for me: class MilkStorage(models.Model): .... created_at = models.DateTimeField(null=False) Usage from datetime import date m_list = MilkStorage.objects.filter(created_at__date=date.today()) It returns an empty queryset <QuerySet []>. Does this query only works in PostgreSQL? -
Django forms - displaying fields based on request parameter
i' ve the following django model: class OrderLog(models.Model): order = models.ForeignKey(Order) entry = models.TextField() private = models.BooleanField(default=False) and the related form: class OrderLogForm(forms.ModelForm): class Meta: model = OrderLog fields = ('entry', 'order', 'private') . How can i modify the fields parameter based on the request parameter? So, if the user is testuser, than the fields tuple contains only the first 2 elements, in other cases 3 elements. Can request be accessible somehow from the form itself? Thanks. -
In Django, how to collect user's input?
I have a question about Django. I have two webpages. User input data in the first webpage, and then the second webpage provides the user something that is selected by user's input in the first webpage. My question is how to collect user's input in a view class so that the data can be used by another view class. Thanks. -
NGINX loading default config and not custom confog
I have been following this tutorial on how to set up Nginx, uwsgi and django together. I have reached the part in which I install Nginx and setup a custom config file, and then I do a sudo ln -s ~/home/ubuntu/mysite/nginx.conf /etc/nginx/sites-enabled/ I can verify that the blank nginx.conf file shows up in the sites-enabled folder beside the default config. However, after I stop/start the server it still doesn't load the custom one. How do I go about setting it up to load from the custom config file? -
Is there any way to integrate django-crispy-forms in django admin
Description: I would like to customize the 'admin/change_form.html', instead of use the basic django.contrib.admin view to draw the fields (they only can be grouped by fieldsets, not much more), would be posible to use crispy for that? I mean to define a form layout with tabs, fieldsets, fields per column etc... and draw it inside the change_form.html template in the admin?. Sorry if it's not the right place to ask this question. Versions I'm using Package version: 1.6.1 Django version: 1.10 Python version: 2.7.13 -
Django website gives an importerror for mixins
I have been given a set of files (Django website) that I am supposed to deploy on a local box and 'support'. First off, I have to say that I have only very basic experience with Django (mostly doing the tutorials and building a simple app myself). Secondly, the files come with no requirements.txt or any instructions so I have had to rely on a lot of repetitive trials, which got me to the part that I am able to run the server (python manage.py runserver), after installing the dependencies on which the runserver command would crash (i.e. bootstrap_themes, Pillow and dbbackup). but as soon as I try to access the website I get the following error: Environment: Request Method: GET Request URL: http://ec2-34-252-71-244.eu-west-1.compute.amazonaws.com:8000/ Django Version: 1.8.7 Python Version: 2.7.12 Installed Applications: ['gts.apps.GtsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap_themes', 'dbbackup'] Installed 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 365. for pattern in self.url_patterns: File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns 401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in urlconf_module 395. self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/home/ubuntu/glycoenzymes/GlycoEnzymes/glycoenzymesapp/urls.py" in <module> 22. url(r'^gts/', include('gts.urls' … -
Sending emails with messages dependent on if statements Django
I need to send emails to different to users with different messages depending on the state of if statements in my code. Currently, I am sending emails like this: send_mail( 'Subject', 'Body', 'From', '['To']' ) However, I need a way where I can change the body of the email depending on the way a user navigates the if statements like so: #drop down to select a, b, or c if dropdown == 'a': sendmail( to b,c) if dropdown == 'b': sendmail(to a,c) if dropdown == 'c': sendmail(to a,b) I could make emails in each if statment, but I feel like there is a way that I could have an email template that I could populate depending where the email is being sent from. Thank you for your help!