Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 1.8 - QuerySet generated include columns not in values
I am trying to get a queryset displaying the average rate of comments. The query looks pretty simple - although Django seems to add automatically an extra field created_at in the generated group by statement. Is there any way to remove it from the group by clause ? Is it there because of the default order by defined in the META class of the models ? GROUP BY "authentification_antenne"."name", "review"."created_at" instead of just GROUP BY "authentification_antenne"."name" Review.objects.select_related( 'appartement__antenne').values('appartement__antenne__name').annotate(average_rating=Avg('rating')).query SELECT "authentification_antenne"."name", AVG("review"."rating") AS "average_rating" FROM "review" LEFT OUTER JOIN "staffing_appartement" ON ( "review"."appartement_id" = "staffing_appartement"."numero_contrat" ) LEFT OUTER JOIN "authentification_antenne" ON ( "staffing_appartement"."antenne_id" = "authentification_antenne"."id" ) GROUP BY "authentification_antenne"."name", "review"."created_at" ORDER BY "review"."created_at" DESC And the models.py class Review(models.Model): guest = models.ForeignKey(Guest) comment = models.TextField() rating = models.IntegerField(null=True) created_at = models.DateTimeField() imported_at = models.DateTimeField(auto_now=True) appartement = models.ForeignKey('staffing.appartement', null=True) class Meta: ordering = ['-created_at'] Thank you -
Django User password not getting hashed in custom User
I am currently implementing the authentication for a Django application, I am writing. Following code of the Thinkster Django course, I implemented the whole registration process, but I cannot login, because the password is not getting hashed, when registering a User. Here is my custom User model and the create_user function. def create_user(self, username, email, password=None): if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email address.') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(db_index=True, max_length=255, unique=True) email = models.EmailField(db_index=True, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() As you can see, I am explicitly calling the set_password function and I cannot find out, why it does not get properly executed. My Serializer, where I create the user is as follows: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) Please note that instead of return User.objects.create_user(**validated_data) I also tried doing return get_user_model().objects.create_user(**validated_data), as it was a suggestion at another … -
Cannot resolve keyword 'available' into field. Choices are: id
Here is the relevant part of my view def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request,'list.html',{'category': category, 'categories': categories,'products': products}) This is the relevant part of my models I think the problem would be from Here class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name Here is the relevant part of my traceback error FieldError at / Cannot resolve keyword 'available' into field. Choices are: id -
Update to 1.11: TypeError build_attrs() takes at most 2 arguments (3 given)
I a updating from 1.10.7 to 1.11.0 and I am getting the following error when viewing a form. I cannot fathom what is wrong with my form at all. Other forms work in the same way. I suspect that it could be an interaction with either select2 or markdownx but there is no indication that those are incompatible with 1.11. How can I debug this further? File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/usr/repos/intranet/isotek_intranet_site/order_book/views.py" in create 161. return render(request, 'order_book/create.html', context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader_tags.py" in render 177. return compiled_parent._render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in … -
Pytest fixtures interfering with each other
I am using Pytest with Django and came to this weird behaviour. I have two user fixtures, one being a superset of the other. Everything works as expected until I use both fixtures in the same test case. Fixtures: @pytest.fixture def user_without_password(): return User.objects.create_user(username=fake.name(), email=fake.email()) @pytest.fixture def user_with_password(user_without_password): user = user_without_password user.set_password('topsecret') user.save() return user Tests @pytest.mark.django_db() def test_without_pass(user_without_password): assert not user_without_password.has_usable_password() @pytest.mark.django_db() def test_with_pass(user_with_password): assert user_with_password.has_usable_password() # THIS FAILS!! @pytest.mark.django_db() def test_both(user_with_password, user_without_password): assert not user_without_password.has_usable_password() assert user_with_password.has_usable_password() The last test doesn't work since apparently user_with_password and user_without_password end up being the same object. Is there a way to ensure that they are new objects each time? This behavior feels counter-intuitive. -
django: compare and decrement without race conditions
I'm trying to compare a value and decrement it without race conditions. The following code is not correct because "stock" could be modified in both the conditional and the assignment. if product.stock >= requested: product.stock -= requested product.save() else: raise Error("Product not available") I read about F() expressions to prevent race conditions. if product.stock >= requested: product.stock = F('stock') - requested product.save() else: raise Error("Product not available") This is better, but the conditional is still prone to race conditions. How can I fix this? -
user_passes_test: raise exception if user does not pass
I am trying to define a decorator to check if the user has admin certain privileges: def admin_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: u.is_staff and u.is_authenticated() and not Association.objects.filter(admins=u).exists(), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator The aim is to use this throught the views. Particularly, I am using it in a class-based view: class MyCBV(CreateView): @method_decorator(admin_required) def dispatch(self, request, *args, **kwargs): return super(MyCBV, self).dispatch(request, *args, **kwargs) The problem is that this view is loaded via AJAX, so the redirect doesn't happen. Also, the HTTP status the view returns is success even when the user authentication fails, so the client (JS) has no way of telling when the action really succeeded or not. I usually have trouble understanding decorators and Django authentication, so my question is: how can I raise an exception (preferably the PermissionDenied exception) when the authentication decoration function fails? -
Uploading text file in server using django
I have a created a website which allows users to login by giving user name and password..Now i want to make an option which will allow the file from local machine to upload to a server.How can i do this? -
Can `auto_id` and `id_for_label` ever have different values?
Both {{ form.myfield.auto_id }} and {{ form.myfield.id_for_label }} have the same value. Usually it's "id_myfield". It is usually used to construct forms, so technically they should always be the same. <label for="{{ form.myfield.id_for_label }}">...</label> <input id="{{ form.myfield.auto_id }}" /> But I wonder why id_for_label even exists, because it just adds unnecessary overhead to something that can be done with only auto_id. Are there cases where the values are different? -
Django - making json object out of formset errors
I have the following code where I try to catch formset errors: if contact_phone_formset.is_valid(): contact_phone_formset.save() else: for dict in formset.errors: if dict: for field, error in dict: formset_errors.append({'field': field, 'error': error}) This code yields error ValueError: too many values to unpack (expected 2). formset.errors has the value <class 'list'>: [{}, {'field_name': ['Required field.']}] Any ideas? -
return user id django
I have a model field account_handler = models.ForeignKey(User, blank=True, null=True, related_name='handling_leads', on_delete=models.SET_NULL) Currently I'm doing something like this def get_queryset(self): user_id = User.objects.all() queryset = User.objects.filter(handling_leads__account_handler=user_id).distinct() return queryset and I've got some results just not what I was expected. How can I properly use this field and return a user_id? I have tried something like this User.objects.filter(handling_leads__account_handler=self.request.user.id).distinct() with out User.objects.all() but that was just returning an empty queryset. I'm trying to filter this so I can populate a table with user__first_name and user__last_name, I need user_id so I can redirect them to their individual page. controler for the datatable: app = angular.module 'statistics' app.controller 'SalesCommissionsListCtrl', ['$scope', '$compile', ($scope, $compile) -> $scope.init = ()-> fetchCommissionsList() fetchCommissionsList = ()-> $('#commissionsSalesList').DataTable({ createdRow: (row, data, index) -> $compile(row)($scope) sDom: 'lftip', processing: true, serverSide:true, searchDelay: 1000, orderMulti: false, pageLength: 10, ajax: { url: '/api/statistics/commissions/list/', data: (data)-> data.limit = data.length; data.offset = data.start; data.search = data.search['value']; if (data.order[0]['dir'] == 'asc') data.ordering = data.columns[data.order[0]['column']].name; else data.ordering = '-' + data.columns[data.order[0]['column']].name; return 0 dataFilter: (data) -> json = jQuery.parseJSON(data); json.recordsTotal = json.count; json.recordsFiltered = json.count; json.data = json.results; return JSON.stringify(json); } columns: [ { data: "username", name: "username__first_name, username__last_name", render: (data, type, row, meta)-> return '<a href="/statistics/commissions/sales/' + … -
Only two digits in year [duplicate]
This question is an exact duplicate of: Show events in a specific time range 1 answer Here is my url of my django app: url(r'^(?P<topic>/(?P<year>[0-9]{2})$' and I want to hav eyear in format 17 instead of 2017, so I tried with: year = datetime.date(int(self.kwargs['year2']), 7, 31) print year.strftime("%y-%m-%d") but I got an error: year=17 is before 1900; the datetime strftime() methods require year >= 1900 -
Custom Django management command not running with crontab
I have an app in a django website that looks like in the tutorial of this page django_documentation and it runs very well if I run the command: python manage.py closepoll.py After I installed Crontab and I put it in INSTALLED APPS in settings.py file. Also I put this line in my settings.py file: CRONJOBS = [ ('*/5 * * * *', 'django.core.management.call_command', ['closepoll']), ] To be able to run the script every 5 minutes. I add the cronjob through: python manage.py crontab add And it was added perfectly. After I restart the server but nothing is happening every 5 minutes. Do you know what I'm doing wrong? -
Homeform fields are not displaying properly
I'm trying to post the text in that CharField of homeform is not displaying properly.I have created seperate app as home and charfield inside homeform is not displaying properly home/views.py from django.views.generic import TemplateView from django.shortcuts import render, redirect from home.forms import HomeForm from home.models import Post def status(request): context = {} template = 'po.html' return render(request, template, context) class HomeView(TemplateView): template_name = 'status.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('status') # args = {'form': form, 'text': text} # return render(request, self.template_name, args) forms.py from django import forms from home.models import Post class HomeForm(forms.ModelForm): post = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Write a...' } )) class Meta: model = Post fields = ('post',) models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) home/status.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1>Status</h1> <form method="post"> {% csrf_token %} {{ form.post }} <br> <button type="submit">Submit</button> </form> <h2>{{ text }}</h2> {% for … -
splitting query list items in a new pdf page
I'm calling a list to be printed in my pdf file but the list items is too long(see img) pdf result How can i break the list after 50 items and show the rest items in a new page? Here is my code: enter image description here [enter image description here][3] -
Converting a package from python2 to python3
I've downloaded the Trumbowyg WYSIWYG editor: http://alex-d.github.io/Trumbowyg/ as well as django-trumbowyg for integrating it with django: https://github.com/sandino/django-trumbowyg However django-trumbowyg is written for python2, whereas my app runs on python3. Is it difficult to convert this package to python3? Or is it just a matter of making a few minor changes? How would I go about it? -
cookies not writtent even when I receive set-cookie response header
Browser is ignoring reponse cookies (csrftoken + seesionid). document.cookie() returns empty string and chrome developer tool show this site has no cookies How to solve this ? FRONT : Angular 2 (localhost:4200) Back : Django/DRF (localhost:8000) Login route : [post] /login Response header : Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://localhost:4200 Allow:POST, OPTIONS Date:Wed, 05 Apr 2017 07:38:24 GMT Server:WSGIServer/0.2 CPython/3.5.2 Set-Cookie:sessionid=d5v1mri12bniyvyqqt55ar8mfl9mr2jk; expires=Wed, 19-Apr-2017 07:38:24 GMT; HttpOnly; Max-Age=1209600; Path=/ Set-Cookie:csrftoken=5PcTF8aQ1O79gdrylZcGchnmKyRy6zwS3kL2jR5dY2CMdjPfEYyhkoJjOzsDZuvj; expires=Wed, 04-Apr-2018 07:38:24 GMT; Max-Age=31449600; Path=/ Vary:Accept, Cookie, Origin X-Frame-Options:SAMEORIGIN -
django static files not served to HTML-EMail template
I am running Django on a local Vagrant arch machine on a Win7 host. I set up my environment variables from Django in a .env file. In my app all static files are served correctly and everything works as it should. Problem: I am not able to serve my static files (images) in my html-email templates. Until now i served them as hardcoded filer URL's and i want to change that. I am passing BASE_URL BASE_URL=http://127.0.0.1:8001, which is proved working, as context to the template and loading static as usual: {% load static %} and calling it in HTML tag: <img src="{{BASE_URL}}{% static 'img/my_image.png' %}"> In the received email the URL of the image is http://127.0.0.1:8001/static/img/my_image.png which looks right but triggers a 404. What am i missing?? (Please dont ask me if the image is in the corresponding folder, it is ;) -
Python - displaying images in Django
I'm new with django and i'm trying to create project, but i got a problem with displaying images. I have a html table with checkboxes and after selecting an object i wish to display image on next page but i can only get broken image. i can display image this way : <img src="{{ MEDIA_URL }}bird.png" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> but then obviously this image will be shown in every object. but in this way what i use in index page it wont find any images: <img src="{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> this is my views.py def selected(request): tags = request.GET.getlist('selected') return render(request, 'tag/selected.html', {'all_tags':tags}) if i use: def selected(request): tags = request.GET.getlist('selected') all_tags = Tags.objects.all return render(request, 'tag/selected.html', {'tags':tags, 'all_tags':all_tags}) then it will find the images but then it will also show all the images even if i select only one. this has been my problem for awhile now so please if anyone could help me i would really appreciate that -
Behave-django Server running
When I configure my environment.py with: def before_all(context): context.browser = Browser() In steps, when access any page with: contex.browser.visit(contex.browser.visit(context.get_url)) Return error 500 server. I think that have something else to configure in behave-django to run a project test when I run behave tests. Note.: I using splinter, behave-django, chromedriver and phantomjs. -
Custom delete method for
Django 1.10.4 I want to use a custom delete method for deleting bunches of my models. list_.models.py class MyQuerySet(models.query.QuerySet): def delete(self): print("deleted") pdb.set_trace() raise SuspiciousFileOperation class NoDeleteManager(models.Manager): def get_query_set(self): return MyQuerySet(self.model, using=self._db) class MyModel(models.Model): objects = NoDeleteManager() In the shell: >>> from list_.models import MyModel >>> m = MyModel.objects.create() >>> m <MyModel: MyModel object> >>> m.id 1 >>> ml = MyModel.objects.all() >>> ml <QuerySet [<MyModel: MyModel object>]> >>> ml.delete() (1, {'list_.MyModel': 1}) >>> ml <QuerySet []> Well, all objects from the list deleted without any sign. This means that my custom manager somehow was not applied. Could you help me understand where my fault is? -
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found.
i have a problem loading the index page , and i have tried for two days but it seem to be not working for me . error : Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] my invoices urls: from django.conf.urls import url, include from django.conf import settings from . import views app_name = 'invoices' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^new/$', views.new, name='new'), ] my base urls, urlpatterns = [ url(r'^invoices/', include('invoices.urls', namespace='invoices')), ] invoices.html {% extends "base.html" %} {% load i18n %} {% block title %}{%trans "Invoices" %}{% endblock %} {% block content %} <table> {% for invoiceheader in invoices %} <tr> <td> <label>{%trans "Number" %}:</label> {% if invoiceheader.number %} {{ invoiceheader.number }} {% else %} - {% endif %} </td> <td> <label>{%trans "Date Issue" %}:</label> {% if invoiceheader.dateissue %} {{ invoiceheader.dateissue }} {% else %} - {% endif %} </td> <td> <label>{%trans "Custumer" %}:</label>{{ invoiceheader.customer_name }}</label> </td> <td> <a href="{% url 'invoices:status' invoiceheader.id%}">{%trans "Status" %}</a> {{ invoiceheader.get_status_display }} </td> {% if invoiceheader.status == 'I' or invoiceheader.status == 'P' %} <td> <label class="getitinfo" findrandomnumber="{{ invoiceheader.findrandomnumber }}" number="{{ invoiceheader.number }}"> {%trans "Get It" %} </label> </td> {% else %} <td>&nbsp;</td> {% … -
How to access local & session storage variable from HTML to Django and how to get in my app views.py?
Django version is - 1.10.5 Python 2.7.10 I'm beginner in Django. Assistance required. What i have done so far:- 1) I have already passing successfully local or session variables between HTML pages. My Questions are:- 1) Do i need to specify anything in HTML or Django to access local or session storage variables? 2) How do i get that local or session variables in my views.py? 3) Without models can i do this? because i don't want anything to store in database. Thanks in Advance -
Mysql not working with python 3.5 and django 1.9
I am trying to connect mysql db with django 1.9 and python version is 3.5. With database connection string I am getting the below error. If I comment out the database connection string the site is loading fine. Can anybody tell what is wrong in this. [Wed Apr 05 07:01:08.287609 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] mod_wsgi (pid=29791): Target WSGI script '/home/abhadran/test/mysite/mysite/wsgi.py' cannot be loaded as Python module. [Wed Apr 05 07:01:08.287675 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] mod_wsgi (pid=29791): Exception occurred processing WSGI script '/home/abhadran/test/mysite/mysite/wsgi.py'. [Wed Apr 05 07:01:08.287705 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] Traceback (most recent call last): [Wed Apr 05 07:01:08.287740 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/test/mysite/mysite/wsgi.py", line 20, in <module> [Wed Apr 05 07:01:08.287787 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] application = get_wsgi_application() [Wed Apr 05 07:01:08.287798 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Wed Apr 05 07:01:08.290733 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] django.setup(set_prefix=False) [Wed Apr 05 07:01:08.290756 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup [Wed Apr 05 07:01:08.290779 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] apps.populate(settings.INSTALLED_APPS) [Wed Apr 05 07:01:08.290790 2017] [wsgi:error] [pid 29791] [remote 173.1.101.95:52570] File "/home/abhadran/myenv/lib/python3.6/site-packages/django/apps/registry.py", line 78, in populate … -
ModuleNotFoundError in Django
I have a form with a submit button that uploads 2 files, one python file(info.py) and a image file(eg "img1"). In views.py, I used this statement " from media.info import * " to import the files from the media directory in Django where my uploaded files resides so that I can use the methods etc. However, when I run the server, there is ModuleNotFoundError: No module named 'media.info'. It seems that the server realizes that I do not have the info.py file yet. is there any way to solve this? any help will be greatly appreciated.