Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API backend versioning approach
We are using django rest framework for creation of apis(which are being consumed by mobile devices). We get the version from request.version in each requested views. All these apis are being used in scenario where requirement changes a lot over time. All the view internally call utils methods(in utils.py). What is the best approach to manage the utils code as per version changes? If we assume number of version changes have been let say around 50.. that many number of if else would look very dirty ? Also how to handle versioning cases if above utils methods are used across more than one django apps. Any django package which solves use cases ? -
Django: Exception as "No module named engine"
django version =1.7.7 degug toolbar install from pip install -e git+https://github.com/django-debug-toolbar/django-debug-toolbar.git#egg=django-debug-toolbar Followed prerequisites from the url : https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#prerequisites After everything set up I keep getting an error as : django.core.exceptions.ImproperlyConfigured: Error importing debug panel debug_toolbar.panels.templates: "No module named engine" Couldn't get around on how to proceed.Can any one help with this exception???Thanks -
Django Rest Framework upload multiply images at once with serializer
I had some research on web for this problem on DRF. When one image is in post DRF works great. But when 3 or 5 images are in one post there is problem that Django save only first image from POST query and others are not saved in database. The question is how to properly handle multiply images upload in one post. Description Django version 1.10 Rest framework version 3.4.6 Python version 3.5 Here is my code what I was trying to do: models class UserModel(AbstractEmailUser): first_name = models.CharField(max_length=30, db_index=True) last_name = models.CharField(max_length=50, db_index=True) details = JSONField(null=True, blank=True, db_index=True) avatar = models.ImageField(blank=True, null=True, upload_to='avatar') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) class UserImages(models.Model): image = models.ImageField(upload_to='images', db_index=True) user = models.ForeignKey('UserModel',related_name='user') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.user) Here in models I have related field from User to UserImages. For purpose on POST query from postman I manual add ID from user to handle FK. serializer class SerializerUserImages(serializers.ModelSerializer): class Meta: model = UserImages def create(self, validated_data): imgs = UserImages.objects.create(**validated_data) return imgs Maybe here I must do some for loop to accomplish save method for multiply images. views class UploadImages(APIView): authentication_classes = (JSONWebTokenAuthentication,) @parser_classes((FormParser, MultiPartParser, FileUploadParser)) … -
Python HMAC hashed value encoding to base64
I am trying to make a twitter auth with the help of django middleware, where I calculate the signature of a request like this (https://dev.twitter.com/oauth/overview/creating-signatures): key = b"MY_KEY&" raw_init = "POST" + "&" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='') raw_params = <some_params> raw_params = quote(raw_params, safe='') #byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'" raw_final = bytes(raw_init + "&" + raw_params, encoding='utf-8') hashed = hmac.new(key, raw_final, sha1) request.raw_final = hashed # here are my problems: I need a base64 encoded string, but get the error "'bytes' object has no attribute 'encode'" request.auth_header = hashed.digest().encode("base64").rstrip('\n') As you can see, there is no way to base64 encode a 'bytes' object. The proposed solution was here: Implementaion HMAC-SHA1 in python -
Serve static files for django on cherrypy
I'm trying to move my Django app from using the development server to a cherrypy server. I've managed to configure it to serve the HTML, however I can't manage to get it to server my static files. My django settings.py for static looks like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(BASE_DIR, 'static'), ) Here is my current start_server function for cherry py: def start_server(options): """ Start CherryPy server """ if options['daemonize'] and options['server_user'] and options['server_group']: #ensure the that the daemon runs as specified user change_uid_gid(options['server_user'], options['server_group']) from cherrypy.wsgiserver import CherryPyWSGIServer as Server, WSGIPathInfoDispatcher from django.core.handlers.wsgi import WSGIHandler server = Server( (options['host'], int(options['port'])), WSGIHandler(), int(options['threads']), options['server_name'] ) if options['ssl_certificate'] and options['ssl_private_key']: server.ssl_certificate = options['ssl_certificate'] server.ssl_private_key = options['ssl_private_key'] try: server.start() except KeyboardInterrupt: server.stop() Any help would be appreciated, thanks very much. -
Django ArrayField gives me syntax error at or near
I was implementing ArrayField, but if I do from django.utils.translation import ugettext_lazy as _ * * exceptions = ArrayField(models.CharField(max_length=200), _('Exceptions'), default=list, help_text=exceptions_help_text) I got this error: django.db.utils.ProgrammingError: syntax error at or near "Exceptions" LINE 1: ..._mymodel" ALTER COLUMN "exceptions" TYPE varchar(200)[Exceptions... Is this a bug? If not how can I set the field name? -
Extract zipFile from zipFile in memory
I've been looking for a topic like this in the internet and didn't find anything. I have a zipfile that contains: zipfile: index.txt zipfile zipfile zipfile ... I'm trying to extract it in memory using the .open method, but I obtain ZipExtFile types of object. I need the extracted object to be ZipFile objects, is there any way I can extract directly the zipfiles objects to memory or transform the zipextfiles to zipfiles without losing any of its properties? Thanks! -
How can I read the status (checked or not) of radio buttons in django template
How can I read the status (checked or not) of radio buttons in django template. Kindly note that I want to read the status in template itself so that I can display remaining content of template as per the user chosen the choice using radio button. context to the template row_list is like this: here row_list context is like this: col1 col2 row1 "001" "XML" row2 "002" "HTML" row3 "003" "DHTML" {% for a in row_list %} <p> {% if forloop.counter < 2 %} <input type="radio" name="items" id="choice" value= {{a.col1}} checked /> {% else %} <input type="radio" name="instances" id="choice" value ={{a.col1}} /> {% endif%} {{a.col2}} </p> {% endfor %} ==== Required to display here the status of radio button checked value(a.col1) using percentage bracket and html code.===== for example like this: {% for r in row_list %} {%ifequal r.col1 rb_status %} Subject: {%endifequal%} {%endfor%} -
Shopify app: adding a new shipping address via webhook
I'm planning to create a simple app using Django/Python that shows a nice button when installed by the store owner on user's account. Clicking on that button should trigger a webhook request to our servers that would send back the generated shipping address for the user. My questions: Is it possible to create such button through shopify API or this something the store owner must manually add? Is it possible to add a shipping address upon user request? Thanks -
TemplateSyntaxError at /cart/, Invalid block tag: '"cart:cart_remove"', expected 'endwith'
I'm doing the webshop following the code in the book "Django by Example". I tried Google and searches in Stackoverflow but I did not find answers to this problem. The product list page and the product detail page work fine but when I try to add items to the cart, the browser says: TemplateSyntaxError at /cart/, Invalid block tag: '"cart:cart_remove"', expected 'endwith'. Here is a screenshot of a part of the error page: error page code lines, maybe the picture is more clear. Here you can also see the code of the error page: 23 {% with product=item.product %} 24 <tr> 25 <td> 26 <a href="{{ product.get_absolute_url }}"> 27 <img src="{% if product.image %}{{ product.image.url 28 }}{% else %}{% static "img/no_image.png" %}{% endif %}"> 29 </a> 30 </td> 31 <td>{{ product.name }}</td> 32 <td>{{ item.quantity }}</td> 33 <td><a href=" {% "cart:cart_remove" product.id %} ">Remove</a></td> 34 <td class="num">${{ item.price }}</td> 35 <td class="num">${{ item.total_price }}</td> 36 </tr> 37 {% endwith %} I checked the code. As you can see below, I have the endwith tag so I don't understand why it gives me that kind of an error. Pycharm was complaining about the " so I changed it to ' for … -
Aggregate to a lower resolution django
Suppose I have the following model: class Snapshot(models): start_time = models.IntegerField() # Timestamp value = models.FloatField() I would like to get a mean of my value field for each past 7 days as a list [0.75, 1, 4.5, 3.2, 1.2, 1.6, 4.8] in the most djangoish way. (I can do that using for loop and unreadable code but simple would be better.) -
How to make a custom Django api
I made a simple Django website which supports user authentication(login/Logoff) and Registration I want to make a custom API which does this using REST how would i do this -
Django - Multiple Download
How to download more than one image at the same time in django using this code: wrapper = FileWrapper(open(filepath)) # img.file returns full path to the image content_type = mimetypes.guess_type(filepath)[0] # Use mimetypes to get file type response = HttpResponse(wrapper,content_type=content_type) response['Content-Length'] = os.path.getsize(filepath) response['Content-Disposition'] = "attachment; filename=%s" % img_name #get filename=filename in models return response -
import django cms as app into existing django project
Hi I have already an existing project into django, now I want to use django cms for dynamic web pages and to gain many more functionality, but not able to find anywhere, how could I use django cms project as app into my django project. can anybody help me out, thanks. -
Merge Login and Signup into one view in django
Merging login/signup view into one view, say LoginSignupView because I have login, signup form in one template. I refered https://gist.github.com/jamesbrobb/748c47f46b9bd224b07fbut think that it doesn't work (Actually I don't know how it works) My views.py : from django.views.generic.base import ContextMixin, TemplateResponseMixin from django.views.generic.edit import ProcessFormView from django.http.response import HttpResponseRedirect, HttpResponseForbidden from django.contrib.auth.forms import AuthenticationForm from users.forms import MyUserCreationForm class MultiFormMixin(ContextMixin): form_classes = {} prefixes = {} success_urls = {} grouped_forms = {} initial = {} prefix = None success_url = None def get_form_classes(self): return self.form_classes def get_forms(self, form_classes, form_names=None, bind_all=False): return dict([(key, self._create_form(key, klass, (form_names and key in form_names) or bind_all)) \ for key, klass in form_classes.items()]) def get_form_kwargs(self, form_name, bind_form=False): kwargs = {} kwargs.update({'initial':self.get_initial(form_name)}) kwargs.update({'prefix':self.get_prefix(form_name)}) if bind_form: kwargs.update(self._bind_form_data()) return kwargs def forms_valid(self, forms, form_name): form_valid_method = '%s_form_valid' % form_name if hasattr(self, form_valid_method): return getattr(self, form_valid_method)(forms[form_name]) else: return HttpResponseRedirect(self.get_success_url(form_name)) def forms_invalid(self, forms): return self.render_to_response(self.get_context_data(forms=forms)) def get_initial(self, form_name): initial_method = 'get_%s_initial' % form_name if hasattr(self, initial_method): return getattr(self, initial_method)() else: return self.initial.copy() def get_prefix(self, form_name): return self.prefixes.get(form_name, self.prefix) def get_success_url(self, form_name=None): return self.success_urls.get(form_name, self.success_url) def _create_form(self, form_name, klass, bind_form): form_kwargs = self.get_form_kwargs(form_name, bind_form) form_create_method = 'create_%s_form' % form_name if hasattr(self, form_create_method): form = getattr(self, form_create_method)(**form_kwargs) else: form = klass(**form_kwargs) return form def … -
Django multi select widget on Galaxy tablet
I've built a site using Django 1.9, and I have a section which uses the multiselect widget. This works perfectly on different browsers and different operating systems (shows me which items I have already selected and which others are available for selection, and allows me to add/remove just fine). However, when I load the same page on my tablet (Samsung Galaxy Tab S2), it only shows the following. It does this both with Chrome and the browser that's just called "Internet". In this specific example, both boxes should show multiple items. I'm not even sure where to begin looking for the problem. The widget code? Something about the tablet itself? Could it be a Javascript issue? Any guidance would be immensely appreciated. -
Saving Django FileFields by default as private to AWS S3
I want all user uploaded files to be private when saved with a FileField in a Django model. I want to save the files to a S3 bucket. From a lot of googling and reading SO QA this is what I've come up with: Create a file s3utils.py and in there place: PrivateS3BotoStorage = lambda: S3BotoStorage( location='uploads' acl='private', querystring_auth=True, querystring_expire=600, # 10 minutes, try to ensure people won't/can't share ) My settings file will then contain: DEFAULT_FILE_STORAGE = 'myproject.s3utils.PrivateS3BotoStorage' I've seen other methods where you create a new type of FileField and set the default_acl to 'private' on initiation, but the method above seems simpler. Lastly, I'm hosting through Heroku so I prefer if authenticated users can download their own file directly from the S3 bucket. To achieve that I'll just place model_instance.file_field_name.url in the Django template. My question is, is this method secure that their files won't be publicly available somehow? Are there better methods to achieve this? In this case, do I still need to set MEDIA_URL Another method I've seen you'll define the FileField in the model and give it the storage to use, so I could use this: class MyModel(models.Model): my_private_file = models.FileField(storage=PrivateS3BotoStorage()) But since I … -
Django session variable not being saved when set using AJAX
I am using database-backed sessions for my project. I am trying to update the value of a session variable via an AJAX post request using AngularJS: app.factory('SomeFactory', ['$http', 'djangoUrl', function ($http, djangoUrl) { return { getSomeDataAndUpdateSessionVar: function () { return $http({ method: 'POST', url: djangoUrl.reverse('some_app:list'), data: { param1: "param1" } }) }, } } ]); Here is the simplified post method of my View: class DocumentListView(JsonRequestResponseMixin, View): def post(self, request, *args, **kwargs): request_data = json.loads(request.body) data_to_be_fetched = request.session.get("data_to_be_fetched", None) if not data_to_be_fetched: data_to_be_fetched = fetch_data(request_data) request.session["data_to_be_fetched"] = data_to_be_fetched print request.session.get("data_to_be_fetched") # This will return the updated value return HttpResponse(json.dumps(data_to_be_fetched), content_type="application/json") It seems like the session variable is not being saved because if I call the above method again, the value of data_to_be_fetched will still be None. The weird thing is that after calling the method for the second time, the new value of session variable will finally be saved (data_to_be_fetched will not be None anymore when fetched after saving it for the second time). Why is it behaving like that? It only happens when setting the session variable during AJAX requests. I tried adding the following after updating the session variable, but the behavior is still the same: request.session.modified = … -
How to display a many to many related objects in Django?
In the model below A has a recursive many to many field. So if A has two records 'a' and 'b'. and if 'a' is related to '1','2' and 'b' has '3'. How do I display that in the Template such that the output is, a: 1,2 b: 3 class A(models.Model): name = models.CharField(max_length=32) as = models.ManyToManyField('self', blank=True) -
How can I register customized user model in Django admin site?
I customized my own user model: from django.contrib.auth.models import AbstractUser from django.db import models GENDER_CHOICES = ( ('M', '남'), ('F', '여'), ) class ChachaUser(AbstractUser): birth = models.DateField(null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M') REQUIRED_FIELDS = ['email', ] And I made admin.py : from django.contrib import admin from users.models import ChachaUser admin.site.register(ChachaUser) And do python manage.py makemigrations and python manage.py migrate. It doens't occur any error. But Admin site doesn't show any User model infos : Did I make any mistake? Need helps. -
Django UpdateView forms
I have a form class that looks like.. #forms.py class ExampleForm(forms.Form): color = forms.CharField(max_length=25) description = forms.CharField(widget=forms.Textarea, max_lenght=2500) and my view looks like this.. #views.py class EditExample(UpdateView): model = Example fields = ['color', 'description'] template_name = 'example.html' def get_success_url(self): pass Template: #example.html {% for field in form %} {% if field.errors %} <div class="control-group error"> <label class="control-label">{{ field.label }}</label> <div class="controls">{{ field }} <span class="help-inline"> {% for error in field.errors %}{{ error }}{% endfor %} </span> </div> </div> {% else %} <div class="control-group"> <label class="control-label">{{ field.label }}</label> <div class="controls">{{ field }} {% if field.help_text %} <p class="help-inline"><small>{{ field.help_text }}</small></p> {% endif %} </div> {% endif %} {% endfor %} When the template is rendered, all the fields show up and populate correctly but the 'description' doesn't show up in a Textarea but rather in a normal field. Im assuming this is because UpdateView works off of 'model = something' rather than 'form = something'. I have tried.. #views.py class EditExample(UpdateView): model = Example form_class = Exampleform template_name = 'example.html' def get_success_url(self): pass but I get a Django error saying "init() got an unexpected keyword argument 'instance'. Is there any way to successfully get the Description to render in a Textarea … -
Why does using .latest() on an empty Django queryset return...nothing?
Here's some code that builds a queryset, and prints the output at each step (for debugging): qs = self.get_queryset(True) print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>] qs = qs.get_user(user) print(qs) # [] qs = qs.completed() print(qs) # [] qs = qs.latest('time_completed') print(qs) # <-- What happened? Why is this blank? print("nothing") if not qs else print("something") # <-- blank?!?! how?! print(type(qs)) # The last operation qs.latest('time_completed') prints blank, the type is blank, the if statement is ignored. What's going on here? An example where the result is NOT an empty queryset works fine (note all items are a single user, just coincidence): qs = self.get_queryset(True) print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>] qs = qs.get_user(user) print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>] qs = qs.completed() print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>] qs = qs.latest('time_completed') print(qs) # obj_1 print("nothing") if not qs else print("something") # something print(type(qs)) # <class 'my_app.models.MyModel'> -
Avoid reloading data needed for multiple django views
I'd like to make a view which uses a template. The template includes several images (plots), each of which are created by other view functions. The plots are based on some data which is loaded as a function of some post variables. As implemented now, the view function associated with each plot in the page has to reload all the data, which is slow. I'd like to only load the data 1 time (when the "parent" view for the page is run) and somehow communicate this data to the other view functions (get it into all the "child" plots/images). Is this possible? I realize I could store the data in a global variable, but that has some significant drawbacks. -
Django: pass request.user as extra argument to model save
After many attempts, Googling, etc., I am looking for an example/nudge in right direction on how to pass the request.user from a ModelForm as an extra argument to a models.py custom save(). The models.py "overriden" save (which came from this SO answer) is here: models.py: ... def save(self, *args, **kwargs): new_meeting = False if not self.id: new_meeting = True super(Meeting, self).save(*args, **kwargs) end = self.start + datetime.timedelta(minutes=119) if new_meeting: event = Event( start=self.start, end=end, title='{0} meeting'.format(self.entity.name), description=self.agenda, ) event.save() er = EventRelation.objects.create_relation(event, self) er.save() cal = Calendar.objects.get(name='civic') cal.events.add(event) else: event = Event.objects.get_for_object(self)[0] event.start = self.start event.end = end event.title = '{0} meeting'.format(self.entity.name) event.description = self.agenda event.save() ... forms.py: ... class MeetingCreateViewForm(forms.ModelForm): class Meta: model = Meeting fields = '__all__' def save(self, creator, *args, **kwargs): f = super(MeetingCreateViewForm, self).save(creator, *args, **kwargs) return f ... views.py: ... class MeetingCreateView(LoginRequiredMixin, CreateView): model = Meeting form_class = MeetingCreateViewForm def form_valid(self, form): form.save(creator=self.request.user) return super(MeetingCreateView, self).form_valid(form) ... I'm currently getting: Traceback: File "/Users/foobaz/.virtualenvs/test_root1_9/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/Users/foobaz/.virtualenvs/test_root1_9/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/foobaz/.virtualenvs/test_root1_9/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/foobaz/.virtualenvs/test_root1_9/lib/python2.7/site-packages/braces/views/_access.py" in dispatch 102. request, *args, **kwargs) File "/Users/foobaz/.virtualenvs/test_root1_9/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, … -
How to set empty value to DateField in django model?
What am I doing wrong here? I need to set empty value to doing_field. def delete_todo_today(request): if request.is_ajax() and request.POST and request.user.is_authenticated: thingtodo = ThingToDo.objects.filter(author = request.user, thing = request.POST.get('item')) thingtodo.doing_date = None thingtodo.save() data = {'message': "%s 's doing_date deleted" % request.POST.get('item')} return HttpResponse(json.dumps(data), content_type='application/json') else: raise Http404