Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django quiz app model for multiple choice questions
I am creating quiz app in django, my django model for questions is like this, class Question(models.Model): questions = models.CharField(max_length=50, unique=True) choice1 = models.CharField(max_length=50, unique=True) choice2 = models.CharField(max_length=50, unique=True) choice3 = models.CharField(max_length=50, unique=True) choice4 = models.CharField(max_length=50, unique=True) correct_answer = models.CharField(max_length=50, unique=True) is this fine or save the four options in postgres array or save the choices in separate table. -
How can I separate text from a query result in html?
I'm trying to display the result of a query in a HTML page on django. I'm getting the result expected but I would like to separate the information from a cell in 5 cells. For example: enter image description here. Since this is a table, I would like to dispose this like 9030101 | 'Registo....' | 165.0 | \65.0 | None. Sorry if the question is silly but I can't fix this. -
Require Log in with AnonymousUser in Django Rest Framework
I have a viewset API which getting Notification of User who get authenticate with Django JWT but I got error. Please take a look! Viewset: from api.notifications.models import Notification from rest_framework.generics import ( ListAPIView ) from api.notifications.serializers import ( NotificationListSerializer ) from api.pagination import NewFeedPagination from rest_framework.permissions import AllowAny from api.permissions import IsOwnerOrReadOnly class NotificationListAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = NotificationListSerializer ordering_fields = 'date' def get_queryset(self, *args, **kwargs): queryset_list = Notification.objects.filter(to_user=self.request.user) return queryset_list When It doesn't logged in, it came to error: int() argument must be a string or a number, not 'AnonymousUser'. How can I set up with AnonymousUser, URL will come to login page: localhost:8000/admin? -
How to include images from Django staticfiles to <div style="background: url('image.jpg')">
I am having trouble on including image to from Django static/images/image.jpg -
Export all fields of functions in export function to generate xlsx
I have some functions in models.py class. Currently there are all fields mentioned in export class. I want to export all fields of function rather then mentioning every particular field which increases my line of code. Is there a way I could do it? Below is the code sample of export function def export_xlsx(self, request, queryset): list_dict = [] idx = 0 for q in queryset: list_dict += [{}] list_dict[idx]['name'] = q.name list_dict[idx]['place'] = q.place list_dict[idx]['time'] = q.time list_dict[idx]['date'] = q.date list_dict[idx]['country'] = q.country list_dict[idx]['city'] = q.city idx += 1 h = [ 'name', 'place', 'time', 'date', 'country', 'city'] gen_xlsx("export_file", h, list_dict, request) return request -
django rest_framework attribute error
Django serializing / deserializing two values to one model field """AttributeError: 'Profile' object has no attribute 'latitude'""" I am applying the same codes as mentioned in above link but in django 1.11, for me it shows error, is there anything to modify in models.py?,with the same serializer -
dajngo get date format in template
I am new to django. In my template I need the current date as date format, while the following code returns string: <p>{% now "Y-m-d" as date %}</p> where I want the date in format of 2018-12-17 as a date not string. Is there anyway to do that? thnaks -
How to register a custom ModelAdmin for FlatPage
I'm reading through the flatpages app documentation. And I was to make some edit to the flatpages admin.py, as discussed here: How to add, change and delete flatpages But forgive me, where exactly in my project do I create and add the admin.py file? Do I create a flatpages directory and place the admin.py in there? That was my first try, and I didn't work. -
How to route to a specific function in a view from django template?
For example I have the following situation where a delete button has to be routed different depending upon who has clicked it, like if he's an admin display a message else go to the delete view. I thought I will place the function to send a message in detail generic view but how to call that function directly from template? {% if user_detail.status == 0 %} <button class="btn clearfix"><i class="icon-trash"></i>Cannot Delete Admin</button> {% else %} <a href="{% url "members:delete" userid=user_detail.pk %}" class="btn clearfix"><i class="icon-trash"></i>Delete User</a> {% endif %} The delete generic view is directly linked to the template, is there to display message in delete view before loading the template? -
Django session wizard redirecting to skipped step when submit form
I am using a session wizard view to capture data from around 10 forms. Everything is working fine. But when I select the go to step which takes me to the last form and after I submit the form from the last page, it is redirecting to the step where I have selected the skip button rather than submitting the form. Usually it takes us to the particular form if there exist any validation error in that form. I have checked whether there is any validation error showing up or getting from the back-end but there exist no such validation error. This is happening in every form when I skip that particular form. It would be great if someone give a helping hand to figure out what is actually happening. -
Pass Django list of strings to JS as an array
Goal: I want to pass list of strings in Django to template JS as an array of strings and get index for each string in the array. Problem: Javascript indexOf() is counting each character (e.g. letters, single quotes and brackets). My tries below are based on this, this and this. Code 1: I tried escapejs and safe filters, but indexOf() is returning 2 for the first item in the array (should be 0). #views.py list = [#utf-8 encoded strings] return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = "{{list|escapejs}}"; console.log(array.indexOf('{{obj}}')); #obj is item in list}); Code 2: Also tried json.dumps() with encode('utf8') or json.loads() but the problem persists. #views.py list = [#utf-8 encoded strings] list = json.dumps(list, ensure_ascii=False).encode('utf8') return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = "{{list}}"; console.log(array.indexOf('{{obj}}')); #obj is item in list}); -
Why can't login after change password using django.contrib.auth.views?
here is the link to my project: https://github.com/MariuszKorotko/Twitter/tree/master/twitter I'm working on simple application like 'Twitter'. Everything looks like working ok, but after change password and logout, can't login again. New password and old password doesn't work. I was looking for solution of this problem but without success. Can I ask for your help? A I'm not sure, but maybe problem is beacause of custom User model. Thanks for any help. twitter/urls.py from django.contrib.auth import views as auth_views url(r'^$', IndexView.as_view(), name='index'), url(r'^login/', auth_views.LoginView.as_view( template_name='registration/login_form.html'), name='login'), url(r'^logout/', auth_views.LogoutView.as_view( template_name='registration/logged_out.html'), name='logout'), url(r'^password_change/$', auth_views.PasswordChangeView.as_view( template_name='registration/password_change_form.html', success_url=reverse_lazy('twitter:password_change_done')), name="password_change"), url(r'^password_change/done/$', auth_views.PasswordChangeDoneView.as_view( template_name='registration/password_change_done.html'), name="password_change_done"), twitter/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set!') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a … -
Django. How can I edit JSONField (PostgreSQL 9.6) in standard Django admin?
My Django version is 1.11.8, Python 3.6.1 and PostgreSQL 9.6. I create Django model with JSONField(). For example, like this: from django.contrib.postgres.fields import JSONField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() And put some data: >>> Dog.objects.create(name='Rufus', data={ ... 'breed': 'labrador', ... 'owner': { ... 'name': 'Bob', ... 'other_pets': [{ ... 'name': 'Fishy', ... }], ... }, ... }) But how I can edit this JSON data in admin page? I mean, something like transform all key: value data to normal fields into Django Admin. For example: 'breed': 'labrador' ---transforms---> CharField(name='breed', ...) with value 'labrador' Some use cases and useful comments are welcome. -
Django cannot find pattern name when redirecting
I am workign on django project, i have modified the default django user model to employee's model using AbstractUser model. Now On their first login, i need to redirect employee's to change password page the Url for which is defined in the EmployeeAdmin - get_urls method. Also to override the default login behaviour i had to override the default AdminSite as shown below: admin.py class MyAdminSite(AdminSite): login_form = AdminLoginForm admin_site = HRMSAdminSite(name='My-admin') @admin.register(Employee, site=admin_site) class EmployeeAdmin(admin.ModelAdmin): def get_urls(self): return [ path( '<id>/password/', self.admin_site.admin_view(self.user_change_password), name='auth_user_password_change', ), ] + super().get_urls() def user_change_password(self, request, id, form_url=''): pass And on my AdminLoginForm i check for the first login of user: forms.py class AdminLoginForm(AuthenticationForm): def confirm_login_allowed(self, user): # user.last_login is blank if this is first login for this user if not user.last_login: return redirect('auth_user_password_change') However, when running the above code i get below error: Reverse for 'auth_user_password_change' not found. 'auth_user_password_change' is not a valid view function or pattern name. I dont know why django cannot find the named url i.e defined inside EmployeeAdmin's get_urls() method. -
Django model formsets fields become none after save
I am trying to make a model formset to generate a form for each object that has 'completed' boolean field False. I managed to render it, but everytime i'm trying to save, the page will refresh and for a reason all field's values become None. Ex: From this to this models.py class TranslatorTest(models.Model): data = models.ForeignKey(TranslatorData) language = models.ForeignKey(Language) type = models.ForeignKey(TextType, blank=True, null=True, default=None) question = models.TextField(blank=True) answer = models.TextField(blank=True) completed = models.BooleanField(default=False) forms.py class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseAuthorFormSet, self).__init__(*args, **kwargs) self.queryset = TranslatorTest.objects.filter(completed=False) TranslatorTestFormSet = modelformset_factory( TranslatorTest, fields=['question', 'answer', 'language', 'type'], widgets={ 'language': forms.Select(attrs={'class': 'form-control m-bootstrap-select m_selectpicker', 'required': 'false'}), }, formset=BaseAuthorFormSet) views.py def translator_test(request): data = dict() if request.method == "POST": formset = TranslatorTestFormSet(request.POST) if formset.is_valid(): for form in formset.forms: form.save() return redirect(reverse_lazy('core:index')) else: formset = TranslatorTestFormSet() data['formset'] = formset return render(request, 'core/translator_test.html', data) translator_test.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="m-portlet__body"> {% for form in formset.forms %} {{ form.id }} {{ formset.management_form }} {% for field in form.visible_fields %} <div class="form-group m-form__group row"> {% if field.name == 'question' %} {{ field.label }} {{ field.value }} {% elif field.name == 'language' %} {{ field.label }} {{ field.value }} {% elif field.name == 'type' %} … -
'pipenv install -r' is not working
Excuted this : 'pipenv install -r requirements/local.txt' D:\doc\jaeeongram> pipenv install -r requirements/local.txt Requirements file provided! Importing into Pipfile… Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Nothing happens here. (After 5min, ...., 1hour) The following is my Pipfile. [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] Django = "==1.10.8" django-environ = "==0.4.4" django-crispy-forms = "==1.7.0" django-model-utils = "==3.0.0" Pillow = "==4.3.0" "argon2_cffi" = "==16.3.0" django-allauth = "==0.34.0" awesome-slugify = "==1.6.5" pytz = "==2017.3" django-redis = "==4.8.0" redis = ">=2.10.5" coverage = "==4.4.2" django_coverage_plugin = "==1.5.0" Sphinx = "==1.6.5" django-extensions = "==1.9.8" Werkzeug = "==0.13" django-test-plus = "==1.0.21" factory_boy = "==2.9.2" django-debug-toolbar = "==1.9.1" ipdb = "==0.10.3" pytest-django = "==3.1.2" pytest-sugar = "==0.9.0" [dev-packages] [requires] python_version = "3.6" pipenv shell -> django-admin not found... How to resolve this problem? -
Expand static tree sidebar menu in django template with jQuery when new pages loads
I have a python+django app and the sidebar menu is defined in the base.html, which is extended by other dynamic pages, so let's call the sidebar tree menu static. Now, when I click a link in the sidebar, as the new pages loads, the new page has the sidebar all items collapse, which is not desirable. I want to make the link corresponding to current page highlighted(with "class=active") and its parent item expanded. My site is based on a free webpage template called "AdminLTE": https://github.com/almasaeed2010/AdminLTE and it has some code to handle the toggle/expand/collapse event, but does not solve the "remain-link-active-and-menu-open" problem, because on every page, the sidebar part is repeated and each corresponding link and its parent have their states(active and expanded) hard-coded. I want the sidebar menu "remembers" the state, by passing some arg in between calls, etc. The sidebar tree code is below: /* Tree() * ====== * Converts a nested list into a multilevel * tree view menu. * * @Usage: $('.my-menu').tree(options) * or add [data-widget="tree"] to the ul element * Pass any option as data-option="value" */ +function ($) { 'use strict' var DataKey = 'lte.tree' var Default = { animationSpeed: 500, accordion : true, followLink … -
Where should I specify the output_field kwarg in this complex query?
I wrote a little survey app. I have a query that causes an exception upon upgrade to Django 2.0: Expression contains mixed types. You must set output_field. Here's a few relationships necessary to understand the query (where --fk--> indicats a foreign key): response --fk--> question --fk--> survey response --fk--> person Here's my query: answered_surveys = SurveyResponse.objects.all()\ .values('fk_question__fk_survey__hash', 'fk_question__fk_survey__name')\ .annotate( nb_respondants = Count('fk_person', distinct=True), survey_name = F('fk_question__fk_survey__name'), survey_hash = F('fk_question__fk_survey__hash') )\ .annotate( completion=100*Count('id')/ (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')) ) It's fine up until the last annotate, but I don't know where to add the output_field kwarg since I only have F and Count models. Count outputs an IntegerField by definition, F complains if I try to add that kwarg. How do I fix this? -
Use inline formset in modleform django
this might be a simple question but I couldn't find the answer anywhere. I have a modelform which I use to update models (User model). now I want to add an inline formset to this form for some model (UserReports). I already tried: class UserModelForm(UserChangeForm, CrispyForm): reports = inlineformset_factory(User, Reports, fields=('text',)) class Meta: model = User fields = ("email", "first_name") which does not work. any ideas what am i doing wrong/ what might fix this? -
using csrf_token in django widget
I am trying to make a custom django widget with ajax. The ajax call requires csrf_token. I need to know how to pass the csrf_token to the widget html. # forms.py from django import forms from widgets import MyWidget class PenForm(forms.ModelForm): color = forms.CharField(widget=MyWidget) class Media: js = ( 'js/jquery-3.2.1.min.js', 'js/jquery-ui.min.js', ) css = { 'all': ( 'css/jquery-ui.min.css', ) } # widgets.py from django.forms.widgets import Widget from django.template import loader from django.utils.safestring import mark_safe class MyWidget(Widget): template_name = 'my_widget.html' def get_context(self, name, value, attrs={}): return {'widget': { 'name': name, 'value': value, 'attrs': attrs, 'csrf_token': '???' }} def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) Here is my widget html: <script> $( function() { $( "#autocomplete_{{ widget.name }}" ).autocomplete({ source: function( request, response ) { $.ajax( { url: "/get_colors", type: "post", dataType: "json", contentType: "application/json; charset=utf-8", headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: { term: request.term }, success: function( data ) { response( data ); } } ); }, minLength: 1, select: function( event, ui ) { log.debug( "Selected: " + ui.item.value + " , " + ui.item.id ); } } ); } ); </script> # admin.py @admin.register(Pen) class PenAdmin(admin.ModelAdmin): form = PenForm list_display = … -
Django Query Set is giving a type error
The django query set is giving me a type error when trying to do a foreign key lookup. The Django reverse look up is giving me this error Where Im trying to get the details of the applications made by the Candidate. I have given my models and views.py and attached all of my Trace of error so kindly help me! Views.py def candidateDetail(request,id=None): instance = get_object_or_404(CandidateRegister, id=id) applic = instance.applications_set.all() for i in applic: print(i) # Throwing an error here!! context = {"instance": instance,"applic":applic} return render(request,"candidatedetail.html",context) Models.py class Applications(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) jd = models.ForeignKey(JoDesc,on_delete=models.CASCADE) candidate = models.ForeignKey(CandidateRegister,on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now= False,auto_now_add=True) application_made_by = models.ForeignKey(User,on_delete=models.CASCADE) class Meta: unique_together = ('jd', 'candidate') def __str__(self): return '%s' % (self.application_made_by,self.jd) My Trace Environment: Request Method: GET Request URL: http://127.0.0.1:8000/candidateDetail/9467e007-23e8-4cc7-b256-5082cd1facbe/ Django Version: 2.0 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'new', 'crispy_forms', 'djutils'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/sskadit/Office/nlpondec2017/newenv/src/newproject/new/views.py" in candidateDetail 112. print(i) File "/Users/sskadit/Office/nlpondec2017/newenv/src/newproject/new/models.py" in __str__ … -
Unable to get request.FILES django
I am trying to upload a text file to my django backend, but my request.FILES is always empty. I am using axios to send the file and have followed the django requirement to have 'multipart/form-data' as content type of the request. What am I missing? On my app.js I send a post request via: onSubmit() { var formData = new FormData(); formData.append('reqtype', this.reqtype) formData.append('fileToUpload', this.uploadedFile) axios.post('/sreqtool/tc/', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) On the network request payload: ------WebKitFormBoundarymAnl54hGVTifZzwM Content-Disposition: form-data; name="reqtype" filebased ------WebKitFormBoundarymAnl54hGVTifZzwM Content-Disposition: form-data; name="fileToUpload" data:text/plain;base64,OTA1NTIzMzg2NQ0KOTE3NTAwMTU0Mg0KOTc3NDczNjcyNg0KMTIzNTQ2ODQ1Ng== ------WebKitFormBoundarymAnl54hGVTifZzwM-- In my views.py I have: @csrf_exempt def index(request): if request.method == 'POST': DLOG.info(request.POST) DLOG.info(request.FILES) form = ExtractForm(request.POST, request.FILES) if form.is_valid(): res = QueryManager.processRequest(request.user, form.cleaned_data) DLOG is my logger and the output of the dlog is: [2017-12-18 16:51:06,510] INFO views index: <QueryDict: {u'fileToUpload': [u'data:text/plain;base64,OTA1NTIzMzg2NQ0KOTE3NTAwMTU0Mg0KOTc3NDczNjcyNg0KMT IzNTQ2ODQ1Ng=='], u'reqtype': [u'filebased']}> [2017-12-18 16:51:06,512] INFO views index: <MultiValueDict: {}> -
How to run correct all test of each app in django (connection already closed)?
I have two django app: core and blog, each app have tests. my_project_name: ... core tests __init__.py test_views.py test_models.py test_forms.py test_api.py blog tests __init__.py test_views.py test_models.py test_forms.py test_api.py ... each test file have: from django.test import TestCase class MyNameTest(TestCase): @classmethod def setUpTestData(cls): When i ran all test: python3 manage.py test I got this erros: ERROR: setUpClass (core.tests.test_views.PageDetailViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/my_path/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 234, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/my_path/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 212, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: ... File "/my_path/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 212, in create_cursor cursor = self.connection.cursor() django.db.utils.InterfaceError: connection already closed ---------------------------------------------------------------------- Ran 20 tests in 1.884s FAILED (errors=1) What is the problem ? and how this fix ? -
Adding keyboard shortcust functionality to Django Admin
What is the easiest way to add keyboard shortcuts to Django admin panel without overriding admin templates? Like new object, save object, delete object and etc. -
Remove add another from django admin
I have an inline model in Django admin which is having OneToOneField relation with the parent. class Child(models.Model): parent = models.OneToOneField(Parent) received_on = models.DateField(null=True,) In admin Inline I don't want to show "add another button" so I have done something like this:- class CampaignInfluencerShippingTrackingInline(admin.TabularInline): model = Child can_delete = False extra = 0 fields = ['received_on'] def has_add_permission(self, request): return False But it is still showing add another button the problem is with relation with the parent as it is having OneToOneField if I try with ForeignKey with same code add another button is not showing but with OneToOneField it is always showing. Can anyone suggest me how it is working and what I can do to remove add another button from the Inline child?