Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to block the 2nd field with choices until the choice in the 1st field is selected?
# models.py class UserSportKinds(AbstractSports): KINDS_OF_SPORTS = ( (1, _('football')), (2, _('volleyball')), (3, _('hockey')), ) MASTERY_CHOICES = ( (1, _('newby')), (2, _('amateur')), (3, _('semi-pro')), (4, _('pro')) ) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) kind_of_sport = models.IntegerField(_('kind of sport'), null=True, blank=True, choices=KINDS_OF_SPORTS) mastery = models.IntegerField(_('mastery'), null=True, blank=True, choices=MASTERY_CHOICES) This code allows to have mastery without kind_of_sport, so admin via admin page and user via its profile may select any mastery without corresponding sport. Is it possible to block mastery field in template until kind_of_sport is selected using django built-in features or any django batteries, so without external javascripts? -
Troubleshooting 5 sec Delay in Form Submission
I have created a very simple form submission for users to register, requiring them to enter their email, username, and password. There is a ~5 sec delay from when I click the submit button to when the form actually submits. How can I figure out what's going on here? Here is what I have tried so far: Django Debug Toolbar - Profiling: It seems that there are clues here, but I have been unable to use this information to solve the issue using this data. Any ideas? Profiling Image Javascript I attached some progress bar Javascript using NProgress. It is interesting to note that the progress bar does not start until after the 5 sec delay. Here's the HTML (orange-bt class is just formatting): <form class="register-form" method="POST" action="/register/"> {% csrf_token %} {{ form.as_p }} <input class="progress-bar orange-bt" type="submit" value="Register"> </form> And some Javascript at the bottom: <script> $(".progress-bar").click(function() { NProgress.start(); }); </script> views.py I inserted a few print to console lines while troubleshooting, and it appears that the delay occurs right before the if request.method == 'POST' line. All the actions in the POST if statement occur quickly enough after the 5 sec delay, but I cannot figure out what … -
Add context to every Django Admin page
How do I add extra context to all admin webpages? I use default Django Admin for my admin part of a site. Here is an url entry for admin: urlpatterns = [ url(r'^admin/', admin.site.urls), ] And my apps register their standard view models using: admin.site.register(Tag, TagAdmin) My problem, is that I want to display an extra field in admin template header bar and I have no idea how to add this extra context. My first bet was adding it in url patterns like below: urlpatterns = [ url(r'^admin/', admin.site.urls, {'mycontext': '123'}), ] But that gives an error: TypeError at /admin/tickets/event/4/change/ change_view() got an unexpected keyword argument 'mycontext' Can you give any suggestion? I really do not want to modify every AdminModel class I have to insert this context, as I need it on every admin page. Thanks. -
Django: pythons os.scandir next() method not working inside jinja2 code
I have the following code in the views.py def gallery(request): import os, sys img_list2 = os.scandir('/home/shared/testing') return render(request,'blog/gallery.html', {'images2':img_list2}) It is sending the iterator img_list2 to the template gallery.html My gallery.html is as follows <div> <p>{{ next(images2).path }}</p> </div> I am just testing the next() method works or not. it says django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '(images2).path' from 'next(images2).path' [13/Sep/2016 23:21:38] "GET /gallery/ HTTP/1.1" 500 13092 -
Why "class Meta" is necessary while creating a model form?
from django import forms from .models import NewsSignUp class NewsSignUpForm(forms.ModelForm): class Meta: model = NewsSignUp fields = ['email', 'first_name'] here This code works perfectly fine. But, when I remove "class Meta:" as below, it throws a ValueError saying "ModelForm has no model class specified." from django import forms from .models import NewsSignUp class NewsSignUpForm(forms.ModelForm): model = NewsSignUp fields = ['email', 'first_name'] Can someone please give an explanation? :( -
Use wget to upload files to django
I'm quite new to Django and following this post to implement a project that receives files from client. The application works fine with a browser or curl but I'm having trouble figuring out the wget command to use. The environment I'm working in doesn't support curl and I'll have to use wget, which doesn't directly support multipath/form-data. Based on this post, I tried using something like: wget --header "Content-Type: multipart/form-data" --post-data "docfile=log.log" http://192.168.1.1/myapp/uploadlog/ but wasn't sure how to specify the boundary parameter. I'd appreciate any guidance. I'm also open to changing my Django app if needed. Thanks in advance. -
Django upload image to cdn using an API
I am building a website in Django on Pythonanywhere.com and I am using Backblaze's B2 cloud storage to store all the static and media files. My css and images that I have uploaded to Backblaze are working but I can't figure out how everything should fit together, so here is where I am (minimalized): In this model I want to store a thumbnail image, I have a form working to upload it. class Post(models.Model): (...) thumbnail = models.ImageField(null=True, blank=True, width_field="width_field", height_field="height_field") (...) Backblaze has all the code for the http requests and responses that I need, so I just pasted that in a seperate file. I first need to get an account authorization token, followed by an upload url and then I can send the file. So that whole function needs three things as input: the file date, file name and file size. As output I get the file id (and other things, details here). Now I wonder where I need to call that upload function, I assume it has to do with the "upload_to" parameter in the ImageField. And I wonder what actually gets stored in the ImageField, since I don't tell ImageField the location where to find the … -
Django ImportError cannot import name request
I'm learning Django using book Django-By-Example by Antonio Mele. For now I reached chapter 5 and now I'm trying to create image sharing app. But despite following all instructions in that chapter I'm getting ImportError when I try to add the image from external URL in django development server. ImportError at /images/create/ cannot import name request Request URL: http://127.0.0.1:8000/images/create/?title=%20Django%20and%20Duke&url=http://upload.wikimedia.org/wikipedia/commons/8/85/Django_Reinhardt_and_Duke_Ellington_(Gottlieb).jpg. Django Version: 1.8.6 Exception Location: /home/ciotar/projects/VirtualEnvs/env/bookmarks/bookmarks/images/forms.py in <module>, line 1 Python Version: 2.7.11 I'm using Pycharm and have set python 3.5 interpreter from active virtualenv instance. Not sure why Django runs with python 2.7 though. I wonder if this problem could appear because of 'request' name conflict between forms.py and views.py modules? /images/urls.py urlpatterns = [ url(r'^create/$', views.image_create, name='create'), ] /images/views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): """ View for creating an Image using the JavaScript Bookmarklet. """ if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() messages.success(request, 'Image added successfully') # redirect to new created item detail view return redirect(new_item.get_absolute_url()) … -
Trying to set a field from a ModelForm equal to an attribute of another model results in a memory object
I've been trying to set a ModelForm's field equal to the following: project.region = list(Profile.objects.filter(user=request.user))[0].region If I print this object it returns a string, the region, of the current user. However, when it saves this value to the project model, it gets saved as some sort of deferrable object at a spot in memory as follows: <django.db.models.query_utils.DeferredAttribute object at 0x03ACAFF0> I have a sneaking suspicion that this has to do with the ModelForm's handling of fields, but pouring through the Django docs has proven fruitless for trying to set a field to another model's attribute. Thanks so much for your help in advance guys. -
OperationalError: Can't connect to local MySQL server through socket
I'm trying to run a server in python/django and I'm getting the following error: django.db.uils.OperationslError: (200, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"). I have MySQL-python installed (1.2.5 version) and mysql installed (0.0.1), both via pip, so I'm not sure why I can't connect to the MySQL server. Does anyone know why? Thanks! -
Validate and get django form's unkown number of multipleselect checkbox fields
I am trying to get all selected checkboxes values as a list however not able to validate the form due to choices option forms.py: class MarkAccountsForm(forms.Form): accounts = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple, required = False ) template: {% for account in accounts %} <tr> <td><input type="checkbox" name="accounts" value="{{ account.id }}"></td> <td>{{ account.name }}</td> </tr> {% endfor %} views.py: if request.method == 'POST': form = MarkAccountsForm(request.POST) if form.is_valid(): #this fails data = form.cleaned_data When I try to print form.errors, it says Select a valid choice. 1119 is not one of the available choices. Is there a way that I can avoid choice validation and still get values of all accounts checkboxes checked as a list? How do I say it to allow any for choices? If I can get the list without form validation then that is fine too. -
Tastypie return a Resource based on the current logged in user [API]
I'm trying to create a read only API using Tastypie. I want to be able to know how to return a Resource based on the current logged in user. # models.py from django.contrib.auth.models import User class Store(models.Model): store_name = models.CharField(max_length=200) user = models.ForeignKey(User) class Item(models.Model): item_name = models.CharField(max_length=200) store = models.ForeignKey(Store, on_delete=models.CASCADE) So far, I understand that I can "expose" my models using this code from the documentation: # myapp/api.py from tastypie.resources import ModelResource from myapp.models import Store, Item from django.contrib.auth.models import User class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' class ItemResource(ModelResource): store = fields.ForeignKey(StoreResource, 'store') class Meta: queryset = Item.objects.all() resource_name = 'item' class StoreResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta: queryset = Store.objects.all() resource_name = 'store' These urs are now exposed... http://127.0.0.1:8000/api/store/ http://127.0.0.1:8000/api/store/1/ http://127.0.0.1:8000/api/item/ http://127.0.0.1:8000/api/item/1/ http://127.0.0.1:8000/api/user/ http://127.0.0.1:8000/api/user/1/ My question is, at any given moment, there is a user that is currently logged in. When I hit up http://127.0.0.1:8000/api/store/, I don't want it to return Store.objects.all(), but all the stores that belong to the current user. What's the right way to do this using Tastypie? -
django override model save method error
I have a model, which contains an ImageField. I want to autocreate 2 additional fields from that ImageField. class Images(models.Model): ... img = models.ImageField(upload_to='img') #for autocreating rimg = models.ImageField(upload_to='rimg', null=True, blank=True) limg = models.ImageField(upload_to='limg', null=True, blank=True) def create_rimg(self): # some work for generating rimg self.rimg.save() def create_limg(self): # some work for generating limg self.limg.save() def save(self, *args, **kwargs): self.create_rimg() self.create_limg() force_update = False if self.id: force_update = True super(Images, self).save(force_update=force_update, *args, **kwargs) That code gives a 500 error. If i call that code, it works perfect: def save(self, *args, **kwargs): self.create_rimg() #self.create_limg() force_update = False or def save(self, *args, **kwargs): #self.create_rimg() self.create_limg() force_update = False How can i call that 2 functions in save() method? -
unable to delete form in django formset
Using Django 1.9.9, Python 2.7 I am trying to figure out why I am not able to delete form/instance inside of FormSet. I was folowing debug to this function in django.forms.formsets.py line 300. def _should_delete_form(self, form): """ Returns whether or not the form was marked for deletion. """ return form.cleaned_data.get(DELETION_FIELD_NAME, False) In my case: form.cleaned_data = {'name': 2, 'file': FieldFile: real_estate_1/podpis.html} data = { u'contracts-0-DELETE': [u'on'], ...} changed_data = [[u'DELETE'], ...] ... The main problem is that cleaned_data missing the DELETE field. The formset has self.can_delete = True. But I am not able to figure out why the field is missing there...? I would appreciate any advice. My classes look this: class DocumentsForm(CustomModelForm): file = forms.FileField(label=_(u'Smlouva'), required=True) empty_permitted = False class Meta: model = Contract fields = ['name', 'file'] fields_with_permissions = ['file'] class RequestInlineFormSet(BaseGenericInlineFormSet): formset = 'contracts' empty_permitted = False def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) form_kwargs = {'request': self.request} super(RequestInlineFormSet, self).__init__(form_kwargs=form_kwargs, *args, **kwargs) ContractFormSet = generic_inlineformset_factory(Contract, form=DocumentsForm, formset=RequestInlineFormSet, can_order=False, can_delete=True, fields=('name', 'file'), extra=1) -
How to check which translation file Django ugettext uses?
I'm facing a problem where ugettext returns a wrong translation string. Is there a way to see which .po or .mo file ugettext got the string from? from django.utils.translation import ugettext, activate activate('sv') ugettext('First name') > u'Etunimi' I've tried grepping the string from my .po files and regenerated the .mo files to no avail. -
Django Python Social Auth only allow certain users to sign in
I want only users from a @companyname.net email or from a list of email addresses to be able to sign in with Python Social Auth through google+. How would I accomplish this? SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['companyname.net'] is what I currently have in settings.py, but that only allows @companyname.net-ers to sign in. -
Django: Multiple URL parameters
I'm making a study app that involves flashcards. It is divided into subjects. Each subject (biology, physics) has a set of decks (unitone, unittwo). Each deck has a set of cards (terms and definitions). I want my URLs to look like localhost:8000/biology/unitone/ but I have trouble putting two URL parameters in one URL. models.py class Subject(models.Model): subject_name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.subject_name def get_absolute_url(self): return reverse('card:index') class Deck(models.Model): deck_name = models.CharField(max_length=100) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) def __str__(self): return self.deck_name class Card(models.Model): term = models.CharField(max_length=100) definition = models.TextField() deck = models.ForeignKey(Deck, on_delete=models.CASCADE) def __str__(self): return self.term views.py class IndexView(generic.ListView): template_name = 'card/index.html' context_object_name = 'subjects' def get_queryset(self): return Subject.objects.all() class SubjectView(DetailView): model = Subject slug_field = "subject" template_name = 'card/subject.html' class DeckView(DetailView): model = Deck slug_field = "deck" template_name = 'card/deck.html' urls.py # localhost:8000/subjects/1 (biology) url(r'^subjects/(?P<pk>[0-9]+)/$', views.SubjectView.as_view(), name='subject') # localhost:8000/subjects/1/1 (biology/unitone) url(r'^subjects/(?P<pk>[0-9]+)/<deck_name_here>/$', views.DeckView.as_view(), name='deck'), How do I do this? -
Change the polymorphic content type of a django model instance
If I have a polymorphic model: class Father(polymorphic.model.PolymorphicModel) and an inheritor class with no extra fields: class Child(Father) When I have an instance of Father, how can I convert it to a Child instance? What I have tried is: foo = Father.objects.get(pk=1) # foo is just a Father, no record in Child database table. foo.polymorphic_ctype = ContentType.objects.get(app_label='myapp', model='child') foo.save() But nothing changes. I want foo to be a Child object and need to have this into the child database table. -
django-positions - multi-table model inheritance using parent_link
Using https://github.com/jpwatts/django-positions, I have a few models that inherit from a parent one, for example: class ContentItem(models.Model): class Meta: ordering = ['position'] content_group = models.ForeignKey(ContentGroup) position = PositionField(collection='content_group', parent_link='contentitem_ptr') class Text(ContentItem): title = models.CharField(max_length=500, unique=False, null=True, blank=True) I understand I need to use the parent_link argument. But I get this error when I use it: websites.Text: (models.E015) 'ordering' refers to the non-existent field 'position'. I've tried various field names such as websitecontentitem_ptr, websitecontentitem_ptr_id etc but no luck. Anything identifiable here I'm doing wrong here? -
django-tables2 add dynamic columns to table class
My general question is: can I use the data stored in a HStoreField (Django 1.8.9) to generate columns dynamically for an existing Table class of django-tables2? As an example below, say I have a model: from django.contrib.postgres import fields as pgfields GameSession(models.Model): user = models.ForeignKey('profile.GamerProfile') game = models.ForeignKey('games.Game') last_achievement = models.ForeignKey('games.Achievement') extra_info = pgfields.HStoreField(null=True, blank=True) Now, say I have a table defined as: GameSessionTable(tables.Table): class Meta(BaseMetaTable): model = GameSession fields = [] orderable=False id = tables.LinkColumn(accessor='id', verbose_name='Id', viewname='reporting:session_stats', args=[A('id')], attrs={'a':{'target':'_blank'}}) started = DateTimeColumn(accessor='startdata.when_started', verbose_name='Started') stopped = DateTimeColumn(accessor='stopdata.when_stopped', verbose_name='Stopped') game_name = tables.LinkColumn(accessor='game.name', verbose_name='Game name', viewname='reporting:game_stats', args=[A('mainjob.id')], attrs={'a':{'target':'_blank'}}) I want to be able to add columns for each of the keys stored in the extra_info column for all of the GameSessions. I have tried to override the init() method of the GameSessionTable class, where I have access to the queryset, then make a set of all the keys of my GameSession objects, then add them to self, however that doesn't seem to work. Code below: def __init__(self, data, *args, **kwargs): super(GameSessionTable, self).__init__(data, *args, **kwargs) if data: extra_cols=[] # just to be sure, check that the model has the extra_info HStore field if data.model._meta.get_field('extra_info'): extra_cols = list(set([item for q in data if q.extra_info … -
DRF:Apply order by in nested Searilizer
Nested Representation: [ { 'id': 1, 'phone': 1023456789 'stats': { 'created': 1-09-2016, 'result': 'fail', ... }, }, { 'id': 2, 'phone': 1023456789 'stats': { 'created': 13-09-2016, 'result': 'pass', }, }, ] I have 3 serializers: class abcSerializer(serializers.ModelSerializer): created=Field(source='created') result = Field(source='result') class Meta: model = abc fields = ('created','result') order_by = ['-created'] class defSerializer(serializers.ModelSerializer): created=Field(source='created') result = Field(source='result') class Meta: model = def fields =('created','result') order_by = ['-created'] class mainSerializer(serializers.ModelSerializer): obj1 = abcSerializer() obj2 = defSerializer() class Meta: model = main ''' main is model class.Contains fields as id,phone,stat ''' fields = ('obj1','obj2') In views.py Accessing those serialized data: data = main.objects.filter(id=111) serializer = mainSerializer(data) return Response(record) I want sort the searilized data on basis of field 'created' on descending order. tried some SO link & then github link as link with no success. github link is similar to my problem but it didn't address my solution. Can some one point some solution to my problem!! -
Django filter OR .filter(x=1,y=2) like Django Docu
So this works: from django.db.models import Q Item.objects.filter(Q(creator=owner) | Q(moderated=False)) But why does this not work according to https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships Item.objects.filter(creator=owner, moderated=False) It acts like Item.objects.filter(creator=owner).filter(moderated=False) -
Is it possible to limit mocked function calls count?
I have encountered a problem when I write a unit test. This is a chunck from an unit test file: main.obj = MainObj.objects.create(short_url="a1b2c3") with unittest.mock.patch('prj.apps.app.models.base.generate_url_string', return_value="a1b2c3") as mocked_generate_url_string: obj.generate_short_url() This is a chunk of code from the file 'prj.apps.app.models.base' (file which imports function 'generate_url_string' which is being mocked): from ..utils import generate_url_string ..................... def generate_short_url(self): short_url = generate_url_string() while MainObj.objects.filter(short_url=short_url).count(): short_url = generate_url_string() return short_url I want to show in the unit test that the function 'generate_short_url' doesn't return repeated values if some objects in the system have similar short_urls. I mocked 'generate_url_string' with predefined return result for this purpose. The problem is that I couldn't limit number of calls of mocked function with this value, and as a result the code goes to an infinite loop. I would like to call my function with predefined result ('a1b2c3') only once. After that I want function to work as usual. Something like this: with unittest.mock.patch('prj.apps.app.models.base.generate_url_string', return_value="a1b2c3", times_to_call=1) as mocked_generate_url_string: obj.generate_short_url() But I see no any attributes like 'times_to_call' in a mocking library. Is there any way to handle that ? -
Cannot resolve keyword 'content_type' into field
I'm trying to use generic relations, my model looks like this: class Post(models.Model): # Identifiers user = models.ForeignKey(User, unique=False, related_name = 'posts') # Resource resource_type = models.ForeignKey(ContentType) resource_id = models.PositiveIntegerField() resource = GenericForeignKey('resource_type', 'resource_id') # Other date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True) class Meta: unique_together = ('resource_type', 'resource_id',) However, when on my resource I try to get the Post object, using 'SomeResource.posts' the following exception occurs: Cannot resolve keyword 'content_type' into field. Choices are: date_created, id, resource, resource_id, resource_type, resource_type_id, user, user_id Why is it looking for content_type when I explicitly named it resource_type on my GenericForeignKey? -
How to get CSS button added to Django admin to actually trigger logic
The 'Export' button I've added to my Django admin won't hook to my view even though the button itself shows up on screen. I've used several tutorials on SO to get the button visible - BUT it just does nothing when clicked, reloads the same page. I have a feeling that the structure of how I have it set up is wrong or that I'm not passing it the data from my database correctly. I'm assuming there are errors here that I am missing? How do I pass my export function the data that is already in my database? I figure I have to do a queryset but I'm not sure I'm actually getting the data or putting it in the right place. The button is intended to let the user export all data that has already been stored (e.g. all records of a particular type) to an Excel file. My app > css > categories.css (to create the button) .btn{ border: solid 1px #000; background: #eee; border-radius: 3px; margin-top: 20px; float: right; text-align: right; } Changes I made to the change_list.html template to get my button to be visible (I put it after the search bar on admin change …