Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to clean up input data in a Django view to avoid CSRF?
Lets say, in a view, I use input data to create an instance of a Model in my Django project. def create_post(request, message): post = Post.objects.create(message=message) post.save() Now, the problem is, the 'message' is coming from sources which may be unsavory, that is, a plugin that makes AJAX requests to my API. If it was a django form, I could have just used {% csrf_token %} and cleared the issue, but, I want to do this in my view. How do I do this? Note, please don't suggest adding csrf protection in my Javscript code, because that will not work for my case. Thanks! -
Django - how to work in live/dev environments and upgrade live?
I was wondering how i should work in Live/Dev environments in django and how to update the app. Currently I just edit the live version and if i break it i fix it. but the app is reaching a point where its not feasible to do this anymore. So i was wondering how best to do things? do i keep a copy locally on my machine and edit that then upload files? or should i package it and upgrade it once it has no bugs? (if the latter how do i create an upgrade package? Thanks for any advice -
django admin, set choice field length?
im trying to set the ChoiceField length in my django form, I used the below: from django.forms import TextInput, Textarea, ChoiceField class SiteAdmin(admin.ModelAdmin): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'25'})}, models.ChoiceField: {'widget': TextInput(attrs={'size':'25'})}, models.GenericIPAddressField: {'widget': TextInput(attrs={'size':'25'})}, } ... and then got the error: File "/var/www/infternal/sites/admin.py", line 18, in SiteAdmin models.ChoiceField: {'widget': TextInput(attrs={'size':'25'})}, AttributeError: 'module' object has no attribute 'ChoiceField' Does anyone know what i need to alter to change the select/dropdown length? Thanks -
Django, Javascript: Can't upload image from other PCs
Here is a strange one. Although, when I login from my PC I can upload an image (using my client's credentials), when others login from their PCs they can't upload images. I am not talking about application hosted on my PC. I am talking about the one that is on the production server. So, we both use the exact same code. It is important to note that I get no error or warning message in my log files. The form I am using is something like this: <form method="post" action="{% url 'add_recipe' %}" enctype="multipart/form-data"> {% csrf_token %} <div id="file_upload-drop" class="uk-file-upload" style="background-image: url('/media/{{ recipe.featured }}'); background-repeat: no-repeat; background-position: center;"> <p class="uk-text">Drag an image</p> <p class="uk-text-muted uk-text-small uk-margin-small-bottom">ή</p> <a class="uk-form-file md-btn">Please, select an image to upload<input id="file_upload-select" name="image" type="file"></a> </div> <div id="file_upload-progressbar" class="uk-progress uk-hidden"> <div class="uk-progress-bar" style="width:0">0%</div> </div> as you can see there is a progress bar just underneath the image upload. and the views.py is like this: if request.method == "POST": image = request.FILES.get("image") and this is the models.py from sorl.thumbnail import ImageField class FoodRecipe(models.Model): featured = ImageField(upload_to='recipe', default=None, blank=True) The progress bar has a javascript code like this: var progressbar = $("#file_upload-progressbar"), bar = progressbar.find('.uk-progress-bar'), settings = { action: '/media/recipe', … -
django formset: it is always trying to create when the form is updated
I have been Googling around for this question for quite long. And sadly no luck. Indeed I found questions like SO question and SO question. I would say I found myself having a very similar question to the first one. However, I do not understand the discussions under that question. So first of all, to make it clear, I did not even get formset.is_valid() to return True--that is the problem. There are indeed uniqueness check but my edit should be able to pass that check in the database level. And here comes my code: ### models.py class DataAccess(models.Model): user = models.ForeignKey(User, models.CASCADE) project_data = models.ForeignKey(ProjectData, models.CASCADE) role = models.CharField( max_length=2, choices=ROLES, default='N' ) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = (('user', 'project_data', 'role'),) # query from project data should happen more index_together = [['project_data', 'user', 'role']] def __str__(self): return '{}&{}&{}'.format(self.user, self.project_data, self.role) def save(self, *args, **kwargs): curr = datetime.now() if not self.created_at: self.created_at = curr self.updated_at = curr return super(DataAccess, self).save(*args, **kwargs) class DataSyncPath(models.Model): server = models.ForeignKey(Server, models.CASCADE) project_data = models.ForeignKey(ProjectData, models.CASCADE) path = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = (('server', 'project_data',),) index_together = [['project_data', 'server']] def __str__(self): return '{}&{}'.format(self.server, self.project_data) def … -
python3.5 Error installing Django1.9.6: syntax error
when i call server.apache error log.I try to solve.but i I have failed.Hope everybody to help me.Thank you very much. Traceback (most recent call last): File "/var/www/DjangoBlog/weblog/config/wsgi.py", line 19, in <module> from django.core.wsgi import get_wsgi_application File "/usr/local/python3/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/usr/local/python3/lib/python3.5/site-packages/django/utils/version.py", line 7, in <module> from django.utils.lru_cache import lru_cache File "/usr/local/python3/lib/python3.5/site-packages/django/utils/lru_cache.py", line 28 fasttypes = {int, str, frozenset, type(None)}, ^ SyntaxError: invalid syntax this is my python version. python -V Python 3.5.1 this is my http conf Listen 81 WSGIPythonPath /usr/local/python3/lib/python3.5/site-packages <VirtualHost *:81> WSGIScriptAlias / /var/www/DjangoBlog/weblog/config/wsgi.py ErrorLog logs/domain.com-error_log DirectoryIndex index.html Alias /static/ /var/www/DjangoBlog/weblog/static/ <Directory /var/www/DjangoBlog/weblog/static> Order allow,deny Allow from all </Directory> <Directory /var/www/DjangoBlog/weblog> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> </VirtualHost> -
Django template add class to link
I want to add another class to my div when this condition execute. {% for k in all_conversations %} <div {% if k.id == current_id %}class="shape"{% else %}class="emptyshape"{% endif %}><a href="{% url 'chatapp:chat' k.id %}">{{k.seller}}</a></div> {% endfor %} Everything is correct but it doesn't add class name and always executes else condition. current id in this situation is 212 but it doesn't work if i write in this way <div {% if k.id == 212 %}class="shape"{% else %}class="emptyshape"{% endif %}><a href="{% url 'chatapp:chat' k.id %}">{{k.seller}}</a></div> it works perfectly fine -
HTTPConnectionPool: Max retries exceeded with url: /_bulk (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
Please i need help with this. This happens when i'm trying to create a user in my model. Can't really tell whats happening here :S -
Django view DateField Format headache
Help would be appreciated. Whatever i search for I find everything else but what I need it seems. wwwaaah.... I have a DateField on my template that i need to get user specified date for an API i am building. My trouble is I need it in a specific format. I have googled and trying various params but cant get to work. Django's DateField default format is yyyy-mm-dd, but due to how our API works I need yyyy/mm/dd. specs: -django1.5 -python27 What works.... views.py class AddForm(forms.Form): new_timestamp = forms.DateField(required=False) class TimeView(View): def post(self, request) time_content = AddForm(request.POST) content['client_time'] = time_content if time_content.is_valid(): new_timestamp = time_content.cleaned_data["new_timestamp"] ... ...blah blah template: <div id="div_date_section">Date: <input type="text" name="new_timestamp"> YYYY/MM/DD </div> Gives me the following output (captured in my debug logs): 2016-11-10 23:46:48,520: DEBUG: views.py:296 timestamp: 2016-01-01 00:00:00-08:00 2016-11-10 23:46:48,520: DEBUG: views.py:297 timestamp type: <type 'datetime.datetime'> What I would like is a string formatted as: 2016/01/01. I have tried various methods to no effect. As mentioned I have been googling for hours, and one of thing i found was as follows, however this makes my code not work. I get absolutely no error to log or console, my code just breaks complaining about something unrelated … -
What is the Correct Django Model Relationship
Im a beginner in django and its modeling structure. And i would like to seek answer from anyone. I have a model Animal and Herd Each herd has a multiple animals and an animal belongs to a herd. So i design this many-to-one model relationship as an example. Am i in a wrong way or should i continue this practice? Because i am confuse with the djangorestframework serializer relations of Album and Track model relationship. Please help. animal.models.py class Animal(models.Model): name = models.CharField(max_length=25) date_of_birth = models.DateField() birth_weight = models.IntegerField() sex = models.CharField(max_length=7) sibling_order = models.IntegerField() herd.models.py class Herd(models.Model): animal = models.ForeignKeyField(Animal, related_name="animals", on_delete=models.CASCADE) name = models.CharField(max_length=25) description = models.TextField(max_length=250, null=True) -
SyntaxError: missing ; before statement on JSONResponse
I am getting this kind of error: SyntaxError: missing ; before statement I don't know what causes the error but I have this code here: (function pollschedule(){ $.ajax({type: "GET", dataType: "jsonp", contentType: "application/json", url: "http://127.0.0.1:8080/get/schedule/1/", success: function(data){ console.log(data); }, complete: pollschedule, timeout: 5000}); })(); In case you might need to see what http://127.0.0.1:8080/get/schedule/1/ is: def get_schedule(request, sid): schedule = Schedule.objects.filter(id=sid, date=datetime.datetime.now()).values('id', 'sched__name', 'date', 'time') sched_collection = collections.defaultdict(list) for i in schedule: sched_collection[i['sched__name']].append(i) return JsonResponse({"schedule" : dict(sched_collection)}) And returns this: {"schedule": {"CWW": [{"date": "2016-11-11", "time": "17:10:10"}]}} The error points the semi-colon after "schedule" in the response. -
django - queryset in modelForm
i need to filter Food model by datetime in forms.py but I do not know how to do it models.py class Food(models.Model): class Meta: verbose_name = "Food" verbose_name_plural = "Foods" def __unicode__(self): return self.food_name food_name = models.CharField(verbose_name="Food Name", max_length=50) serve_date = models.DateTimeField(verbose_name="Serve Date") forms.py class Reserve(forms.ModelForm): food_name = forms.ModelChoiceField( queryset=Food.objects.all(), widget=forms.Select(), empty_label=u"برای انتخاب غذا کلیک کنید", ) class Meta: model = Reservation fields = ('food_count', 'food_name') -
DjangoAllAuth - Get access token pre_social_login FB
I've a signal as follow:- class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin=None, **kwargs): token = 2222 # I want to get token over here. I've tried 1) request.GET 2) request.POST 3) sociallogin.account.extra_data 4) kwargs None contains the token of the user. How can I get the access token of the user in pre_social_login?? -
django: call overridden model method from django template
I have overrode (overrided?) the get_FOO_display() method of django model class (see: doc reference) to return some different choice field mapping. But, on calling this function from the django template as {{ model_object.get_FOO_display }} calls the base class method instead of the new overridden method. I read the source code django/db/models/base.py and it seems like this is not some regular method rather, it is created dynamically for the model fields. (let me know if am getting it wrong) Is there a way I can resolve to the overridden method from the template ? See this code to get the essence of my issue: class UserStatus(models.Model): invite_status = models.CharField(max_length=15, choices=USER_STATUS, default='new') # Overridden method def get_invite_status_display(self): return dict(USER_STATUS_DISPLAY).get(self.invite_status) Yes, I need to display different content than the choices dict and no, I cannot keep my to-be-displayed content in the choice dict in the first place. Let me know if there is any possible way to make this template call work. Thanks. -
Django 1.8. Formset. Implement check field for delete image
I have a formset for update with image file and clear field. If clear is True I need to delete image from model. How can I get current model in formset and update it? What is the best way to do it? My model form: class ImagesForm(forms.ModelForm): clear = forms.BooleanField(required=False) class Meta: model = Images fields = ('file',) widgets = {'file': forms.FileInput} ImagePerSet = inlineformset_factory(Personal, Images, form=ImagesForm, extra=10, max_num=10) I tried to do it in view like so: if formset.is_valid(): models = formset.save(commit=False) for form in formset: if form.cleaned_data.get('clear'): #delete image, but I don't know how to get the current model. -
Deserializing SlugRelatedField on ForeignKey with Django Rest Framework
I am struggling to set a PrimaryKeyRelatedField using a SlugRelatedField. My models.py looks like: class Airport(models.Model): name = models.CharField(max_length=200, blank=True) iata = models.CharField(max_length=20, blank=True) <other unrelated fields> class Flight(models.Model): flight_number = models.CharField(max_length=25, blank=False, unique=True) origin = models.ForeignKey(Airport, related_name='origin', null=True) destination = models.ForeignKey(Airport, related_name='destination', null=True) scheduled_departure = models.DateTimeField(null=True) scheduled_arrival = models.DateTimeField(null=True) My view looks like: class FlightList(APIView): # List all flights, or create a new flight queryset = Flight.objects.all() serializer_class = FlightSerializer def get(self, request, format=None): flights = Flight.objects.all() serializer = FlightSerializer(flights, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = FlightSerializer(data=request.data) if serializer.is_valid(): serializer.save() print serializer.validated_data return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) If I set my serializers.py to: class FlightSerializer(serializers.ModelSerializer): class Meta: model = Flight fields = ('flight_number', 'origin', 'destination', 'scheduled_departure', 'scheduled_arrival') From the shell I see the serializer renders to: FlightSerializer(): flight_number = CharField(max_length=25, validators=[<UniqueValidator(queryset=Flight.objects.all())>]) origin = PrimaryKeyRelatedField(allow_null=True, queryset=Airport.objects.all(), required=False) destination = PrimaryKeyRelatedField(allow_null=True, queryset=Airport.objects.all(), required=False) scheduled_departure = DateTimeField(allow_null=True, required=False) scheduled_arrival = DateTimeField(allow_null=True, required=False) I am able to POST origin and destination pk's that match up with Airport entries in the database to create new flights. Great. However, I actually need to post the airport code, (i.e.) LAX as the origin or destination, and have DRF figure out the appropriate … -
Creating a sample application where Django Bulk Writes to Mongo Db after Sessions end
I want to be able to use Django Sessions and Mongo DB together to perform bulk writes to database after a Session. Later I want to be able to associate Users to Sessions and Events as well. I have just started and I am new to Django . I am just running around tutorial after tutorial and so far I have just tried out some things and may have got a few things right I guess. Any help with finding some right direction is appreciated. Here is my views.py # Create your views here. from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render from django.contrib.sessions.models import Session from django.conf import settings from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import json class Events(APIView): def post(self,request,format=None): try: event_info = json.loads(request.body) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) if not request.session.session_key: request.session.save() sid = str(request.session.session_key) settings.DB.events.insert(event_info, w=1) return Response(sid,status=status.HTTP_200_OK) events = Events.as_view() models.py from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. from django.contrib.sessions.models import Session from django.contrib.auth.signals import user_logged_in class EventsModel(object): def __init__(self): self.conn = pymongo.MongoClient() self.db = conn.dev_db def save(self, event_info): """ Save json object into mongodb Cluster … -
Django custom test runner remove some of the default test argument
I write a custom test runner in Django to add custom argument '--headless', but the side effect is i can not use some of the default argument. I am using Django 1.9.11. My test runner code is: from django.test.runner import DiscoverRunner class IbesTestRunner(DiscoverRunner): @classmethod def add_arguments(cls, parser): parser.add_argument( '--headless', action='store_true', default=False, dest='headless', help='This is custom optional arguments for IBES.' 'Use this option to do browser testing without GUI') The result of ./manage.py test -h when using this test runner is: usage: manage.py test [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--noinput] [--failfast] [--testrunner TESTRUNNER] [--liveserver LIVESERVER] [--headless] [test_label [test_label ...]] . . . While using the default test runner, the result of ./manage.py test -h is: usage: manage.py test [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--noinput] [--failfast] [--testrunner TESTRUNNER] [--liveserver LIVESERVER] [-t TOP_LEVEL] [-p PATTERN] [-k] [-r] [-d] [--parallel [N]] [test_label [test_label ...]] ... Notice that i can not use some arguments like, -k, -p ,-r, etc. How can I add custom test arguments but not losing the default test argument? -
How to show depth of a single field in Django Rest Framework?
I am using depth = 1 on my serializer to show details of a foreign key field. However, it is also showing details of another foreign key field which I don't really need. How do I show the details of one field but not the other one? -
overwritten on the code
i'm new in django and python i'm currently having problem in python docx the dict it gives me all of the values but i need to show the values depends on the level accommodation_list = groupby(obj.accomodations.all(), lambda x: x.get_accommodation_level_display()) if accommodation_list: accommodation_dict = OrderedDict() for level, accomodations in accommodation_list: accommodation_dict[level] = OrderedDict() accommodation_dict[level]['name'] = level accommodation_dict[level]['data'] = dict(Counter([a.get_accommodation_display() for a in list(accomodations)])) floor_covering = OrderedDict() for level, level_data in accommodation_dict.iteritems(): level_name = level_data.get('name', '') level_accomodations = level_data.get('data', '') floor_covering['floor'] = dict(Counter(obj.all_floor_coverings for a in (level))) pprint (floor_covering) pprint('___') accomodation_str = '' for accomodation_name, accomodation_count in level_accomodations.iteritems(): accomodation_str += '{} {}, '.format(accomodation_count, accomodation_name) if accomodation_str.endswith(', '): accomodation_str = accomodation_str[:-2] hr31_cells3 = table3.add_row().cells hr31_cells3[0].paragraphs[0].add_run(level_name).font.bold = True in the terminal when i print out the floor_covering it shows me all the the values inside but i need to sort it depends on the level OrderedDict([(u'floor', {u'Ceramic Tile, Marble, Vinyl, Painted Concrete': 1, u'Terazzo': 1, u'Timber, Broken Marble': 1})]) u'___' -
How can I embed django code in html?(pagination)
I am trying to make a website using django. The url for the page is: url(r'^(?P<practical_id>[0-9]+)/(?P<photo_index>[0-9]+)/$', views.detail, name='detail'), My views.py is: def detail(request, practical_id, photo_index): photos = get_object_or_404(Photo, practical = practical_id, index=photo_index) return render(request, 'practicals/detail.html',{'photos':photos}) In details.html(bootstrap is used), <nav> <div class="text-center"> <ul class="pagination pagination-centered"> <li><a href="#" aria-label="previous">&laquo;</a></li> <li><a href="{% url 'practicals:detail' photos.practical.id 2 %}">2</a></li> <li><a href="#" aria-label="next">&raquo</a></li> </ul></div> </nav> I tried to link the url to the previous and next page, but I couldn't figure out how. I tried something like: <nav> <div class="text-center"> <ul class="pagination pagination-centered"> {% for i in range(1, photos.practical.index) %} <li><a href="{% url 'practicals:detail' photos.practical.id i-1 %}" aria-label="previous">&laquo;</a></li> <li><a href="{% url 'practicals:detail' photos.practical.id i %}">2</a></li> <li><a href="{% url 'practicals:detail' photos.practical.id i+1 %}" aria-label="next">&raquo</a></li> {% endfor %} </ul></div> </nav> It seems that we cannot use parenthesis() inside {% %}, so range function cannot be used and (i-1),(i+1) cannot be used either. So how can I use pagination the better way? -
list 1st folder in zip
I'm currently working with python. I want to print first folder without any other files or folders. There are 100 files and 1 folder in the zip. Using this code list me all files and folders in the zip file zip_ref = zipfile.ZipFile(filename, 'r') print zip_ref.namelist() I only want to get list for the first folder without any other files or folder. -
ImportError: No module named timeutils
I trying to follow tutorial install of django-celery. After install i need run migrate to make the necessary tables but appears that error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/guilherme/.virtualenvs/martizi-api/local/lib/python2.7/site-packages/djcelery/models.py", line 15, in <module> from celery.utils.timeutils import timedelta_seconds ImportError: No module named timeutils im not finding anything about this timeutils on web im using: django==1.9.8 django-celery==3.1.17 Thanks! -
What's the difference between .post() , .create() and perform_create() in views.py and .create() in serializers.py
I'm confused with .post() and .create() and perform_create() in views.py and .create() in serializers.py seems like .create() in serializers.py get the validated_data, so it can not check serializer.is_valid Here is the serializers.py: class PostListSerializer(ModelSerializer): class Meta: model = Post fields = [ 'title', 'content', 'publish', ] def create(self, validated_data): print("-------------------") print("5555555 - create", validated_data) return Post.objects.create(**validated_data) And if my code is : views.py class TestPostListAPIView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostListSerializer def post(self, request, *args, **kwargs): serializer = PostListSerializer(data=request.data) if not serializer.is_valid(raise_exception=False): # deal with serializer.errors return Response({'[post]custome error 1 !!!!!!!!!'}, status=status.HTTP_400_BAD_REQUEST) else: print("[post]- serializer.validated_data ", serializer.validated_data) serializer.save() return Response({'[post]Create success'}, status=status.HTTP_201_CREATED) the process will go .post() in views.py --> .create() in serializers.py --> Response to client If my views.py use: class TestPostListAPIView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostListSerializer # def post(self, request, *args, **kwargs): # serializer = PostListSerializer(data=request.data) # if not serializer.is_valid(raise_exception=False): # # deal with serializer.errors # return Response({'[post]custome error 1 !!!!!!!!!'}, status=status.HTTP_400_BAD_REQUEST) # else: # print("[post]- serializer.validated_data ", serializer.validated_data) # serializer.save() # return Response({'[post]Create success'}, status=status.HTTP_201_CREATED) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) print("44444-1 perform_create ", serializer) if not serializer.is_valid(raise_exception=False): print("44444-3 serializer.is_valid() ", serializer.is_valid()) return Response({'custome error!!!!!!!!!'}, status=status.HTTP_400_BAD_REQUEST) else: print("44444-7 serializer.validated_data ", serializer.validated_data) self.perform_create(serializer) return Response({ … -
Django template blocks
I currently have... <title> MyApp | {% block customtitle %}{% endblock %} </title> What I want really is for the | to only appear if the customtitle block is NOT empty. I only want to see MyApp in the title if the page does not set the customtitle block. Is that an option? How would one implement it?