Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unit test an external facing function
I am trying to write unit test case for an external facing api of my Django application. I have a model called Dummy with two fields temp and content. The following function is called by third party to fetch the content field. temp is an indexed unique key. @csrf_exempt def fetch_dummy_content(request): try: temp = request.GET.get("temp") dummy_obj = Dummy.objects.get(temp=temp) except Dummy.DoesNotExist: content = 'Object not found.' else: content = dummy_obj.content return HttpResponse(content, content_type='text/plain') I have the following unit test case. def test_dummy_content(self): params = { 'temp': 'abc' } dummy_obj = mommy.make( 'Dummy', temp='abc', content='Hello World' ) response = self.client.get( '/fetch_dummy_content/', params=params ) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Hello World') Every time I run the test case, it goes into exception and returns Object not found. instead of Hello World. Uponn further debugging I found that temp from request object inside view function is always None, even though I am passing it in params. I might be missing something and not able to figure out. What's the proper way to test these kind of functions. -
Django looking for static file through wrong path...how do I change?
I am implementing Jquery into my Django base...well at least trying here. I have done the necessary steps from (http://www.tangowithdjango.com/book17/chapters/jquery.html), and I'm trying to run collectstatic in cmd to update static files, as that is what I believe is the main culprit in my Jquery code not running. My static folder is located in: c:.../website/mysite/personal/static However, I go to run collectstatic in cmd and I am getting the following error: "FileNotFoundError: [WinError 3]The system cannot find the path specified: 'C:\Users\PC\Desktop\website\mysite\static" Not sure why it is pulling from there. I do have a folder /website/mysite/mysite , but I don't believe that to be the issue at hand. Below are my settings.py for static: STATIC_URL = '/static/' STATIC_ROOT = "/mysite/personal/static/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"),) -
How to initialize data from a file when the site executes - django python
I want to build a dictionary translation site using django Python. I have a dictionary file available in dictionary.txt. Here is the format of the file: Etc Discusses: thảo luận Deals with: giải quyết Etc I want to read this file when the site is executed. Because for processing I have a function that will read the data from dictionary.txt and save it to a dictionary data type in python. Can you help me? This is my code, which reads data in .txt file: def read_dictionary(fileName): dict = {} my_dict = {} with open(fileName, 'r',encoding="utf8") as f: for line in f: items = line.split(':') key, values = items[0].replace('X','*'),items[1].strip().replace('\n','') dict[key] = values for k, v in dict.items(): my_dict.setdefault(v, []).append(k) return my_dict -
Why does dict.key returns value in Template but not in Views
Continuing from previous Question. I have a queryset that I can get the value through key in Template, but if I try identical steps in Views.py, I get: 'dict' object has no attribute 'user' My query is: rate = foo.objects.values('user').distinct().annotate(r=Avg("rate"), r1= Avg("rate1"), r2= Avg("rate2")).annotate(a = F('r')+F('r1')+F('r2')).order_by('a')[:5] The above query returns: <QuerySet [{'user': 18, 'r': 2.0, 'r1': 2.0, 'a': 10.0, 'r2': 2.0}, {'user': 16, 'r': 1.0, 'r1': 5.0, 'a': 15.0, 'r2': 4.0}, {'user': 17, 'r': 4.333333333333333, 'r1': 5.0, 'a': 20.833333333333332, 'r2': 4.833333333333333}]> In template, if I do this, it returns the user_id: {% for r in rate %} {{ r.user }} {% endfor %} but if I do similar in view: for r in rate: foo = r.user I will get a 'dict' object has no attribute 'user'. My objective is to get the user object, so I'm trying to get the user_id and through it get a list of the users so I can use them to display information in template. Looking for a reason as to why it works in template, and not in Views. Also looking for an alternative to the query which would return user object, rather than user_id. Thanks, -
How do I use a pre-set list of choices from a foreign key as the options to select from in a ModelForm in Django?
I have 2 models, one is a profile user model and the other for categories of that profile. (see below). The category model has one 'name' attribute which consists of a set of choices that users must choose as their profile type. class DkUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) category=models.ForeignKey(Category, blank=True, null=True) CATEGORIES = ( ('cat1', 'Category1'), ('cat2', 'Category2'), ('cat3', 'Category3'), ) class Category(models.Model): name=models.CharField(max_length=100, choices=CATEGORIES) My form thus far: class ProfileForm(forms.ModelForm): category = forms.ChoiceField() class Meta: model = DkUser fields = ('category') What I'm trying to do is to include a drop-down choice-field on the form that allows users to select one of 'category 1', 'category 2' or 'category3'. I've looked at ModelChoiceField, but that appears to be for choosing from the Model Instances. How might I achieve this? All help greatly appreciated. -
How to pass id from url to another url that already contains an id?
I explain, I have a view q when selecting a specialty sends me the id of this to a list view where they find all the articles of that specialty, then an enter button that sends to enter the quantity of the item, I have to return A The specialty list, so the first ID is lost and do not know which list to send. No articles to show. Now, as it would be a return that maintains the specialty ID once the amount is entered, so that I return to the same view of the specialty that is being entered. view.py: This captures the ID of the specialty and passes it by get to the URL and shows me the articles. ej: http://127.0.0.1:8000/solicitar/lista/2/ def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user if user.is_superuser: pedido = Pedido.objects.filter(especialidad=especialidad) template = 'admindata.html' return render_to_response(template,locals()) else: pedido = Pedido.objects.filter(especialidad=especialidad) template = 'index2.html' return render_to_response(template,locals()) This list the articles of the selected specialty. Sending the model form to enter an amount in numbers: ej: http://127.0.0.1:8000/solicitar/ingresar/128/ def Pedido_Edit(request, id_pedido): pedido = Pedido.objects.get(id=id_pedido) if request.method == 'GET': form = PedidoEditForm(instance=pedido) else: form = PedidoEditForm(request.POST, instance=pedido) if form.is_valid(): form.save() return redirect('usuario:lita_todo') return … -
Django data losing order when running on Heroku
I have a list which contains lists like [[1, 2, 4], [5, 6,7], [8, 9,10]] I pass the list to the template html which then loops through it and displays it as a table like below: <tbody> {% for zone in zones %} <tr> <td>{{zone.2}}</td> <td>{{zone.0}} -- {{zone.1}}</td> </tr> {% endfor %} </tbody> This is how I'm passing it: return render(request, 'alpha/index.html', {"zones":zones}) When I'm running it locally it works as I expect it. That is, the first element in the list is presented first in the table as well. This order is lost when I push to Heroku (the zones appear randomly in the table) and I'm not sure what is causing this. I have tried to take the elements of the list, load them into variables and pass them one by one to see if the list is losing the order somehow. This didn't help, so I'm thinking it's a problem either with Heroku's setup or I'm using Django wrong. Any help is much appreciated. Thanks! -
Dynamic forms for end users in django
I'm creating a django project where any user can create forms with any number of fields. For example user A could create the follow form: Name of field: Field_1 - Type: Text Name of field: Field_2 - Type: Date Name of field: Field_3 - Type: File And user B could create: Name of field: name - Type: Text Name of field: phone - Type: Text Look that the user need to say to the program the name of the field and type. Since is a dynamic way to create any number of forms and any number of field for each forms. What would be the most efficient way to create the database model? Take into account that the program does not know the name of the field until the user send it. So in the views, I can't process it with exact name of fields. -
The date is frozen for tomorrow, not today
# -*- coding: utf-8 -*- from __future__ import unicode_literals import base64 from datetime import timedelta, datetime from freezegun import freeze_time from django.conf import settings from django.core.urlresolvers import reverse from django.core.management import call_command from django.test import Client from django.core.files.uploadedfile import SimpleUploadedFile class timetravel(object): """ Fast forward in time with simulated CRON jobs (used for unit testing) """ delta = None def __init__(self, *args): self.initial_now = datetime.now() if isinstance(args[0], timedelta): self.delta = args[0] self.now = datetime.now() + self.delta elif isinstance(args[0], datetime): self.now = args[0] if args[0] > self.initial_now: self.delta = args[0] - self.initial_now else: self.delta = self.initial_now - args[0] else: print("Please provide a datetime or timedelta object as argument") # import IPython # IPython.embed() #self.now = self.initial_now #self.freezer = freeze_time(self.now) #self.freezer.start() def __enter__(self): # Traveling in the past, we don't run cron jobs backward if self.now < self.initial_now: self.now = self.now - self.delta self.freezer = freeze_time(self.now) # import IPython # IPython.embed() self.freezer.start() # Traveling in the future, run cron jobs else: self.now = self.initial_now self.freezer = freeze_time(self.now) self.freezer.start() hours = self.delta.total_seconds() / 60 / 60 weekday = self.now.weekday() month = self.now.month year = self.now.year for i in range(1, int(hours)+1): call_command('cron', hourly=True, verbosity=0) if weekday != self.now.weekday(): weekday = self.now.weekday() call_command('cron', daily=True) if … -
Django-Rest-Framework - How to serialize queryset from an unrelated model as nested serializer
I'm trying to add a nested serializer to an existing serializer based on some criteria of the parent model, not a Foreign key. The use case is to return a 'Research' object with an array of 'ResearchTemplate' objects that are identified by filtering on a postgres ArrayField. Models class Research(TimeStampedModel): category = models.CharField(max_length=100, choices=RESEARCH_TEMPLATE_CATEGORIES, default='quote') body = models.CharField(max_length=1000, blank=True, default='') #The body of text comprising the nugget additionaldata = JSONField(null=True) # all the varying values to be merged into a wrapper def __str__(self): return self.body class Meta: ordering = ('created',) class ResearchTemplate(TimeStampedModel): template = models.TextField(blank=True, default='') category = models.CharField(max_length=100, choices=RESEARCH_TEMPLATE_CATEGORIES, default='quote') mergefields = ArrayField(models.CharField(max_length=200), blank=True) def save(self, *args, **kwargs): merges = re.findall("{{(.*?)}}", self.template) #get all the template names from within the mustaches self.mergefields = list(set(merges)) #TODO: Make Unique super(TimeStampedModel, self).save(*args, **kwargs) def __str__(self): return self.wrapper class Meta: ordering = ('created',) Serializers class ResearchSerializer(serializers.ModelSerializer): templates = ResearchTemplateSerializer(many=True) class Meta: model = Research fields = ('id', 'created', 'speaker', 'body', 'templates') class ResearchTemplateSerializer(serializers.RelatedField): def get_queryset(self, values): return ResearchTemplate.objects.filter(mergefields__contained_by=['django']) #This must an array of keys from the Research object's JSON field class Meta: model = ResearchTemplate fields = ('id', 'template') I've been able to nest serializers when there is a foreign key mapping them, … -
corrupted image swift3 base64 django
I am trying to send an image from ios to my django server, using base64. All of the pieces seem to be working fine and there is no error, But the image saved in the django server is corrupted. Below is my code for the ios side: let imageData:NSData = UIImageJPEGRepresentation(image, 0.5)! as NSData let strBase64 = imageData.base64EncodedString(options: .endLineWithCarriageReturn) where image is a UIImage. Then I send the json {'image',strBase64} to my django server. In the following you can find the code for the django side. This is the function which is called: from base64 import b64decode def up(request): imageStr = request.POST.get('image','') if imageStr != '': image_data = b64decode(imageStr) Images.objects.create(pic = ContentFile(image_data,'image.jpg')) return HttpResponse("Function called.") return HttpResponse("No image received.") and my model is like this: class Images(models.Model): pic = models.ImageField("Image", upload_to = "images/") upload_date = models.DateTimeField(auto_now_add = True) And my django version is 1.10. I read the similar questions and the answers but none of them solved my problem. -
DocumentForm for mongoengine is not rendered with CreateView Django
I'm using these libraries: mongoengine mongodbforms mongogeneric When I try to pass my DocumentForm to CreateView on form_class, on template this form is not appearing, but if I define the view as a function passing it manually with a return render(..., {'form': form}) it works. Any ideas to solve this with generic class based views? -
How to access a Django model instance after it has already been saved?
I have 2 models, one called MyProfile and another for items for sale. In my views I am trying to create an item for sale, but when I set author (which is a foreignkey to MyProfile, I get an error. views.py active_user = MyProfile.objects.filter(user=david) form.author = active_user error ValueError: Cannot assign "<QuerySet [<MyProfile: david test test None>]>": "Entry.author" must be a "MyProfile" instance. I think the problem here is that I am trying to pass an instance of MyProfile to form.author, but instead I am passing a QuerySet. So my question is how do I pass the object? I am working on a project in django and trying to completely bypass the django user model, so please keep this in mind when answering. I am NOT trying to use the included django User model, all I'm trying to figure out is a solution for passing the MyProfile instance to form.author since this is a ForeignKey field. I thought I could just pass it via request.session, but I got an error about serializing this object. -
Python Social Auth - Custom user and the pipline
I'm trying to create a facebook login function for my page. However I ran into a problem when the pipeline tries to create a user. I get a Email must be set and it's my model CustomUserManager that throws it. Below is my CustomUserManager and CustomUser models class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ print('creating user...') if not email: raise ValueError('Email must be set') #<--- Throws the error. email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=250, unique=True, ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=datetime.now) objects = CustomUserManager() REQUIRED_FIELDS … -
Django endless pagintion on scroll in case of overflowed container
I have the following Django template: <ul id = 'dialog_list_container'> {% include page_template %} {% block js %} {{ block.super }} <script src="/static/js/el-pagination.js"></script> <script src="/static/js/el-pagination_on_scroll.js"></script> <script> $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 20 }); </script> {% endblock %} </ul> dialog_list_container is a scrollable element: #dialog_list_container { overflow-y: auto; height: 500px; } The problem is that I have still to manually press the Show more link in the bottom of paginated list, whereas I would expect new records to be uploaded automatically as I scroll to the bottom of dialog_list_container. I guess, the reason is that Django's pagination on scroll triggers in those cases when browser window is scrolled. Is there any painless way to make Django upload new records in case of a container with css overflow-y: auto attribute? -
calling command line app from flask or django
I have a command line tool like as follow: tool -o output -a authentication.txt -i input.txt (it gets some files as input) what I would like to do is to provide an web interface for this command line tool using flask or django since the tool is based on python. So can you guide me how can I call the tool and gets its results from stdout! Also tool has the config file and I want to open and edit it in web interface too. My initial idea was to call python subprocess to call the app to gets its stdout but do not know how wise it is?s -
Django Debug = False returns bad request even Allowed_Host = ['localhost','127.0.0.1'] is configured
I get Bad Request (400) on my localhost when my DEBUG = False. Even I configured ALLOWED_HOSTS. I have been searching all over stackoverflow but still can't find the source of the problems. DEBUG = False ALLOWED_HOSTS = ['localhost','127.0.0.1'] -
django permissions: new permission is inserted after all other migrations
I added a new permission to my model, and than used manage.py makemigrations. it created a migration that alters the model options (specificly the permisions..). later , I added a migration that has a dependency on that first migration, and uses the permission (that i believed the first migration created). that migration used the permission in a RunSQL operation that queried auth_permissions. as i debugged the migrations - i realized that the insert to the auth permission only happens after all of the migrations have been applied. meaning - when i try to query the id of the permission in order to use it in the second migration - it doesn't exist and so the second migration doesn't behave as expected. any idea why this happens and how to prevent it? my assumption when adding a new permission was that it will be added with the migration that django created for me..and not at a different stage. Thanks! -
exception raised if not enough space on hdd when saving FileField
What will happen if server hard drive is nearly full OR it's memory is full, when I try to upload a (huge) file and save it to my model FileField? Will Django raise an exception? What type it is? Is it a subclass of DatabaseError? -
how to temporarily pass form validation for a form field
I have the following model: class Regulatory(models.Model): field1 = models.BooleanField(choices=BOOL_CHOICES, default=None, ) field2 = models.IntegerField(choices=THREE_CHOICES, default=None,) I have the following form: class RegulatoryForm(forms.ModelForm): field1 = forms.BooleanField(required=False) field2 = forms.IntegerField(required=False) class Meta: model = Regulatory widgets = { 'field1': forms.RadioSelect(attrs={"required": "required"}), 'field2': forms.RadioSelect(attrs={"required": "required"}), } def __init__(self, *args, **kwargs): self.site_id = kwargs.pop('site_id', None) super(RegulatoryForm, self).__init__(*args, **kwargs) def clean(self): data = self.cleaned_data if self.site_id == 2: data['field1'] = 0 data['field2'] = 0 else: return data When I submit the form, I still get the validation error: field error: This field cannot be null. How can I allow the required fields to temporarily pass through to my view so I can set them before saving? -
Python Flask import list
I'm new to python and can't seem to figure it out.. I have following code saved as content.py import fnmatch import os matches = [] for root, dirnames, filenames in os.walk("Z:\\"): for filename in fnmatch.filter(filenames, '*.iso'): matches.append(os.path.join(root, filename)) for item in matches: print(item) I have following code for website in website.py : from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run('192.168.1.8', 8080) I tried many combinations to get it to work so my matches gets added into the website.py somehow. Can i add a list directly into the website.py? The list will have lines of OS iso copies. I would like to website.py run every houre as a cron job. Do i need to stop the website in website.py to refresh it contents inside the cron job?: @app.route('/shutdown', methods=['POST']) def shutdown(): shutdown_server() return 'Server shutting down...' Sorry for these questions, but i'm more a scripter.. so using stuff i know but using program languages is very different. Thanks, Ward -
Upload Image File to server
Have a little problem with uploar file image to server That is JS code for ajax send file to server /** * * Init Crope Image * */ $('input[type=file]').change(function(){ files = this.files; }); $('#upload_photo').click(function (event) { event.stopPropagation(); // Остановка происходящего event.preventDefault(); // Полная остановка происходящего var data = new FormData(); $.each( files, function( key, value ){ data.append( key, value ); }); var obj = { csrfmiddlewaretoken: $('input[name^="csrfmiddlewaretoken"]').val(), action: 'upload_photo', file: data }; $.ajax({ url: /user_ajax_set_photo/, type: 'POST', data: data, cache: false, dataType: 'json', processData: false, contentType: false, success: function( response, textStatus, jqXHR ){ if( response.error === 'false' ){ console.log('Загружен' + response.error ); } else{ console.log('ОШИБКИ ОТВЕТА сервера: ' + response.error ); } }, error: function( jqXHR, textStatus, errorThrown ){ console.log('ОШИБКИ AJAX запроса: ' + textStatus ); } }); }); } That us my View def user_ajax_set_photo(request): if request.method == 'POST': form = FileUploadForm(data=request.POST, files=request.FILES) if form.is_valid(): print 'valid form' else: print 'invalid form' print form.errors return True And for last that is my Form class FileUploadForm(forms.Form): class Meta: model = RegModel fields = ['image'] def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(FileUploadForm, self).__init__(*args, **kwargs) def save(self): photo = super(FileUploadForm, self).save(commit=False) artist = RegModel.objects.get(id=self.request.user.id) photo.artist = artist photo.save() return photo … -
Django UpdateView pk via POST arguments
I'm developing an app on django v1.10, and I want to pass a pk to an UpdateView via POST arguments, for security reasons, because the app uses an authentication system. I've researched and found that overriding the get_object method I (should) get what I want bu nothing happens. I don't know if I'm doing something wrong or I'm missing something. Maybe the situation requires a different approach. In my view source I pass the argument via link in a form, calification.id is the pk. <form method="post" action="{% url 'edu:calification-update' %}"> {% csrf_token %} <input type="hidden" value="{{ calification.id }}" name="pk"> <button class="btn btn-default btn-xs" type="submit">editar</button> </form> In the receiving view I override the get_object method: class CalificationUpdateView(UpdateView): model = Calification template_name = 'edu/calification_create.html' form_class = CalificationForm def get_object(self): obj = get_object_or_404(Calification, pk=self.request.POST.get('pk')) return obj But in the update template the object is not retrieved, the form is in blank and no error appears. Thanks -
Django Multiple Choice Filter With Ranges
I am reading through django documentation for filters and came across the multiple choice filter. class User(models.Model): username = models.CharField(max_length=255) first_name = SubCharField(max_length=100) last_name = SubSubCharField(max_length=100) status = models.IntegerField(choices=STATUS_CHOICES, default=0) STATUS_CHOICES = ( (0, 'Regular'), (1, 'Manager'), (2, 'Admin'), ) class F(FilterSet): status = ChoiceFilter(choices=STATUS_CHOICES) class Meta: model = User fields = ['status'] In my application I have a decimal field representing the price in my product model. I was wondering if there was a way I could use the multiple choice filter to select price ranges, e.g., (0-200, '$'), (201-500, '$$'), (501-1000, '$$$') I am aware of the range filter but I need the functionality of the multiple choice filter and be able to select multiple ranges. -
Django sort records by calculated field
I have a class : class Person(models.Model): def __str__(self): return self.name score1 = models.FloatField(default=0) score2 = models.FloatField(default=0) score3 = models.FloatField(default=0) in django and i need to sort the records by the average score (using order_by method). i did some research and came up with pythons django class I tried to use it both as a method and as decorator the problem is django doesn't accept that as a field and to sort a column by some attribute it has to be a field. is there anyway around this? am i making the right call using the property class or should i use some other method? thanks in advance