Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting message part of serialized._errors when defining a unique constraint for REST
Based on this post, I put a uniqueness constraint on my serializer like this: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(validators=[ UniqueValidator( queryset = User.objects.all(), message=_('Such email is already registered in the system'), )] ) class Meta: model = User fields = ('username', 'password', 'email', ) And in the views.py, I have: def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): #.... else: return Response({'success': False, 'detail': serialized._errors, 'object': None}, status=status.HTTP_400_BAD_REQUEST) Now, the problem is that through my entire API, I use a standardized structure of json response, and in the detail part, third-party developers always expect a string with error message. However, serialized._errors returns dict: {'email': [u'Such email is already registered in the system']}, and the issue lies in that I need pure string with error message. I know I could use serialized._errors['email'][0], but the question is, does python/Django provide any magic generic syntax which I could use instead of serialized._errors to extract the string message in case of arbitrary dict field name, so that the code looks like this: return Response({'success': False, 'detail': MAGIC_OPERATOR, 'object': None}, status=status.HTTP_400_BAD_REQUEST) -
Form validation fails in Django
I am trying to implement a form in Django, but the validation always fails! here's the code! my views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Description from django.http import Http404 from .forms import DForm # Create your views here. def index(request): context = {} return render(request, 'front/index.html', context) def bill(request): try: billinfo = Description.objects.all() context = {'billinfo': billinfo} except Description.DoesNotExist: raise Http404("No Bills") return render(request, 'front/bill.html', context) def commitvalues(request): if request.method == "POST": form = DForm(request.POST) if form.is_valid(): Description = form.save() return HttpResponse("Hello;You're at the front index.Commit's done!") return HttpResponse("Validation Failed") models.py: from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db import models @python_2_unicode_compatible class Description(models.Model): desc = models.CharField(max_length = 200,default = "Suits") bill = models.CharField(max_length = 200) length = models.CharField(max_length = 200) quality = models.CharField( max_length=200,default = "custom") rate = models.CharField(max_length = 200) def __str__(self): return self.desc forms.py from django import forms from .models import Description class DForm(forms.ModelForm): class Meta: model = Description fields = ('desc','bill','length','quality','rate') here's the index.html template <form action ="{% url 'front:commit' %}" method = "post" > {% csrf_token %} <label for="name">Name</label> <input type="text" name="name" id="name" value="name"><br> <label for="Bill">BILL</label> <input type="text" name="bill" id="bill" value="bill"><br> <label for="length">Length</label> <input type="text" name="length" id="length" … -
Add header in *.docx word file using python
I have a question: How do add header (and footer) in *.docx file? I use library python-docx in my django project. But it really can't add header. I found solution on stack (July 2012) with using 'win32com', but nowadays it don't work for me. Help me advice. Thank you. Have a nice day. -
Automate uploading files in django admin
I have a database model that in the Django model all I need to do is upload an image file to a new database record. Is there anyway I can automate this as I have a lot of images to upload? All help is appreciated. Thanks -
Django TypeError: Model instances without primary key value are unhashable
I have my models.py as follows: class Article(models.Model): date = models.DateTimeField(null=True, blank=True) title = models.TextField(default=None, null=True, blank=True) content = models.TextField(default=None, null=True, blank=True) author = models.TextField(default=None, null=True, blank=True) url = models.CharField(max_length=255, default=None, null=True, blank=True, unique=True) class Keyword(models.Model): word = models.CharField(max_length=80) def __str__(self): return self.word article = models.ForeignKey(Article, related_name='keywords_found', null=True, blank=True) I encounter an error when I try to save the data like this: Article.objects.create(date=publish_date, title=article.title, content=article.text, author=article.authors, url=url, keywords_found=keywords_found) Here, keywords_found is a list of Keyword objects. The error is: TypeError: Model instances without primary key value are unhashable Where am I going wrong? Django version : 1.10 -
Simplified/PHP alike django application deployment
what this is about I am looking for a possibility to simplify the deployment of django applications on my server. Currently I am using one uWSGI instance per application. I do not want to mess around with configuration files whenever I uploaded a new project to my www-root-folder. Instead I am looking for a more php alike solution, where I can upload a project folder to my www-root and have it available through nginx-> uWSGI or nginx-> Gunicorn "automatically". current state For that I have found, that uWSGI's emperor mode for django applications in combination with magic variables may work. But with my configuration only settings from one django application gets and stays loaded, so that no other can start. from uwsgi.conf.template: [uwsgi] master = true socket = :8000 master = true reuse-port = true reload-os-env = true vaccuum = true logto = /var/log/uwsgi-%n.log manage-script-name = true chdir = /usr/local/www/%n mount = /%n=%n/wsgi.py from nginx.conf: location ~ ^/(.+)/(.+?)$ { include uwsgi_params; uwsgi_pass 10.0.0.106:8000; uwsgi_param UWSGI_SCRIPT $1.wsgi; uwsgi_param SCRIPT_NAME /$1; uwsgi_param UWSGI_CHDIR /usr/local/www/$1; uwsgi_param PATH_INFO "/$2"; # strip path } location ~ ^/(.+)/$ { include uwsgi_params; uwsgi_pass 10.0.0.106:8000; uwsgi_param UWSGI_SCRIPT $1.wsgi; uwsgi_param SCRIPT_NAME $1; # uwsgi_param UWSGI_APPID /$1; uwsgi_param DJANGO_SETTINGS_MODULE $1.settings; … -
Dedicated web service for web app (Python/Django)
Let's assume that I want to create a simple todo list web application. I am thinking about creating RESTful web services which will be used my the web application and which will be providing all functionalities concerning managing todo list and tasks. I have two concerns: Is there a sense in creating dedicated web service assuming web service will be only used by my web application? Web service and web application will be on the same server and there have to be a lot of 'views' duplication. Web application will only delegate request to web service, process the response, and return a web page. Assuming I decided for this kind of architecture: dedicated web service + web application, what is the best practice for calling web service from views in web application? They will be just two different apps within Django project. request? -
Why doesn't "python" command work in virtualenv?
Before asking, I should mention that this is NOT a problem or a bug, this is just a question to widen my knowledge. When I was working on a Django project (I'm quite new to all these things so don't beat, please) I activated my virtualenv, installed django module and started a new Django project by using django-admin.py startproject myproject . That worked. But then I cd to myproject and tried to run python manage.py startapp firstapp, and failed. I caught ImportError: no module named 'django'. The problem was solved by simply typing ./manage.py startapp firstapp . What the heck is that? Why doesn't python command work? Python version is 3.5.2. -
Django migration discovery - get migrations from a different directory
Lets say i have the same django project (multi-tenant project) in different code version, version a and newer version b. version b has some new migrations. I'm currently running version a on my production environment and want only to migrate the DB to the new version (the migrations are as such that it won't cause problems for version a to run correctly). so up until now, i would clone the repository with the new version b and run on it manage.py migrate and all is well. The problem is that now, version a can make new tenants (which means new schemas). - each new schema runs the migrations of the current version so in potential, there is a situation where a schema is created with the migrations of version a although version b ran its migrations and the DB is one step ahead. Looking for: I would like to have a configuration so that the command migrate_schemas of the manage.py of version a will migrate against the code base of version b. Is this possible? Tech stuff Django 1.8 django-tenants 1.1.7 python 2.7.6 Thanks! -
Unable to update a user in SQLite3 with Django
I have a view which is supposed to apply modification to a user. This is my view.py: @login_required def edit_user_info(request): user = request.user print user.summary for key in request.POST: if key != "csrfmiddlewaretoken": user.__dict__[key] = request.POST.get(key, '') print user.summary user.save() print "saved" return HttpResponseRedirect('../home/') The two prints show me that the field change correctly and that the user is saved correctly. But When I call the user back it's the old value that still present. What I'm doing wrong? -
django- Quiz app,how to keep track of all user's selected choice
The registered user, selects the choice for the question. I need to save the selected choice by each user class Question(models.Model): question_text = models.CharField(null = False,max_length= 200) class Status(models.Model): User = models.ForeignKey(User) question = models.ForeignKey(Question) #red not answered,yellow ans but doubt,answered green status = ( ('Red','Red'), ('Yellow','Yellow'), ('Green','Green'), ) #Question not answer first so red Qstatus = models.CharField(max_length=6,choices=status,default='Red') #when user goes to previous question,the selected choice is highlighted selected = models.IntegerField(default=-1) When a Question object is created: How to populate every user in Status model,with the newly created question or the the vice-versa Example I have 5 question.when i am adding a new user the status model should link all questions to the user OR When a new question is added ,the status model should link all the users with the question https://github.com/garrykevin-ep/codewars -
what is the best way to map/plan out a Django project API with Angular2?
i am in the process of setting up my website and i needed help with the structure and the planning of it. I will be using Django REST and Angular... suggestions are welcome! thanks. -
How to override clean method using related field attribute?
There is Order and Invoice models in my app. Order has attribute approved. When admin set approved=True in Django-admin, customer is notified that they can pay the order (Invoice). The problem is that Invoice has attribute final_price which has to be set by admin before admin can approve the order. In Django-admin, there is Invoice object inlined into Order object. I want to allow admin to set final_price attribute and set approved order at once. So I've overriden the clean(self) method of Order. def clean(self): if self.approved and not self.invoice.final_price: raise ValidationError(_("Invoice final price has to be set on approved order!")) The problem is that if Admin sets Invoice.final_price and Order.approved at once, the clean method raises ValidationError because it doesn't know that Invoice is about to be changed. Do you have any suggestions how to solve this problem? -
Controlling the frequency of Django signals
I have tried post_save signal in Django. My table will get multiple tables suddenly. As expected multiple signals are sent in this case. How can I reduce the number of signals to one in a time interval? Basically, I want to put some constraint on the frequency of signals sent. -
I do not know why I get an error (Django)
from django.db import models class Tests(models.Model): x1 = models.CharField(max_length=30) x2 = models.CharField(max_length=30) (Python) I do not know why I get an error... please help me.. -
Django signals - customize
I want to use signals to notify the user about changes in the database. post_save signals help me to do this. Now I want to control additional arguments passed to the receiver based on some conditions. Also, I want the signal to be sent only depending on some conditions. How will I do this? One obvious answer is to signal a function and send the actual signal from this function. Is there a better way? Something like overriding the function that is sending the signal? -
django-tenant-schemas & avatars
Multi tenant django 1.8 setup (using django-tenants schemas) requirements.txt: Django==1.8.16 django-allauth==0.27.0 django-tenant-schemas==1.6.4 django-avatar==3.1.0 ... Keeping the tenants as much as possible isolated, so kept only these APPs shared (note that allauth is not here, each tenant has its own auth_user table): SHARED_APPS = ( 'tenant_schemas', # mandatory 'customers', 'django.contrib.contenttypes', ) Serving avatars (from /media URL) is posing an issue now since the avatar URL is unaware of the tenants. Avatars are served from /media/avatars/<user ID>/userx-pic.jpg but to avoid clashes it should take the tenants into account. Target is to have: /media/avatars/<tenant>/<user ID>/userx-pic.jpg How can this be configured? I am thinking of using RedirectView (https://docs.djangoproject.com/en/1.10/ref/class-based-views/base/#redirectview) ... but the avatars also need to be stored in the correct location. So the question is twofold: How to get the avatars in the correct -tenant aware- location? How to serve them correctly? -
Django webapp 500 server error after running migrations
So I ran python manage.py migrate after making some code changes, and I end up getting a 500 server error when I run the app. I tried reverting the migration files but that didn't work, and when I try to run migrate again it tells me that there are No migrations to apply. Any general suggestions? -
Create Multiple Custom User Models in Django
I want to Create a user registration and auth project that with have multiple level auth...1) Admin 2) Staff 3) Students... any idea how to go about it? as far as i know i can create only one custom user model. -
Using Java code in Django
I have written a Java server application which internally uses Hadoop. The server has been tested by making get,put and post requests. Now I need to develop a proper website for this application. Django seems to be a good choice of framework for my requirements. But I cannot figure out how I would use Java code(the application logic) with Django. Googling on this topic did not help much. It would be great if someone could help me figure this out or point me to the right resources. -
Trying to import app django-audiotracks
I'm new to Django, GitHub page here says "Edit settings.py and add audiotracks to your list of INSTALLED_APPS. Then synchronize your database with:" $ python manage.py syncdb I added 'audiotracks', to INSTALLED_APPS in settings.py then ran syncd, which returned "unknown command" so I tried: $ python manage.py migrate which returned "no migrations to apply." Next step on GitHub page says, "Edit your ROOT_URLCONF and add a piece of code similar to:" urlpatterns += patterns('', # Here we mount the app under /music. Feel free to use something else url("^music", include("audiotracks.urls")), # Some URLs require a Django username url("^(?P<username>[\w\._-]+)/music", include("audiotracks.urls")), ) In settings.py: ROOT_URLCONF = 'mysite.urls' Which means that code should go into mysite/urls.py correct? When I do that and migrate I get "NameError: name 'patterns' is not defined" I'm not sure where the issue lies, any input is appreciated. -
serializing objects in a django app
I have a django app, let's call it example_app. Inside example_app I have a file called my_class.py which defines the MyClass objects. I would like to be able to save an instance of MyClass to file and load it, as needed, in example_app/views.py using the view get_results. To do this, I initially used pickle. When I run the django application I receive the following error: Internal Server Error: /get_results/ Traceback (most recent call last): File "//anaconda/envs/example_project/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "//anaconda/envs/example_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "//anaconda/envs/example_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jkarimi91/Projects/example_project/example_app/views.py", line 16, in get_results s = pickle.load(f) File "//anaconda/envs/example_project/lib/python2.7/pickle.py", line 1384, in load return Unpickler(file).load() File "//anaconda/envs/example_project/lib/python2.7/pickle.py", line 864, in load dispatch[key](self) File "//anaconda/envs/example_project/lib/python2.7/pickle.py", line 1096, in load_global klass = self.find_class(module, name) File "//anaconda/envs/example_project/lib/python2.7/pickle.py", line 1130, in find_class __import__(module) ImportError: No module named my_class I came to the conclusion that the error must be due to the fact that pickle serializes classes by reference. As a result, pickle requires that the class be defined in the top-level of a module. It seemed sloppy to move my_class.py to the project root directory. Instead, I opted … -
Retrieving new value from django form field without submitting
I have a web app that allows users to choose from multiple subscription levels. I am using Stripe to implement payment. In the user's account view, I allow them to change their subscription. Code is as follows: {% extends '_layouts/base.html' %} {% block content %} {% if user.is_authenticated %} <h1>Your Account</h1> <form action="/accounts/create_subscription" method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <script Stripe checkout script... data-description={{form.plan_type.value}} ... </script> </form> {% else %} {% endif %} {% endblock %} One of the form fields is a ChoiceField where the user can select from different plans. I want to populate the data-description field in the Stripe Script with the new value the user has selected from the plan_type field. Unfortunately as it stands, form.plan_type.value always yields the ChoiceField's initial value as opposed to the updated value. How can I get the new value the user has selected without submitting the form? -
Why do an extra set of double quotes get put on this template insertion?
I wrote this get_context_data method for an update view: def get_context_data(self, **kwargs): context = super(MyAccountEdit, self).get_context_data(**kwargs) context.update({ 'form_title': 'Edit My Account', 'form_attributes': 'method="post"', 'form_button_label': 'Save' }) return context So I create/update three context variables. However, when I view this in a browser, the form appears like this: <form method=""post""> Because of the additional quotes, the form uses get, rather than post, since it interprets that line as an empty string after method=. After I changed this line in my code: 'form_attributes': 'method="post"', to this: 'form_attributes': 'method=post', It appears to fix the HTML to how I would expect it to render: <form method="post"> So, the question: why does the template tag insertion work this way? What am I misunderstanding? I also tried escaping the quotes and using double-quotes on the outside. Here is the relevant part of my template: <form {{ form_attributes }}> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form.as_p }} <button class="button-primary" type="submit">{{ form_button_label }}</button> </form> -
Bind data to a form in template or view
I have created a form as: class KeyForm(ModelForm): class Meta: model = Key fields = ['name', 'access_level', 'permission'] And here is the view to render the form: def key(request): template = 'keys.html' user = request.user key = get_object_or_404(Key, user=user) if key.access_level == "0": owners = Key.objects.filter(access_level = "0") ownersFormSet = formset_factory(KeyForm) context = { 'owners': owners, 'ownersFormSet': ownersFormSet, } return render(request, template, context) I want to bind the data from the 'owners' queryset to the 'ownersFormSet'. I am iterating over 'owners' in the template so can I bind the form data in each iteration in the template?