Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - safe to set ALLOWED_HOSTS to * behind two proxies?
I'm running Docker to make my Django builds. I run into a problem when I want to run manage.py migrate or collectstatic during the build process because the build has a random hostname which is not in ALLOWED_HOSTS. The docker sits behind two layers of Nginx, does that mean it's safe to set ALLOWED_HOSTS to ['*'] so that my manage.py tasks will run? Or is there a better way to run management commands during a docker build? Django 1.11.1 on Python 3.6 . -
'bool' object has no attribute 'utcoffset'
In my admin, I am getting errors for only one class, 'bool' object has no attribute 'utcoffset'. I have looked at a few other similar questions and have been unable to solve it. Any ideas on how to fix it? The traceback is below the class. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', verbose_name='Категория') name = models.CharField(max_length=200, db_index=True, verbose_name='Название') slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d/', blank=True, verbose_name='Изображение товара') description = models.TextField(blank=True, verbose_name='Описание') price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') stock = models.PositiveIntegerField(verbose_name='На складе') available = models.BooleanField(default=True, verbose_name='Доступен') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(default=True) class Meta: ordering = ['name'] verbose_name = 'Товар' verbose_name_plural = 'Товары' index_together = [ ['id', 'slug'] ] def __str__(self): return self.name AttributeError at /admin/shop/product/add/ 'bool' object has no attribute 'utcoffset' Request Method: GET Request URL: http://127.0.0.1:8000/admin/shop/product/add/ Django Version: 1.9.1 Exception Type: AttributeError Exception Value: 'bool' object has no attribute 'utcoffset' Exception Location: E:\internetshopproject\python_shop_env\lib\site-packages\django\utils\timezone.py in is_aware, line 340 Python Executable: E:\internetshopproject\python_shop_env\Scripts\python.exe Python Version: 3.6.0 Python Path: ['E:\\internetshopproject\\my_shop', 'E:\\internetshopproject\\python_shop_env\\Scripts\\python36.zip', 'E:\\internetshopproject\\python_shop_env\\DLLs', 'E:\\internetshopproject\\python_shop_env\\lib', 'E:\\internetshopproject\\python_shop_env\\Scripts', 'c:\\anaconda3\\Lib', 'c:\\anaconda3\\DLLs', 'E:\\internetshopproject\\python_shop_env', 'E:\\internetshopproject\\python_shop_env\\lib\\site-packages'] Server time: Thu, 11 May 2017 20:09:54 +0300 Error during template rendering In template E:\internetshopproject\python_shop_env\lib\site-packages\django\contrib\admin\templates\admin\change_form.html, error at line 33 'bool' object has no attribute 'utcoffset' 23 {% endblock %} 24 {% endif %} 25 26 … -
Django: Formular for OneToOneField children
I have build an incremental user-model in my app, that can be extended by the users as they need. Idea: A user is registered with the standard-django User-class. Then he shall be able to type in his general info like adress, etc. in the Account-class. Afterwards he shall be able to activate sub-classes (class Sportler, ...) that refer to class Account. I don't know how to make the formulars. models.py from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Sportler(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) ... -
django-pyodbc and calling a stored procedure
I'm testing my code on Windows 10. I have a Django application that needs to call a stored procedure on a remote SQL Server database. Here's the DATABASES snippet from settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', 'HOST': 'mycompany.com', 'PORT': '3306', 'USER': 'user', 'PASSWORD': 'pw', }, 'ss': { 'ENGINE': 'django_pyodbc', 'NAME': 'db2', 'HOST': 'myserver\SQLEXPRESS', 'USER': 'myuser', 'PASSWORD': 'mypw', 'PORT': '1433', # 'DRIVER': 'SQL Server', 'OPTIONS': { 'driver_supports_utf8': True, 'host_is_server': True, # must be True for remote db 'autocommit': True, 'unicode_results': True, 'extra_params': 'tds_version=8.0', }, }, } Here's a code snippet from my view: cursor = connections['ss'].cursor() cursor.execute("{call dbo.mysproc(?)}", (id)) When I execute the cursor.execute statement I get this error: django.db.utils.DatabaseError: ('The SQL contains 1 parameter markers, but 36 parameters were supplied', 'HY000') My parameter, id, is a GUID. Thoughts? -
Django QS cant solve basic case?
I'm sure this is has been asked/answered before, but there is no obvious solution or directly comparable situation I could find; Given ParentModel, and RelatedToParentModel how do I generate a values queryset that details the number of related_to_parent_models per parent_model in ParentModel.objects.all() where related_to_parent_model.some_field == 0? Getting a values queryset for the count is trivial: ParentModel.objects.annotate( my_count = Count('related_to_parent_models') ).values('pk', 'related_to_parents__some_field', 'my_count') But when I try to throw a filter in there, such as .filter(related_to_parents__some_field = 0) it doesn't exactly remove every result where it evaluates to true, it removes only the sets of results for each ParentModel where it's never true, but keeps all the results for ParentModels where it's at least sometimes true. Also, even if I just iterate through the list and filter it myself after the query, some of the numbers are crazy and don't make sense. I'm not sure what I'm doing wrong. I'm on Django 1.9 -
What is include() in python? How is it different from import?
I recently started with django and in one of the tutorials I came across the following piece of code : urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] What does that include statement do -
Set creator automatically with DjangoRestFramework
I have a model with a creator field. I want this field to be initialized to the person that created the model instance and not be modifyable later on. The creator field looks like this: creator = models.ForeignKey(User) And in the DRF HyperlinkedModelSerializer I have this: read_only_fields = ('creator',) Now the problem is I of course can't create new instances anymore since the creator field is not set. how can I achieve that? One possible solution seems to be this def create(self, validated_data): validated_data['creator'] = self.context['request'].user return models.MyModel.objects.create(**validated_data) Is this the dry way to do it? -
Why my image is not readable after uploaded on the Django Rest Framework?
I am newbie on Django and I would like to implement a request that allow to make upload file. I wrote some code for this, but when I opened the file in local, my computer says it may be damaged. I don't understand why because the size file is the same to another when i sent with postman. here is my code : view.py def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class FileUploadView(APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, format="png"): file_obj = request.data['file'] handle_uploaded_file(file_obj) return Response(filename, status.HTTP_201_CREATED) -
Data returning None in Django with appended Select Field in JS
I have a select field with a drop-down list that I append in Javascript. But even though the field is populated, my clean() method returns None... and so my form doesn't validate etc. class MY_MODEL(models.Model): date = models.DateField(null=True, blank=True) description = models.CharField(max_length=150, null=True, blank=True) def __unicode__ (self): return self.description or u'' class MY_MODELForm(forms.ModelForm): class Meta: model = MY_MODEL fields = ['date', 'description',] widgets = { 'description': forms.TextInput( attrs={'required': False, 'placeholder': 'Description', 'class': 'format-form'} ), 'date': forms.Select( attrs={'required': False, 'class': 'format-form'} ), } def clean(self): cleaned_data = super(MY_MODELForm, self).clean() description = cleaned_data.get("description", None) date_worked = cleaned_data.get("date", None) #returns None even though populated... print date I append a list of dates based off some calcs (Which works fine). I am using JS for this because the list that is presented is interface dependant. Something like this... $( document ).ready(function() { //generate select options var dropDownOptions = ["Tuesday 2", "Wednesday 3"] var select = $("select[id$='date']") for ( j = 0; j < dropDownOptions.length; j++){ select.append($("<option></option>").attr("value", dropDownOptions[j]).text(dropDownOptions[j])); } }); All the appending and everything works fine... but my cleaned_data.get('date_worked') is returning None when something is selected something from the drop down.... ? Thanks -
Django assert post_save signal called
I'm trying to assert that a post_save signal receiver is called when an instance of my Client model is saved. The signal receiver looks as follow: # reports/signals.py @receiver(post_save, sender=Client) def create_client_draft(sender, instance=None, created=False, **kwargs): """Guarantees a DraftSchedule exists for each Client post save""" print('called') # Log to stdout when called if created and not kwargs.get('raw', False): DraftSchedule.objects.get_or_create(client=instance) I've set up a test that looks like this @pytest.mark.django_db @patch('reports.signals.create_client_draft') def test_auto_create_draftschedule_on_client_creation(mock_signal): client = mixer.blend(Client) # Creates a Client with random data assert mock_signal.call_count == 1 I would expect this test to pass since the called print statement appears in captured stdout when the test is ran. However, the test runner seems to think my mock function was never called at all. mock_signal = <MagicMock name='create_client_draft' id='139903470431088'> @pytest.mark.django_db @patch('reports.signals.create_client_draft') def test_auto_create_draftschedule_on_client_creation(mock_signal): client = mixer.blend(Client) > assert mock_signal.call_count == 1 E AssertionError: assert 0 == 1 E + where 0 = <MagicMock name='create_client_draft' id='139903470431088'>.call_count reports/tests/test_signals.py:36: AssertionError ---------------------------------------------------------------------------------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------------------------------------------------------------------------------- called The print statement seems to suggest that the function was called during the test, whereas the test assertion suggests otherwise. Am I missing something obvious here with the mocking library? -
Django Rest Framework and django.contrib messages
How can I integrate calls to DRF Generic Views functions like perform_create, perform_update, perform_destroy so that the resulting response contains a message added by using django.contrib messages framework? so far i have this: def perform_destroy(self, instance): try: instance.remove() messages.success(self.request._request, 'Delete successful') except Exception as e: messages.error(self.request._request, e) the message appears correctly when the page is reloaded but I cannot access it directly with this function response. Thanks for any help -
Getting Error while installing Django into virtuslenv
virtual -p /usr/local/bin/python3 env 'virtual' is not recognized as an internal or external command, operable program or batch file. While installing using cmd generating this above error. please try to solve.As I am using python3 to use Django. Thank you. -
Django: display object related to user in admin interface [duplicate]
This question already has an answer here: Django - User, UserProfile, and Admin 3 answers Imagine this code: class UserProfile(LogModel): def __str__(self): return self.user.first_name + ' ' + self.user.last_name user = models.OneToOneField(User, related_name='profile') coachs = models.ManyToManyField(User, verbose_name=_('coachs'), related_name='athletes', blank=True) As you can see, the UserProfile model can have one or many coachs (related to User model). Therefore, the User model is related to UserProfile models through related_name 'athletes'. What I want to do is to display (read only is ok, no need to allow edition) the list of related UserProfile ('athletes') in my User admin page. -
Django and Celery - re-loading code into Celery after a change
If I make a change to tasks.py while celery is running, is there a mechanism by which it can re-load the updated code? or do I have to shut Celery down a re-load? I read celery had an --autoreload argument in older versions, but I can't find it in the current version: celery: error: unrecognized arguments: --autoreload -
Navigation menu does not working all pages
I am using Django with MPTTmodel. I created Category Model and added some parent category and child category. I am showing my navMenu on HomeView(TemplateView) no problem.. I created CategoryView(DetailView) for list my posts by categories(www.example.com/category/example) but i must add context for my navMenu in CategoryView. Will I must add context for navMenu in all page(about/contact/post/..) views ? Example at the bottom views.py class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['nodes'] = Category.objects.all() return context class CategoryView(DetailView): model = Category template_name = 'cat.html' context_object_name = 'cat' base.html {%include 'header.html' %} {% block content %} {% endblock %} header.html {% recursetree nodes %} <li><a href="">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} home.html and cat.html {% extends 'base.html' %} {% block content %} {% endblock %} -
How to create a custom filter template in the Django admin interface?
My goal is to put a custom input field in the filter list box on my Django interface. I found no way of doing this with standard tools so I want to create a new template for the filter box. In the official Django doc, there's this: It is possible to specify a custom template for rendering a list filter: class FilterWithCustomTemplate(admin.SimpleListFilter): template = "custom_template.html" See the default template provided by Django (admin/filter.html) for a concrete example. But no more details are given. How am I supposed to implement this? filter.html does not extend change_list.html and I don't know where I am supposed to put my new custom filter template (I tried in templates/admin/my_app_name with the rest of my other overriding templates but it doesn't work) How can I create a new template for my admin filter box ? -
Django Keep different session in different tabs
I have django app (1.6) where I want to be able open two tabs with different sessions. But now when I open first tab with form to write a post, and on second tab I switch to different tab I also have the same session in this tab, because I refresh session. Is the way to separate sessions? Thanks for any help. JS part of my code: setInterval(function () { Dajaxice.calendars.get_calendar_name(function(data){ $('#calendars_name').html(data.calendar); }); }, 10000); Python part of my code: @dajaxice_register def get_calendar_name(request): c = request.session["current_calendar"].name return simplejson.dumps({'calendar': c}) -
How create Multiple Select Box in Django?
I am tring to create Multiple Select Box field from Django Select 2 library as in the picture below? I used next code but it return simple select multiple widget. I think I forgot something to add. Where is my mistake? Can someone show me how create such field correctly? I use: django-select-2 version: 5.1.0 JQuery version: 3.1.1 forms.py: class ProductForm(forms.ModelForm): company = forms.ModelMultipleChoiceField(queryset=Company.objects.none()) class Meta: model = Product fields = ('company ',) widgets = { 'company': Select2MultipleWidget() } def __init__(self, all_companies, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['company'].queryset = all_companies -
Select frames whose items belonk to keepers 1 and 2
Django 1.11 class Frame(models.Model): pass class Item(models.Model): frame = models.ForeignKey(Frame, on_delete=models.PROTECT) keeper = models.ForeignKey(Person, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", blank=False, null=True, on_delete=models.PROTECT, verbose_name=_("Keeper")) This is a photo archive. There are frames, items and keepers of items. Now, I've got a string representing keepers. keeper_and_list = '1 2' I'd like to extract Frames whose items belong to keepers 1 AND 2. keeper_and_list = keeper_and_str.split() keeper_and_query = reduce(operator.and_,[Q(item__keeper__id=int(element)) for element in keeper_and_list]) queryset = queryset.filter(keeper_and_query) Result: <QuerySet []> It is wrong. It should be: <QuerySet [<Frame: 4: Michael's news>, <Frame: 7: Michael's news>]> As we can check: >>> Frame.objects.filter(item__keeper__id=1) <QuerySet [<Frame: 4: Michael's news>, <Frame: 7: Michael's news>]> >>> Frame.objects.filter(item__keeper__id=2) <QuerySet [<Frame: 4: Michael's news>, <Frame: 7: Michael's news>]> Could you give me a kick here? -
Add a field error in Django Rest Framework validate method?
In Django Rest Framework (and Django), traditionally we check fields in validate_<field> method, and make more global checks in validate method. However, look at this code snippet: def validate(self, data): # .... try: customer.activate(data['signup_code'], data['raw_password']) except BadCodeProvided: raise ValidationError(MSG_WRONG_ACTIVATION_CODE) except SomeOtherException: raise ValidationError(SOME_OTHER_MESSAGE) Here, I'm forced to use validatemethod because I'm using 2 fields for my validation (signup_code and raw_password). However, if an error occurs in a BadCodeProvided Exception, I know it's related to the signup_code field (and not the raw_password one) because of the exception raised here. In the snippet code above, thiw will create a "non_field_error". Question: is there a way in DRF to raise the same error but related to the "signup_code" field? (like it would be done in a validate_signup_code method). Thanks -
Django UpdateView crispy formset no request .post.data
I'm triyng to add formset with a django generic class UpdateView: view.py: class EntryUpdateView(UpdateView): template_name = 'rubrica_app/rubrica_form.html' model = Anagrafiche form_class=Entryform success_url = reverse_lazy('rubrica_app:rub_list') def get_context_data(self, **kwargs): data = super(EntryUpdateView, self).get_context_data(**kwargs) y= Contatti.objects.filter(anagrafica=self.kwargs['pk']) data['formsetctc'] = ContattiFormSet( queryset=y) return data forms.py: class Contattiform(forms.ModelForm): def __init__(self, *args, **kwargs): super(Contattiform, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit("submit", "Save")) self.helper.layout = Layout( ....) class Meta: model = Contatti from django.forms import modelformset_factory ContattiFormSet = modelformset_factory(Contatti, form=Contattiform, extra=2) template: {% load crispy_forms_tags %} {% crispy form %} <form method="post" action=""> {% for form in formsetctc %} {% crispy form form.helper %} {% endfor %} </form> But when i click the Save button in single form of formset not only he form in the formset, but the entire page is submitted. if I add a debug point and look at self.request.POST.data are there no data referred to formset. What am I missing? Data are correctly shown but can't be edited. -
could not understand foreign key and manytomany field in django
I know this is a very basic question. I am learning django and i see the most important part is ForeignKey field and ManyToManyField. They are used ubiquitously. Without understanding those two, a proper model cannot be designed. If i have to design a model with FK relation, i always have to see the example first and try to come with the solution. I cannot confidently design a model cause i have not understand this well. It would be great if someone make me understand so that the picture comes to my head what is FKField, how FKField and MTMField are generated in table with simple english(Language is one of the barrier for me to understand from the documentation). Here is the model for foreign key class Category(models.Model): name = models.CharField() class Product(models.Model): name = models.CharField() category = models.ForeignKeyField(Category, related_name="product") -
Django REST Framework: Purpose of CreateOnlyDefault
According to the Django REST Framework docs, CreateOnlyDefault can be used to only set a default argument during create operations. During updates the field is omitted. It takes a single argument, which is the default value or callable that should be used during create operations. How is this different from declaring read_only=True, default=<arg>, where <arg> is that single argument you would pass to CreateOnlyDefault? -
Error while loading zone.js and main.js file
I have a django(1.6.11) project running perfectly fine. I want to use it with Angular2. So, I have been following this example. I am getting the following error on localhost:8000 page. By the way it shows Cannot GET / in localhost:3000. Error: Zone$1http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:232:1 Zone$1http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:114:17 scheduleResolveOrReject/<@http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:502:78 Zone$1http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:265:1 Zone$1http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:154:21 drainMicroTaskQueue@http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:401:25 ZoneTask/this.invoke@http://localhost:8000/ng/node_modules/zone.js/dist/zone.js:339:25 Evaluating http://localhost:8000/ng/src/main.js Error loading http://localhost:8000/ng/src/main.js localhost:8000:25 Following a suggestion for a question on stackoverflow, I changed loading long-stack-trace-zone.js instead of zone.js in my index.html code. But this says, Zone is not defined. Is this some version compatibility issue? I am using npm 4.1.1 and node v4.8.3. Please do comment if I need to show any of my files. -
Django user roles
I m building a website in which I have 2 types of users. For each type of user I have a corresponding django application. I would like when I am logging into the website as type A user or type B user, to be redirected to the appropriate django app and not to be able to access the other application. For logging each user will have a corresponding form. What is the best approach for this case ?