Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not able register my model to wagtail admin using wagtail_hook
I am trying register my model to wagtail admin but i am not able see my model. my model is class Abc(models.Model): abc_id = models.AutoField(primary_key=True) type = models.ForeignKey(AbcTypes, models.DO_NOTHING, db_column='type') name = models.TextField() country = models.ForeignKey(Countries, models.DO_NOTHING, db_column='country') active = models.BooleanField() i am trying to register my Abc model to wagtail admin using wagtail_hook. wagtail_hook.py from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register) from .models import Abc class AbcWagtailAdmin(ModelAdmin): model = Abc menu_label = 'Abc Data' # ditch this to use verbose_name_plural from model menu_icon = 'tag' # change as required menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd) add_to_settings_menu = False # or True to add your model to the Settings sub-menu exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view modeladmin_register(AbcWagtailAdmin) But its not showing to wagtail admin menu. Help will be appreciated. -
Can I display two distinct tables for a model in the django admin interface, based on a boolean in that model table?
I want to display two separate tables for a model when I go into the django admin interface based on a boolean in that model. For example in admin.py I have: class MyModelsAdmin(admin.ModelAdmin): list_display = ('Name', 'user', 'sample', 'experiment', 'reported') and 'reported' is a boolean. I would like to display two tables , reported and not reported. Is there a way to do this in my MyModelsAdmin class? Something like: class MyModelsAdmin(admin.ModelAdmin): list_display = ('Name', 'user', 'sample', 'experiment', 'reported') if reported == True: ... display table with header Reported ... elif reported == False: ... display table with header Not Reported ... else: pass -
Django save user profile manually
I was crated a Profile and attached to user model using OneToOneField. I have a registration form where user enters input which corresponds to user and profile. Django provides User.objects.create_user to save fields which are related to User model, but i don't know how to save details of Profile model manually. Here is my code: models.py from django.db import models from django.contrib.auth.models import User def Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=150, required=True) # lot more fields here views.py @csrf_protect def register(request): if request.method == 'POST': full_name = request.POST.get('full_name', '') username = request.POST.get('username', '') password = request.POST.get('password', '') User.objects.create_user(username=username, password=password) # how to save Profile full_name here return render(request, 'register.html') register.html <form method="post" action="/register/">{% csrf_token %} <div class="form-group"> <label for="full_name">Name</label> <input type="text" name="full_name" id="full_name"> </div> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" value="" id="username"> </div> <div class="form"> <label for="password">Password</label> <input type="pass" name="password" value="" id="password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> 1) How can i save full_name of Profile model in views.py ? Can i do this without creating form class for every model that want to save, that's my intention from the beginning and they are confusing? 2) Do i need to change auth_user_model in settings.py in order to … -
Django - data as in firebase but on my server
we have prototype of frontend write with firebase. Our company security policy do not allow us to use firebase, moust of our tools are written in python/django, so we want to write in django backend which do not work on tables but on dictionary structure. Could you recomend me same framework which allow me to in easy and fast way write samething similar do firebase. -
__init__() got an unexpected keyword argument 'instance' with custom formset for inlineformset_factory
I'm getting this error init() got an unexpected keyword argument 'instance' whenever I try to send a form with formset argument specified for inlineformset_factory. Any ideas why this is happening? Here is my code. Sorry it's not commented I'm rewriting it a lot trying to understand how django works forms: class PurchaseForm(forms.ModelForm): class Meta: model = Purchase fields = ['product', 'price', 'consumer'] widgets = { 'product': forms.Select(attrs = { 'class': 'form-control input-sm', }), 'consumer': forms.Select(attrs = { 'class': 'form-control input-sm', }), 'price': forms.NumberInput(attrs = { 'class': 'form-control input-sm', 'placeholder': 'Цена', }), } discount = forms.DecimalField( min_value = 0, decimal_places = 2, # required = False, widget = forms.NumberInput( attrs = { 'class': 'form-control input-sm', 'placeholder': 'Скидка' } ), ) class PurchaseFormSet(BaseModelFormSet): def add_fields(self, form, index): super(PurchaseFormSet, self).add_fields(form, index) form.fields[DELETION_FIELD_NAME].label = '' view: def receipt(request): purchase_formset = inlineformset_factory( Receipt, Purchase, form = PurchaseForm, formset = PurchaseFormSet, <-- when I comment this everything works fine ) if request.method == 'POST': receipt_form = ReceiptForm( request.POST, prefix = 'receipt' ) if receipt_form.is_valid(): receipt = receipt_form.save() receipt_form = ReceiptForm( instance = receipt, prefix = 'receipt' ) purchases_form = purchase_formset( request.POST, prefix = 'purchase', instance = receipt <-- line that causes error according to traceback ) … -
Django URL trails other file URLs
I'm building a website on Django. Here is the problem : url.py : url(r'^product/(?P<slug>[-_\w]+)/$', ProductView.as_view(), name='product'), This URL calls product/product-slug successfully, but it affects other files' urls. Error message is : "GET /product/lenovo-tv/static/css/bootstrap.min.css HTTP/1.1" 404 4862 What am I missing? base.html : <link href="static/css/bootstrap.min.css" rel="stylesheet"/> <link href="static/css/font-awesome.min.css" rel="stylesheet"> <link href="static/css/custom-styles.css" rel="stylesheet"> -
Django admin panel image upload optimization
I want to optimize the image uploaded by user from the admin site and store original as well as optimized image and for that def save_model(self, request, obj, form, change): if obj.image: filename = obj.image.name.split('.')[:-1] obj.save() img = Image.open(obj.image) print "Before Size: ", img.size w, h = img.size size = min(800.0 / w, 800.0 / h) w, h = int(w * size), int(h * size) print "After Size:", w, h img = img.resize((w, h), Image.BICUBIC) path = obj.image.path.split('\\')[:-1] new_path = "\\".join(path) + "\\{}.jpeg".format("".join(filename)) img.save('{}'.format(new_path)) obj.imgae = img obj.save() Got Error AttributeError: _committed Any helpful suggestion will be appreciated ! -
How to Stop send mail to user when registration for local machine in django rest api?
Please suggest me to stop sending mail while registration using django rest framework, i m new in rest framework and working on existing project, due to unable to deliver mail raising error like: [Errno -2] Name or service not known, or connection refuse so i can't able to understand over all registration flow. Thanks -
Send emails to the users without requiring EMAIL_HOST_PASSWORD in Django
I am trying to make a "noreply" email to send the users. But I dont want to put password in the EMAIL_HOST_PASSWORD field. Is it possible? I tried this exact thing with PHP and it was a success. How can I do this using Django? -
Creating elasticsearch-dsl DocType objects from dict or json
I'm using the elasticsearch-dsl library to define mappings in elasticsearch and to index django model objects. For initial indexing I, however, want to use json data for all models. Is there a way to instantiate DocType subclass objects directly from json or from a python dict? -
django typeError at / 'NoneType' object is not callable
trying to get the following running: https://github.com/DjangoPatternsBook/superbook.git I have to got the server running but when I try to go to localhost I just get the typeError at / 'NoneType' object is not callable Any idea of how I can start figuring this out? Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.3 Exception Type: TypeError Exception Value: 'NoneType' object is not callable Exception Location: /home/sb_django/lib/python3.5/site-packages/django/views/generic/edit.py in get_form, line 45 Python Executable: /home/sb_django/bin/python Python Version: 3.5.2 -
Can't access 8000 port of a Django project in docker
I'm trying to put my Django project into a docker image. This is my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt -i https://pypi.douban.com/simple ADD . /code/ EXPOSE 8000 Then I build and run this docker container: docker run -i -t -P e2 python3 manage.py runserver 8000 Performing system checks... System check identified no issues (0 silenced). July 25, 2017 - 15:24:11 Django version 1.11.3, using settings 'chaoYuBackend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when I visit localhost:8000 or 127.0.0.1:8000 in Chrome, I got ERR_CONNECTION_REFUSED. This is what I got by executing docker ps, it seems that the 8000 port has been exposed: docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 83dd71644f31 e2 "python3 manage.py..." 6 minutes ago Up 6 minutes 0.0.0.0:32769->8000/tcp clever_dijkstra It's there anything wrong in my Dockerfile? How can I visit my Django site in browser? Thanks in advance! -
Django Rest Api filter field's select options based on request.user
I am currently working on a django rest framework api which involves displaying a list of campaigns and allowing user to create new campaign. On the browsable api, I managed to display the list of campaigns that I wanted as well as have a form for the user to create new campaign. This is a screenshot of the form that the user is using for creating new campaign. A screenshot of the form on browsable API While everything is working, I faced an issue that I do not have any idea how to solve even after reading the documentation. As you can see on the screenshot, there is a clist field that allows user to select the contact list he/she want the campaign invitations to be sent to. However, I want to make sure only the contact lists created by the user's company are shown in that field (currently, all the contact lists from different companies can be selected). Here is the codes in the api.py: class EditCampaignViewSet(ModelViewSet): queryset = Campaign.objects.all() serializer_class = EditCampaignSerializer parser_classes = (MultiPartParser, FormParser) def list(self, request, p_uuid=None, type=None, *args, **kwargs): company = request.user.profile.company queryset = Campaign.objects.filter(company=company, product__uuid=p_uuid, deleted=False, campaign_type=type)\ .order_by('-created')\ .prefetch_related('user__profile') serializer = EditCampaignSerializer(queryset, many=True) … -
Django Filter Backend
I'm working with Django rest framework API, I am trying to make a filter by first_name or by last_name or by both of them. This is my ContactViewSet.py : class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer filter_backends = (DjangoFilterBackend, ) filter_fields = ('first_name', 'last_name') lookup_field = 'idContact' My DRF's settings : REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), } My actuel request url look like : http://localhost:8000/api/v1/contacts/?first_name=Clair&last_name=Test But I'm looking for something like : http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes** Any help would be appreciated .. -
Django internal redirect/url rewriting
The situation is the following: I have the url /app/categories/ that supports filtering by query arguments /app/categories/ returns all categories /app/categories/?project=1 returns all categories for the project with ID 1. I want to also have an URL /app/projects/1/categories that will return the same result as /app/categories/?project=1 but without having to rewrite the view. Is it possible to make some kind of internal redirect or url rewriting such that when requesting /app/projects/1/categories the result will be the same as calling /app/categories/?project=1, but without redirecting? (in the future I might need to make the same thing for unsafe methods) -
Issue rendering django for on template with bootstrap
I am trying to render my django forms in the template using bootstrap and I keep getting an error: BoundField' object has no attribute 'fields' This is what I try: {% for field in layer_form %} {{ field | as_bootstrap }} {% endfor %} If I try this: {{ layer_form|as_bootstrap }} then it works. But I need to loop through the form fields and append some if statements in between. Any idea what's going on here? -
Python: how to identify zip code between US and CANADA
I have a form where user can provide their address containing zip code as well. E.g. - V7J, North Vancouver East Central, BC (Canada) 462 1st Avenue, New York, NY 10016 (USA) With given address, In python(django) what is the right approach to identify a country? I tried regx approach US - ^\d{5}(-\d{4})?$ CANADA - ^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$ Or I can just look for any alphabet in zip to say its canada? -
Module object has no attribute SQLStorageAdapter
While running django chatterbot app, i encounter an error module' object has no attribute 'SQLStorageAdapter' I define chatbot the following way in my view. chatbot = ChatBot( "SQLMemoryTerminal", storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ "chatterbot.logic.MathematicalEvaluation", "chatterbot.logic.TimeLogicAdapter", "chatterbot.logic.BestMatch" ], input_adapter="chatterbot.input.TerminalAdapter", output_adapter="chatterbot.output.TerminalAdapter", ) Can anybody tell me why I am getting this error? Should I need any extra library or something like that? Thanks. -
Populate select box by database and save the input into another database. (Django)
my main problem is that I've few select boxes in my current project. By now they "choices" were stored in the 'models.py' but my task is to remake them to gain data from local database. I found easy solution by using ModelChoiceField and declaring it in 'forms.py' instead of models, but I don't know how to save the user input from this select box. Is there easy solution for it? Or do I have to use different approach? Thanks for help. -
db.sqlite doens't work after rm -rf --cached
There is the 'db.sqlite3' in my folder. But it doesn't work. I had git rm -rf --cached . to apply .gitignore and git push. After git pull the git file, in spite of there's db.sqlite3 in github and my file, the db doesn't work and even there isn't migration history. So, I sudo python3 manage.py migrate. But db.sqlite3 doesn't work even there's no superuser. Why db doesn't apply?? -
Django: DetailView implementing a get_queryset()
I'm getting this following error: ImproperlyConfigured at /elearning/7447932a-6044-498a-b902-97cbdd0a4001/ DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Following the Django documentation on DetailView the get_query is not mandatory unless that I want to override it. view.py class CourseDetailView(DetailView): model = Course template_name='elearning/detail.html' def get_object(self): course = get_object_or_404(Course, pk=self.kwargs['pk']) return self.model.objects.filter(pk=pk) def get_context_data(self, **kwargs): context = super(CourseDetailView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context urls.py url(r'^(?P<pk>[0-9a-z-]+)/$', views.DetailView.as_view(), name='course-detail'), listview template <a href="{% url 'elearning:course-detail' article.course_id %}">{{ article.title }}</a> models.py class Course(models.Model): course_id = models.UUIDField(default=uuid.uuid4, editable=False) ... I would like to know why should I implement a get_queryset()? I still get the same error when I add a get_queryset() def get_queryset(self): qs = super(CourseDetailView, self).get_queryset() return qs.filter(pk=self.kwargs['pk']) -
installing gdal on mac os sierra
I have a django project that i want to install and it uses GDAL. The documentation refers me to this page in the django documentation. I have been able to install GEOS and PROJ.4. I wanted to use the latest GDAL which is 2.2.1 and ./configure command failed so I followed this instructions and it compiled. However, make command now fails with the following error In file included from cpl_odbc.cpp:30: /Users/DNG/gdal-2.2.1/port/cpl_odbc.h:39:10: fatal error: 'sql.h' file not found #include <sql.h> ^ 1 error generated. make[1]: *** [cpl_odbc.o] Error 1 make: *** [port-target] Error 2 sudo find / -name sql.h outputs: find: /dev/fd/DNG: No such file or directory find: /dev/fd/DNG: No such file or directory /usr/local/Cellar/unixodbc/2.3.4/include/sql.h /usr/local/include/sql.h /usr/local/php5-7.0.18-20170506-095200/include/sql.h -
【django-1.11.3/angular-1.6.4】POST AJAX CSRF verification failed
guys. I've been studying about both AngularJS and Django recently. AngularJS promises to handle incoming cookie named 'XSRF-TOKEN' and to add a request header named 'X-XSRF-TOKEN' automatically. So I set django variables in settings.py: CSRF_COOKIE_NAME = 'XSRF-TOKEN' CSRF_HEADER_NAME = 'X-CSRF-TOKEN' Obviously, it is not working as is implied here. So I had to install angular-cookies.js module to retrieve 'csrftoken' cookie and put its value in request header 'X-CSRF-TOKEN'. However, it's still not working. So what ever it is this time, it must be on server side. HTML template: <!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <title>youtube-dl</title> <link href="/video/css/video.css" rel="stylesheet" type="text/css"> <script src="/js/angular-1.6.4.min.js" type="text/javascript"></script> <script src="/js/angular-cookies.js" type="text/javascript"></script> </head> <body> <div id="container" class="center" ng-app="vc" ng-controller="vc-ctl"> <img id="dl-icon" src="/video/logo.png"></img> <form name="form"> {% csrftoken %} <input class="url {{urlState}}" type="url" name="url" placeholder="https://" required autofocus ng-model="url"> <button class="btn btn1" ng-if="!form.url.$valid"> {{ buttonText }} </button> <button class="btn btn2 {{btn2State}}" ng-if="form.url.$valid" ng-click="click();"> {{ buttonText }} </button> </form> </div> <script src="/video/js/app.js" type="text/javascript"></script> </body> </html> views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.shortcuts import render from django.http import HttpResponse from .models import VideoTask # Create your views here. def index(request): if request.method == 'GET': return render(request, 'video/index.html') stat = { "full_path: ", request.get_full_path(), … -
How can I add an option to add more fields while creating a new user in django
I was following the official documentation of django and I need help with being able to add a option to the admin site where I can add a option to add a new field like along with customer name and password also an ID so how can i add the ID option on the page itself ? -
Contingently Display Data from Django Snippets an Outside a For Loop
I created a Django snippet to display data with **kwargs and I have header tags for the section titles in my template. What I am having difficulty with is conditionally display that header title only if a value exists, but I don't understand how to do that outside of a for loop and of course, if I place it inside the loop, the header title is repeated for every object in the loop. I hope this makes sense; I included my snippet and template code below. snippet @register.inclusion_tag( 'tags/_chapter-snippets.html', takes_context=True ) def chapter_snippets(context, **kwargs): chapters = ChapterPage.objects.all().order_by('title').filter(**kwargs) return { 'chapters': chapters.select_related('feed_image'), # required by the pageurl tag that we want to use within this template 'request': context['request'], } template I only want to show the h3 tag if the snippet has an object ... <div style='display: grid'> <h3>North America</h3> <div class="row"> {% chapter_snippets ctype='alumni' carea='north_america' %} </div> </div> ...