Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF verification failed. Request aborted. in ajax request and X-editable
I have following JQuery ajax call with X-editable, $(function() { $.fn.editable.defaults.mode = 'inline'; $.fn.editable.defaults.ajaxOptions = { type: "PUT", beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', '{{ csrf_token }}'); xhr.setRequestHeader('csrfmiddlewaretoken', '{{ csrf_token }}'); } }; $('#content').editable({ type: 'textarea', title: 'Enter Content', url: '/coach/profile/', pk:1, params: { 'csrfmiddlewaretoken': '{{ csrf_token }}' } }); }); When I edit and submit it throwing error as Django CSRF verification failed. Request aborted. Any one know why it is not allowing even after adding header and csrf token in request params -
Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`
I'm trying to extend the django.contrib.auth.models.User model. Currently, the model that is referenced in the exception looks like this: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) dob = models.DateField() def __str__(self): return self.user.username And my serializer class looks like this: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') I don't see where the serializer is getting UserProfile or why this exception is happening: AttributeError: Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `UserProfile` instance. Original exception text was: 'UserProfile' object has no attribute 'username'. -
How to capture output from Python smtp debug server
I'm trying to write unittests for some custom Django email backends, and to test it against a "real" smtp server, I'm trying to use Python's built-in smtpd debugging server by running: python -m smtpd -n -c DebuggingServer localhost:1025 My unittest basically looks like: class Tests(TestCase): @override_settings(EMAIL_BACKEND='mycustombackend') @override_settings(EMAIL_HOST='localhost') @override_settings(EMAIL_PORT='1025') def test_backend(self): from django.core import mail mail.send_mail( subject='Subject here', message='Here is the message.', from_email='from@example.com', recipient_list=['to@example.com'], fail_silently=False, ) and when I run this, the smtpd process outputs the email content correctly. However, when I try and capture that so I can confirm it in my unittest, I get nothing. I've tried using the subprocess package, to launch the process and read the output via pipes, but it never receives any output. I thought I was using subprocess incorrectly, so as a last resort, I tried launching the process with: python -m smtpd -n -c DebuggingServer localhost:1025 > /tmp/smtpd.log and reading the log file. However, even with that, no output is ever written to the file. What's going on here? -
Updating an ManyToMany field with Django rest
I'm trying to set up this API so I can use a "PUT" to update one/many "TAG"s on an item in the model "MOVIE". Tags is an M2M on MOVIE. I am posting on the PK of the item in movie. My httpie work (returns a 200OK) but nothing gets created. When I post the whole JSON (using fetch) it just creates the TAG but no M2M relationship on MOVIE (link). httpie http -f PUT http://localhost:8000/api/Edit/3/ tag:='{"name": "TEST"}' Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) class Movie(models.Model): title = models.CharField("Whats happening?", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) Serializers.py class TagSerializer(serializers.ModelSerializer): taglevel = filters.CharFilter(taglevel="taglevel") class Meta: model = Tag fields = ('name', 'taglevel', 'id') class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) class Meta: model = Movie ordering = ('-created',) fields = ('title', 'pk', 'tag') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.create(**tag_data) movie.tag.add(tag) return movie -
Trouble installing pillow for
Having issues installing Pillow for python djgango. I am using Windows 10, Python 3.6. When I run pip install pillow==3.3.0. ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting My question is how do I properly install its dependency(zlib)? I cant find any documentation on how to successfully install it in Windows. -
how do I set up a image upload to a folder that the folder name is a value of another field in the model in DJango
I have a model with some fields: class RankStructure(models.Model): RankID = models.CharField(max_length=4) SName = models.CharField(max_length=5) Name = models.CharField(max_length=125) LongName = models.CharField(max_length=512) GENRE_CHOICES = ( ('TOS', 'TOS'), ('TMP', 'TMP'), ('TNG', 'TNG'), ('DS9', 'DS9'), ('VOY', 'VOY'), ('KTM', 'KTM') ) Genre = models.CharField(max_length=3, choices=GENRE_CHOICES) image = models.FileField(upload_to='RANKS/'+<<GENRE>>+'/', blank=True) In the last line is an image FileField. I want the folder to be associated with the Genre. So if the Genra is TOS, then the folder should be RANKS/TOS/image.jpg. How do I set it so this happens? Thanks. -
Django - passing parameters to GET method when using JS window.open() function
I Have the following JS script which opens a new window and renders a Django template corresponding to /my_url/. function draw_comparing_graphs() { window.open('/my_url/', '_blank', 'location=yes,height=570,width=1500,scrollbars=yes,status=yes'); } Now, the question is, how do I pass on parameters to Django ? I mean, what is the equivalent of $.post('/my_url/', data) -
Django Internal Server 500 Error AWS Elastic-Beanstalk issue
How do I fix the Django Internal Server 500 error on an AWS eb deployed application? Do I need to change my allowed hosts in my base.py file to have the ip address of the ec2 in elasticbeanstalk? # SECURITY WARNING: keep the secret key used in production secret! # Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.auth', 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) ... STATIC_URL = '/static/' ALLOWED_HOSTS = [] ... -
Django choices and dictionary
I have code JOBS = 1 CATEGORY_CHOICES = ((JOBS, "Jobs"),) And code in the model category = models.IntegerField(choices=CATEGORY_CHOICES, default=JOBS) Instead of "jobs" I want to add a dictionary and have access to it in the template. For example JOBS = 1 CATEGORY_CHOICES = ((JOBS, {'title':"Jobs",'icon':"fa fa-briefcase",'slug':"jobs"}),) But instead I get the following How to add the dictionary into the choices? -
How to implement multiple inlines in a FormView like in django admin
I´m newbie with django, I'm trying to replicate the inlines in the Django admin for adding related models to my Foto Model, it has three foreign keys to different models, I found this code http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/ but it is something different of what i want, because the foreign keys, in my case, are relations from Foto to other three models. I want to create a Form with all the fields from associated models. My models.py is: class Foto(models.Model): fotoID = models.AutoField(primary_key=True) imgfile = models.ImageField(upload_to='fotos/',null=True, blank=True) camara = models.ForeignKey(Camara, null=True) punto_muestreo = models.ForeignKey(PuntosMuestreo, null=True) colector = models.ForeignKey(Colectores, null=True) fecha = models.DateField(blank=True, null=True) def __str__(self): return str(self.filename) class Colectores(models.Model): colectorID = models.AutoField(primary_key=True) name = models.CharField(max_length=510, null=True) institution = models.CharField(max_length=510, null=True) e-mail= models.CharField(max_length=255, null=True) def __unicode__(self): return unicode(self.nombre) class PuntosMuestreo(models.Model): puntoID = models.AutoField(primary_key=True) nombre = models.CharField(max_length=255) latitud = models.FloatField(blank=True, null=True) longitud = models.FloatField(blank=True, null=True) datum = models.CharField(max_length=50, blank=True, null=True) elevacionMinima = models.IntegerField(null=True, blank=True) elevacionMaxima = models.IntegerField(null=True, blank=True) class Camara(models.Model): camaraID = models.AutoField(primary_key=True) modelo = models.CharField(max_length=510, null=True) cantidad_fotos = models.IntegerField(null=True, blank=True) archivo_inicial = models.CharField(max_length=255, null=True, blank=True) archivo_final = models.CharField(max_length=255, null=True, blank=True) In my views.py I only got an inline for PuntosMuestreo form but with inlineformset_factory can´t include Camara and Colectores inline forms, only get camara … -
Problems getting Django project to run in mod_wsgi
I am having some issues getting a django project of mine to be properly served via mod_wsgi. This is the first time I have tried something like this so please forgive any noob mistakes. The error I am currently getting is as follows: [Wed Oct 19 16:24:23 2016] [error] [client 140.225.0.153] mod_wsgi (pid=20418): Exception occurred processing WSGI script '/opt/badgr/code/apps/mainsite/wsgi.py'. [Wed Oct 19 16:24:23 2016] [error] [client 140.225.0.153] Traceback (most recent call last): [Wed Oct 19 16:24:23 2016] [error] [client 140.225.0.153] File "/opt/badgr/code/apps/mainsite/wsgi.py", line 14, in <module> [Wed Oct 19 16:24:23 2016] [error] [client 140.225.0.153] from django.core.wsgi import get_wsgi_application [Wed Oct 19 16:24:23 2016] [error] [client 140.225.0.153] ImportError: No module named wsgi The main project directory is here: /opt/badgr/ The project has its own virtualenv located here: /opt/badgr/env/lib/python2.7/site-packages My wsgi.py file: """ WSGI config for badgr project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainsite.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I also have a django.conf file located in /etc/httpd/conf.d/: Alias /static /opt/badgr/code/staticfiles <Directory /opt/badgr/code/staticfiles> </Directory> <Directory /opt/badgr/code/apps/mainsite/> <Files wsgi.py> </Files> </Directory> WSGISocketPrefix /var/run/wsgi/wsgi WSGIDaemonProcess badgr python-path=/opt/badgr:/opt/badgr/env/lib/python2.7/site-packages/ WSGIProcessGroup badgr WSGIScriptAlias / /opt/badgr/code/apps/mainsite/wsgi.py As far … -
Django ImportError No module named x.settings
I have the following structure: mysite -> manage.py -> mysite (again) -> __init__.py -> wsgi.py -> settings.py etc -> myapp -> __init__.py -> myscript.py -> models.py etc When I run a script from myapp (that does myapp-related things, putting stuff in a the database for example) i need to do import django django.setup() in order to be able to from models import MyModel. But if i do this in the myapp directory, I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\django\__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named mysite.settings Which I kind of understand since it's further up the directory tree and not in the same directory as e.g manage.py (the root I guess?). When I issue a python interpreter in mysite where manage.py is located, I dont get this error. What should I do to be able to place my scripts in myapp and still be able to use django.setup() from that dir? -
Deploying a Django app with Nginx + Uwsgi
So I am kinda new to uwsgi + nginx and I am trying build a docker container for a django app using nginx + uwsgi. The problem that I am experiencing is that I cannot get the nginx + uwsgi part to work. What I have in my uwsgi.ini file is: [uwsgi] wsgi-file = /path to/wsgi.py chdir = /new folder pythonpath = /var/www socket = :8000 And my conf file for nginx looks like this: server { listen 8000; server_name 192.168.99.100; #because of docker container charset utf-8; client_max_body_size 75M; location / { uwsgi_pass django; include /pathto/uwsgi_params; } } I saw I have to create a socket to link both of them, but every time I create a socket and replace :8000 in the uwsgi.ini file the container of the app simply exits. How am I actually supposed to tell uwsgi and nginx to work together? Furthermore, uwsgi seems to not load any apps, eventhough I read almost every single topic on the internet that I could find and did everything that was written... -
Removing null=True from Django model CharField are values updated to empty string
I have a error being thrown: coercing to Unicode: need string or buffer, NoneType found which I believe to be related to the null=True in many of my CharField's throughout my various models. I ran into this error when attempting to add Django Rest Framework Parsers to a ListAPIView like so: class TestList(generics.ListAPIView): """ """ def post(self, request, *args, **kwargs): return None queryset = Tests.objects.all() serializer_class = TestSerializer filter_class = TestFilter parser_classes = (FormParser, MultiPartParser) class Courses(models.Model): created = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=200, unique=True) test = models.ForeignKey('Tests', blank=True, null=True, on_delete=models.CASCADE) class Tests(models.Model): name = models.CharField(max_length=200) it's either getting upset because of the null=True on the CharField's or perhaps because of the test foreign key I'm not totally sure? Would removing null=True and migrating solve this issue? Additionally, I should probably remove the null=True on CharField's anyway, would that be updated retroactively in the database? -
Django rest framework serialize ForeignKey field to list
I have 3 models: Study, Author and StudyAuthor class Study(models.Model): id = models.TextField(primary_key=True) class Author(models.Model): name = models.TextField(primary_key=True) class StudyAuthor(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='studies') study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='authors') class Meta: unique_together = ("author", "study",) And a StudySerializer class StudySerializer(serializers.ModelSerializer): class Meta: model = Study fields = ('authors',) With this setup a list of authors' primary keys are returned from StudyAuthor table. The question is how to get a list of names related to a study from the Author table. Output should be: {"authors": ["author1", "author2", "author3"]} not {"authors": [1, 2, 3]} Here's what I tried: I added this line authors = serializers.SlugRelatedField(many=True, read_only=True, slug_field='author') to the StudySerializer class, but then I got a TypeError saying <Author: Author object> is not JSON serializable -
Django get related objects ManyToMany relationships
i have two models: class CartToys(models.Model): name = models.CharField(max_length=350) quantity = models.IntegerField() class Cart(models.Model): cart_item = models.ManyToManyField(CartToys) i want to get all related toys to this cart. how can i do this -
Django missing change history
I just upgraded to Django 1.10, and now all of my admin's links to /admin/app/model/id/change/history are broken. I can't find a reference to this feature being removed in any of the release docs. Where did this feature go? -
How to dynamically change Django model without triggering migration?
I'm using a Django PyPI package, but I'm dynamically changing some of its model's help_text attributes by doing: from schedule.models import Event models.Event._meta.get_field('end_recurring_period').help_text = 'some better help text' to make the admin more user-friendly. However, after upgrading to Django 1.9, Django now bizarrely interprets this change as a schema change and refuses to migrate any other apps until I generate and run a migration to somehow "apply" this change to my database. Even worse, if I do generate the migration, it writes the migration into my virtualenv's dist-package directory, so it won't be captured by source control. How do I customize model help text without Django erroneously thinking I'm making schema changes? -
Django file upload does not work fine
models.py: class File(models.Model): name = models.CharField(verbose_name="File name", max_length=200, blank=True, null=True) file = models.FileField(upload_to='files/%Y/%m/%d') upload_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, related_name="uploader", blank=True, null=True) def __str__(self): return str(self.name) views.py: class FileView(APIView): parser_classes = [FileUploadParser, MultiPartParser] serializer_class = FileSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] # @method_decorator(csrf_exempt) def post(self, request, format=None): serializer = FileSerializer(data=request.FILES) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) Anythings works fine, but when uploads file images are damaged! Where I make mistake? -
Attribute error for PersonalInfoForm
I'm a little confused why is 'clickjacking middleware` trowing Attribute Error on my form. I'm making a simple application for collecting labor or user information, and I'm facing a small problem, can someone please help me and clarify what is wrong in this code Dpaste from my Traceback, this is my view class PersonalInfoView(FormView): """TODO: CreateView for PersonalInfoForm return: TODO """ template_name = 'apply_to/apply_now.html' form_class = PersonalInfoForm success_url = 'success/' def get(self, form, *args, **kwargs): """TODO: define get request return: TODO """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) return self.render_to_response( self.get_context_data(form=form)) def post(self, form, *args, **kwargs): """TODO: Post request for PersonalInfoForm return: TODO """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_class(form) def form_valid(self, form, *args, **kwargs): """TODO: Validate form return: TODO """ self.object = form.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, *args, **kwargs): """TODO: handle invalid form request return: TODO """ return self.render_to_response( self.get_context_data(form=form)) -
Database used for prefetch_related is not the same that the base query
I'm using a multi-db in my Django app, but to avoid replicacion lag problems the router always uses default database except few places where I set DB manually. I'm facing an issue as I don't know how to specify the database used for prefetch_related. For example I want the next query to use only read_replica DB, but it does 2 queries, the first goes to read_replica as expected and the second goes to default DB. user = UserProfile.objects.using('read_replica').prefetch_related('usermedia_set').get(id=user_id) This are the output of this query: SELECT @@SQL_AUTO_IS_NULL; args=None SELECT VERSION(); args=None SELECT ... FROM ftmanager_userprofile WHERE (ftmanager_userprofile.id = 33); args=(33,) SELECT @@SQL_AUTO_IS_NULL; args=None SELECT VERSION(); args=None SELECT ... FROM ftmanager_usermedia WHERE ftmanager_usermedia.user_id IN (33); args=(33,) -
Non-model object in templates, why __call__() change the behavior?
Today I faced a strange issue on one of my development. I reproduced it with a very minimal example. Have a look at these 2 dummy classes (non Django model subclasses): class DummyClassA(object): def __init__(self, name): self.name = name def __repr__(self): return 'Dummy1 object called ' + self.name class DummyClassB(object): """Same as ClassA, with the __call__ method added""" def __init__(self, name): self.name = name def __repr__(self): return 'Dummy2 object called ' + self.name def __call__(self, *args, **kwargs): return "bar" They are identical, but the second have a special __call__() method. I want to display instances of these 2 objects in a view using the builtin Django template engine: class MyView(TemplateView): template_name = 'myapp/home.html' def get_context_data(self, **kwargs): ctx = super(MyView, self).get_context_data(**kwargs) list1 = [ DummyClassA(name="John"), DummyClassA(name="Jack"), ] list2 = [ DummyClassB(name="Albert"), DummyClassB(name="Elmer"), ] ctx.update({ 'list1': list1, 'list2': list2, }) return ctx and the corresponding template: <h1>Objects repr</h1> <ul> {% for element in list1 %} <li>{{ element }}</li> {% endfor %} </ul> <ul> {% for element in list2 %} <li>{{ element }}</li> {% endfor %} </ul> <h1>Access members</h1> <ul> {% for element in list1 %} <li>{{ element.name }}</li> {% endfor %} </ul> <ul> {% for element in list2 %} <li>{{ element.name }}</li> … -
Django strip_tags template filter add space
I use djangos template filter striptags. Example: >>> from django.utils.html import strip_tags >>> strip_tags("<p>This is a paragraph.</p><p>This is another paragraph.</p>") 'This is a paragraph.This is another paragraph.' What is the best way to add a space character between the paragraphs, so that I get this string instead: 'This is a paragraph. This is another paragraph.' -
Materializecss with django cms for a website
I am using materializecss framework to create navigation in djangocms. I am unable to get the functionality so the dropdown and collapsible work correctly. Right now dropdown only shows one sub-menu, while collapsible wasn't working so I have put that on hold. Following is my menu.html code: {% load i18n menu_tags cache %} {% for child in children %} <li class="child{% if child.selected %} active{% endif %} {% if child.children %} dropdown{% endif %}"> {% if child.children %} <a href="#" class="dropdown-button" data-activates="dropdown3">{{ child.get_menu_title }} <i class="material-icons right">arrow_drop_down</i></a> <ul class="dropdown-content"> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% else %} <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }}</a> {% endif %} </li> {% if class and forloop.last and not forloop.parentloop %}{% endif %} {% endfor %} And following is my base.html call on menu.html: <ul id="dropdown3" class="dropdown-content"> {% show_sub_menu 1 %} </ul> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo">Logo</a> <ul class="right hide-on-med-and-down"> {% show_menu 0 100 100 100 "menu.html" %} </ul> </div> </nav> -
User login in django using sqlalchemy
I am trying to make a login page using sqlalchemy in django. I was able to authenticate it by making a custom backend. However when i do, login(request, user) I get, 'User' object has no attribute '_meta' This is my model, _meta = MetaData(bind=engine) # Create your models here. class User(Base): __tablename__ =Table("person", _meta, autoload=True) id=Column(Integer, primary_key=True) first_name = Column(String(50)) last_name = Column(String(50)) coachName = Column(String(50)) username= Column(String,unique=True) password = Column(String(128)) salt = Column(String(10)) is_active = Column(Boolean, unique=False, default=True) date_joined = Column(DateTime(timezone=True), default=func.now()) #growth_area=relationship("Person_growth_areas", backref="Sessions") def is_authenticated(self): return True def is_anonymous(self): return False def check_password(self, raw_password): #TODO: Make this auto update using # check_passwords setter argument #return self.password==raw_password return check_password(raw_password, self.password) def set_password(self, password): if not self.salt: self.salt = ''.join(choice(ascii_lowercase) for i in range(10)) self.password = make_password(password,salt=self.salt) def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) def save(self): save() Also, save does not work. I have specified user.backend ,but the error remains.