Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - allowing specified user to modify certain fields
I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that. Here's the code sample: class Task(models.Model): creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE) target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() created = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField() priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL') progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED') is_finished = models.BooleanField(default=False) So I want to allow the target, to modify only progress and is_finished fields. I am using DjangoRestFramework, not sure if that will help. Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that. -
How to import rest_framework to public Django project?
i just wanted to publish my Django project but have the following problem: ImportError at / No module named rest_framework.views Request Method: GET Request URL: http://165.227.154.0/ Django Version: 1.8.7 Exception Type: ImportError Exception Value: No module named rest_framework.views Exception Location: /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Thu, 16 Nov 2017 19:30:11 +0000 If i run the project locally everything works. Now i have signed up at Digital Ocean and created a one click app. Started their server and uploaded all my files properly via FileZilla into the server directory. When I enter the IP adress into my browser I also get the reply: It worked! Congratulations on your first Django-powered page. But after I uploaded my files, installed the new apps and added the urls, I receive the Error from above. Apparently, the rest_framework module can not be imported and I don't know how to fix it. Is here someone who can help me? Thanks and kind regards Marcel -
Forward and Reverse Field Relationships in Django
The context is: I have a Match model where I want to store data for a football match. There are some fields are going to be common to all matches (not the value I mean the field name), such as season, local_team, away_team... But the stats of the match are going to differ (one match can have 2 goals and another one 0). My approach to building a common abstract (Django model) of Match is creating the class Stats (to store the actions) and the Class Action. So: Action will have fields --> minute, player, action(goal, red card...) Stats will have fields --> actions (Many to many field to store several actions) Match will have fields --> local, away, ref, stadium, stats (so all matches have 1 common field which is stats). The big question comes now, when I would like to give a proper name to actions and stats. Because a lot of actions and stats from different matches are going to be stored together, when de MatchAdminForm ask me for the stats of the game I want to know quickly which one corresponds, same when the StatsAdminForm ask me for the actions. The ideal for stats would be … -
Django fixture with all possible combinations?
I am trying to test a statistics function, which counts what type of objects I have in my database. For this I would like to create at least one instance of each possible combination of model fields. Random test data requires a lot of test objects to make sure all possible combinations are met. Here is a shortened example from one of my models: class Member(models.Model) is_active = models.BooleanField() name = models.CharField() balance = models.IntegerField() division = models.ForeignKey(Division, on_delete=models.CASCADE) Class Division(models.Model) name = models.CharField() This is how I'm doing it right now using django_dynamic_fixture: from django.test import TestCase from django_dynamic_fixture import G from members.models import Member class StatisticsTestCase(TestCase): def setUp(self): for is_active in [True, False]: for balance in [-100, 0, 100]: for division in Division.objects.all() G(Member, is_active=is_active, balance=balance, division=division) But this looks pretty bad and is hard to read. Is there a simpler way with better to read code to create all possible combinations of properties of an object? I'm open to different test data generators as long as they work nicely with Python 3 and Django. -
How to structure functional testing for a Django project
I would like to create functional tests to cover my Django project. It is a multipage form that accepts input on each page. The input on previous pages changes the content/options for the current pages. The testing is currently set up with Splinter and PhantomJS. I see two main ways to set this up. For each page, create an instance of that page using stored data and point Splinter towards that. Benefits Allows random access testing of any page in the app Can reuse unit test definitions to populate these synthetic pages Downsides Needs some kind of back end to be set up that Splinter can point to (At this point I have no idea how this would work, but it seems time consuming) Structure the testing so that it is done in order, with the test content of page 1 passed to page 2 Benefits Seems like it should just work out of the box Downsides Does not allow the tests to be run in an arbitrary order/only one at a time Would probably take longer to run Errors on earlier pages will affect later pages I've found many tutorials on how to do functional testing on a small … -
Login redirect to main domain using django-subdomains
My project is using django-subdomains and django-allauth to handle subdomains and auth system. It has a couple of subdomains: company1.project.com, company2.project.com Some of views are using @login_required decorator that redirects user to LOGIN_URL = '/login/' at settings.py Ex: user is at company1.project.com and calls view which redirects him to company1.project.com/login/ I need to redirect users to the project.com/login/ django-subdomains have tool reverse('login') which returns project.com/login/ if I do not pass subdomain argument, but I cannot use it in settings for LOGIN_URL because django apps are not loaded yet. -
How can I make a Wagtail Streamfield not required?
In the model below I want to make the bottom_content field in its entirety not required. How can I do this? class ServicePage(Page): top_content = StreamField(default_blocks + [ ('two_columns', TwoColumnBlock()), ('three_columns', ThreeColumnBlock()), ]) bottom_content = StreamField(default_blocks + [ ('two_columns', TwoColumnBlock()), ('three_columns', ThreeColumnBlock()), ]) search_fields = Page.search_fields + [ index.SearchField('top_content'), index.SearchField('bottom_content'), ] content_panels = Page.content_panels + [ StreamFieldPanel('top_content'), StreamFieldPanel('bottom_content'), InlinePanel('service_package', label='Packages') ] -
firstname and lastname not showing in django form
i'm trying to create a registration form with following information (firstname, lastname, email, password, password_confirm), however i do not get firstname and lastname. so far i only get username, password and password confirmation. what am i doing wrong in order to add the missing fields? forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, label='Fornavn', help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, label='Efternavn', help_text='Optional.') email = forms.EmailField(max_length=254, label='Email', help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') register.html {% for field in form %} <div class="form-group"> <label>{{ field.label }}</label> {% render_field field class="form-control" placeholder=field.help_text %} </div> {% endfor %} views.py def register(request): if request.user.is_authenticated(): return redirect('/account/') context = {} if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/account/') else: form = UserCreationForm() return render(request, 'register.html', {'form': form}) urls urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register') ] -
unsupported operand types in django
I am trying to get time delta between two objects obtained from "models.DateTimeField" gave the time in format "15:38:53:.000784" and "datetime.datetime.now" gave the time in format "15:38:53" . But when I tried to subtract the two values.I got an error saying "UNSUPPORTED OPERAND TYPES" Is there any suggestion I can follow to overcome the situation -
DjangoREST json parsing id instead of name
im new to Django (and to the DjangoREST framework)and and I've been struggling for a while with the following: I want for "especies" (apologies for the portuguese..) to be a vector with the names of the model Especies(scroll down pls) and instead this is giving me the id corresponding to the Especie. "especies": [ 13, 14 ] I want, for example: "especies": [ Z1, Z2 ] Thanks in advance! The JSON parsed: { "count": 1, "next": null, "previous": null, "results": [ { "codigo": "Z3", "area": "Z_tres", "especies": [ 13, 14 ], "id": 17 } ] } FROM THE DJANGO REST APP: views.py from django.shortcuts import render from species.models import Especie, Zona, EspecieZona from rest_framework import viewsets from rest.serializers import ZonaSerializer class ZonaViewSet(viewsets.ModelViewSet): queryset = Zona.objects.all() serializer_class = ZonaSerializer serializers.py from species.models import Zona from rest_framework import serializers class ZonaSerializer(serializers.ModelSerializer): class Meta: model = Zona fields = ('codigo', 'area', 'especies', 'id') The models.py on this app is empty. FROM THE MAIN APP models.py from django.db import models class Zona(models.Model): codigo = models.CharField(max_length=120) area = models.CharField(max_length=120) especies = models.ManyToManyField("Especie", blank=True) def __str__(self): return self.codigo class Especie(models.Model): nome = models.CharField(max_length=120) nome_latino = models.CharField(max_length=120) data_insercao = models.DateTimeField(auto_now_add=True) actualizacao = models.DateTimeField(auto_now=True) zonas = models.ManyToManyField("Zona",blank=True ) … -
Using comma-formatted numbers for DecimalField in Wagtail page admin
I have a request from a client to have page admin fields that they can add/read numbers into with commas such as 1,000,000. The Django model field to store the value would be a django.db.models.fields.DecimalField instance. From looking at the Django docs, this is something that’s supported by the django.forms.fields.DecimalField localized property, but I can’t find a way of enforcing it in the Wagtail admin, even when subclassing the Wagtail BaseFieldPanel __init__ function with self.bound_field.field.localize = True. -
Django - code won't enter 'process_request' in custom middleware
I'm using this example to create custom middleware, though I changed it a little bit. When debugging I see that the code enters that class, and get to the function definition, but it doesn't enter inside the function. I'm using django 1.10. This is my middleware class class GlobalThreadVarMiddleware(object): _threadmap = {} @classmethod def get_current_data_manager(cls): return cls._threadmap[_thread.get_ident()]['data_manager'] def process_request(self, request): self._threadmap[_thread.get_ident()] = {} self._threadmap[_thread.get_ident()]['data_manager'] = DataManager() def process_exception(self, request, exception): try: del self._threadmap[_thread.get_ident()] except KeyError: pass def process_response(self, request, response): try: del self._threadmap[_thread.get_ident()]['data_manager'] except KeyError: pass return response -
How do you display divs only on certain pages in Django?
I have a header that's being used as the base of all 3 of my pages, and loaded in like this; {% extends "base.html" %} {% load static %} {% block container %} ... {% endblock %} However, I only want to display certain menu options on one of the pages. Those are contained in a div, so my header looks somewhat like this: <header> <navbar> navbar items </navbar> <div> additional menu options </div> </header> Basically, I want the header/navbar to be displayed on every page, whereas I want the additional options div to appear on just one. Is there a way to make a conditional statement that tests what page I'm on, and only inserts the extra options if it's the right page? -
Getting 404 not found in application urls Django
I was just checking out django, and was trying a view to list the books by passing id as an argument to the URL books/urls.py. But getting 404 page not found error. I'm not getting whats wrong in the url when I typed this url in the browser: http://192.168.0.106:8000/books/list/21/ bookstore/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('books/', include("books.urls")) ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books' ] ... ... ... ROOT_URLCONF = 'bookstore.urls' books/urls.py urlpatterns = [ path('home/', create), path('list/(?P<id>\d+)', list_view), ] books/views.py def create(request): form = CreateForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Book Created") return redirect('/books/list', kwargs={id:instance.id}) return render(request, "home.html", {"form":form}) def list_view(request, id=None): books = Book.objects.filter(id=id) return render(request, "list.html", {"books": books}) Project Structure: ├── books │ ├── admin.py │ ├── forms.py │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── bookstore │ ├── __init__.py │ ├── settings.py │ ├── urls.py Here is the screenshot - EDIT - As addressed in the comments - Tried by appending \ in the books.urls but no luck :( -
twilio Record entire incoming call with gather
I am conducting a survey using Voice with Twilio. Part of that survey is to let the user give a voice feedback so i used Record at first. That was exactly what i needed since i could get the mp3 + the transcription. Problem is : i can't set the language to French so my transcription come in french, instead it is recorded and transcribed as english even though i speak french. So i decided to switch and use the Gather with the speech option which works quite well, the text comes back in french, but using that option, i can't get the mp3. So i decided that i would record the entire call, and use Gather which would have solved my problem, except you only get to set the record parameter to true when you initiate the call (outgoing call). My survey will be taken by incoming call 95% of the time.. I there any way to achieve this without having to use Record and use another API to do the transcription ? -
Django Framework: wrong confirmation email
So guys this is what I have in my reset_password_email.html file: > {{ protocol }}://{{ domain }}{% url 'accounts:reset_password_confirm'uidb64=uid token=token %} This is my urls.py file: url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'accounts/reset_password_confirm.html', 'post_reset_redirect': '/account/reset-password/complete/'}, name='password_reset_confirm'), And this is the E-Mail-Link that I reveive and doesn't work(example): http://127.0.0.1:8000/accounts/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/ If I change the link to account instead of accounts (see below), it works: http://127.0.0.1:8000/account/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/ -
Django - Model.py
Just a simple question. After I connect my django app to a remote database, I don't need to use Model.py to create tables in the database, then what is the function for Model.py at that moment? -
django count per column
I have a ORM like this from django.db import models, class MyObject(models.Model): class Meta: db_table = 'myobject' id = models.IntegerField(primary_key=True) name = models.CharField(max_length=48) status = models.CharField(max_length=48) Imagine I have the following entries 1 | foo | completed 2 | foo | completed 3 | bar | completed 4 | foo | failed What is the django ORM query that I have to make in order to get a queryset somewhat like the following [{'name': 'foo', 'status_count': 'completed: 2, failed: 1'}, {'name': 'bar', 'status_count': 'completed: 1'}] I started with the following but I don't know how to "merge" the two columns: from django.db.models import Count models.MyObject.objects.values( 'name', 'status' ).annotate(my_count=Count('id')) The goal of all this to get a table where I can show something like the following: Name | completed | failed foo | 2 | 1 bar | 1 | 0 -
How to use customize 404.html from decorator.py in django?
I have 4 types of user; client, officer, production_manager, service_manager. Therefore, I was creating 4 groups for each user. These users are my 4 apps in my project. In the corresponding views.py, in the methods, I'm using a decorator to give access only to a certain user, like this @group_required('client_group'). Here is my decorator method: check_group.py def group_required(*group_names): """Requires user membership in at least one of the groups passed in.""" def in_groups(u): if u.is_authenticated(): if bool(u.groups.filter(name__in=group_names)) | u.is_superuser: return True raise Http404 return user_passes_test(in_groups) Now if a client is logged in and trying to access a certain view from url , like, officer/password, then he cannot get access of that view. I am using raise HTTP404. This is the structure of my project: project |-app |-app |-app |-app |-user_group |--|--check_group.py |--|--404.html But the 404 page shown by django is its default. It's not taking my 404.html. Then in the check_group.py, I changed the code form my raise Http404 to template = loader.get_template("404.html") return HttpResponse(template.render()) But then I'm getting an error officer/password doesn't contain any template 404.html Then I put 404.html in the officer/template but still getting the same error. I want to use my customize 404.html rather than django's built-in … -
Dictionary update error in Django's ContextDict
Any idea where this error comes from? Python 3.4.2 Django 1.10.8 Method: POST Traceback as text (to find it if somebody else may search for it): ValueError: dictionary update sequence element #0 has length 0; 2 is required File "django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 215, in _get_response response = response.render() File "django/template/response.py", line 109, in render self.content = self.rendered_content File "django/template/response.py", line 86, in rendered_content content = template.render(context, self._request) File "django/template/backends/django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "django/template/context.py", line 267, in make_context context.push(original_context) File "django/template/context.py", line 59, in push return ContextDict(self, *dicts, **kwargs) File "django/template/context.py", line 18, in __init__ super(ContextDict, self).__init__(*args, **kwargs) -
django-tables2 'list' object has no attribute 'prefixed_order_by_field'
I'm working with Django-tables2. I can display a table using a model but can't get one to display using data. I know I have to have an order_by when using data. I'm not clear, on where and how. view def dictfetchall(cursor): desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def Users(request): data = dictfetchall(cursor) table = ProjectTable(data) RequestConfig(request, paginate={"per_page": 4}).configure(data) return render(request, 'JiraAdmin/index.html', {'table': table}) table.py class ProjectTable(tables.Table): name = tables.Column(verbose_name='Role') lead = tables.Column(verbose_name='Lead') display_name = tables.Column(verbose_name='User) class meta: attrs = {'class': 'paleblue'} attrs = {'class': 'table table-responsive', 'width': '100%'} template {% render_table ProjectTable %} -
Setting id columns with Django tables
I have a table: class Table(tables.Table): actions = tables.TemplateColumn(...) class Meta: model = SomeModel fields = ['field1', 'field2', 'field3', 'field4', 'field5', 'field6'] attrs = {"id": 'id', 'class': 'class'} I know that I an always change the row names: col_attrs = { 'data-id': "adsas" } which would make: <table> <tr id="adsas"> <td>.. <td>.. </tr> <tr id="adsas"> <td>.. <td>.. </tr> </table> But unfortunately, I didn't find a similar thing for rows, I want to have this: <table> <tr> <td id="0">.. <td id="1">.. </tr> <tr> <td id="0">.. <td id="1">.. </tr> </table> Can someone show me how can I make a similar structure, or at least what attr to use for it ? -
Django Form Error: Select a valid choice. ... is not one of the available choices
I am trying to create a dynamic choice field. I have a view that creates a list of tuples. The first value of the tuple is the primary key of the object ServiceWriter while the second value is the name of the ServiceWriter. The list then gets passed into the form class. When I make the selection and submit the page the form is decided to be not valid and the following form error is printed in the shell: "Select a valid choice. (First value of tuple. ie 1,2,3..) is not one of the available choices." forms.py class CreateAdvancedRO(forms.Form): service_writer = forms.ChoiceField() def __init__(self, writer_choices, *args, **kwargs): super(CreateAdvancedRO, self).__init__(*args, **kwargs) self.fields['service_writer'].choices = writer_choices self.helper = FormHelper() self.helper.form_id = 'id-create-advanced-ro' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Open Repair Order')) Note: I am not using a ModelForm. views.py class CreateAdvancedRO(View): form_class = CreateAdvancedRO writer_form = CreateServiceWriter add_line_form = AddJobLine def post(self, request): writer_choices = [] form = self.form_class(writer_choices, request.POST) print(form.errors) if form.is_valid(): '''Do something''' else: writer_choices = [] try: writers = ServiceWriter.objects.filter(user=request.user) for writer in writers: writer_choices.append((str(writer.id), writer.name)) except ObjectDoesNotExist: pass form = self.form_class(writer_choices, request.POST) writer_form = self.writer_form() add_line_form = self.add_line_form() return render(request, 'free/advanced_create.html', {'form': form, 'writer_form': wri 'add_line_form': add_line_form}) I have tried both … -
how to run python file on button click (html) in django
i want to execute .py file on button click (html) in django. function clickfun() { exec('home/hello.py'); } <button type="submit" onclick="clickfun()">Process</button> error: (index):10 Uncaught ReferenceError: exec is not defined at clickfun ((index):10) at HTMLButtonElement.onclick ((index):57) --------------uing AJAX-------------- function clickfun() { $.ajax({ url : 'http://127.0.0.1:8000/hello.py', type : 'POST', success : function (result) { console.log (result); // Here, you need to use response by PHP file. alert('a'); }, error : function () { console.log ('error'); alert('a1'); } }); } and while using ajax receiving following error: POST http://127.0.0.1:8000/hello.py 404 (Not Found) -
GET is going to incorrect URL
I'm learning the ropes of Django and perhaps i'm not understanding the URL routes correctly, but everything i've tried I can't get one form to send the GET to another URL. I would think it was more straight forward. I tried this suggestion, but apparently it wouldn't change the URL route or provide the correct request.POST.getlist: Ajax Call not being passed, POST.request shows as None. I am attempting to pass all of my check box selections to a new view. I have the view part working if I manually type the URL in and get the results in account/requestacess with request.GET.getlist, but when I hit my submit button the current URL is populated instead of where I want to go, which is account/requestaccess. my button is defined as: <button href="{% url 'requestaccess' %}" class="btn btn-primary" input type = "submit"> Request Access</button> my form is defined as: <form action "{% url 'requestaccess' %}" form method = "GET"> When I push the button depending on what is selected my profile URL is populated as such: http://127.0.0.1:8000/account/profile/?report_id=75&report_id=79&report_id=41&report_id=31 I want my /account/request URL to have the ?report_id= in it not the account/profile URL. My URL.py is defined as: url(r'^profile/$', views.profile, name='profile'), url(r'^requestaccess/$', views.requestaccess, name='requestaccess')