Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set a style class to a choice field in a Django form
I am trying to set a bootstrap-select class to my choice field. However, I am getting a 'TypeError: init() got an unexpected keyword argument 'attrs''. class constraintListForm1(forms.Form): region = forms.ChoiceField(choices=REGION, required=True) operator = forms.ChoiceField(choices=OPERATOR, required=True ) class META: model = constraintListModel1 widgets = { 'region': forms.ChoiceField(attrs={'class' : 'bootstrap-select'}), } -
How to customize django admin search results in many to many fields
I trying to filter the list shown when I use the lupe in many to many fields (image bellow). Maybe a text search would be interesting too. Any help? Here's the code: class PresentialModuleCourseInline(NestedStackedInline): """Module Course Presential Stacked Inline""" model = Course.modules.through raw_id_fields = ('module_course',) extra = 1 def get_queryset(self, request): return self.model.objects.filter( module_course__type_course=ModuleCourse.PRESENTIAL) # Doesn't work -
Django: How can I get the Foreign Key ID from selection on model form?
Django beginner here. Say I have the following models: class Mom(models.Model): name = models.CharField(max_length=25) class Dad(models.Model): name = models.CharField(max_length=25) class Child(models.Model): name = models.CharField(max_length=25, unique=True) mom = models.ForeignKey(Mom) dad = models.ForeignKey(Dad) Now say I have a form where I can select a combination of mom and dad and I want to generate a list of the kids they have together. class ChildChooser(forms.ModelForm): class Meta: model = Child fields = ['mom', 'dad'] So I define a view: def myChildChooserView(request): if request.method=='POST': form=ChildChooser(request.POST) if form.is_valid(): myMom=form.cleaned_data['mom'] myDad=form.cleaned_data['dad'] return HttpResponseRedirect(reverse('kid-list', kwargs={'mom':myMom, 'dad':myDad} )) else: form = RawYarnChooser() return render(request, 'chooser.html', {'form':form}) Which I was hoping could take advantage of a url I defined: url(r'^kids/(?P<mom>[0-9]+)/(?P<dad>[0-9]+)/$',views.kidList, name='kid-list'), The problem is that the URL needs the primary key of the 'mom' and 'dad' selected on the form. The form returns the text of the selection. What's the pythonic way to get the primary key numbers from the selection on the form so I can supply them to the kwargs of Http Response Redirect? The solution I have come up with is (in the view) to ping the database with something like: mom_for_kwargs=Mom.objects.get(name=myMom) dad_for_kwargs=Dad.objects.get(name=myDad) And then get the id from those. But this seems to be a … -
How to hide GET requests from also being displayed on web
So I'm working on a django project, and one of the objectives is to allow a separate python script to make a HTTP request (using Requests library) to get json data after being authenticated. This works fine, the problem is that if I directly go the url the request.get object uses, I can see all of the data (without any user authentication being involved). This makes my authentication process pointless, as the data is easily visible by simply going to the url. So how would I hide the data on the web side from being viewed, but still allow a GET request to pull the data to my script? On a side note, I already have a authentication system for the web interface portion of my project (which displays the data). I've tried putting it behind that but to no success. import json, requests, _mysql login_attempt = requests.post('http://127.0.0.1:8000/m_app/data_login/', {'username': 'test', 'password': 'password1234'}) if login_attempt.content.decode('UTF-8') == 'Successful': print('Logged in.') else: print('Not logged in.') cookies = dict(sessionid=login_attempt.cookies.get('sessionid')) data = requests.get('http://127.0.0.1:8000/m_app/load/data', #if I type this URL in, I see the data cookies=cookies) print(data.content) #prints desired data -
possible to call other model through foreign key in templates? django
let's say I have two models class T(models.Model): name = model.Charfield(max_length=12) class S(models.Model): tt = model.ForeignKey(T) boo = model.Boolean(default=False) when I use this...t_objs= T.objects.all() then in my template I know I can loop and use {% for t in t_objs %} {{t.name}} and so on....but what if I want to get how many I can use t_objs to find how many S each t has and also pull out info of S is this possible though? -
How to modify my model to other case
I have these models in Django, class Folio(models.Model): name = models.CharField(max_length=30, primary_key=True) def __str__(self): return self.name class ST(models.Model): name = models.CharField(max_length=30, primary_key=True) def __str__(self): return self.name class Work(models.Model): name = models.CharField(max_length=30, primary_key=True) def __str__(self): return self.name class St_folio(models.Model): idST = models.ForeignKey('ST', blank=True, null=True) idFolio = models.ForeignKey('Folio', blank=True, null=True) class Meta: unique_together = (('idST', 'idFolio'),) idPro = models.ForeignKey('Pro', blank=True, null=True) path_img = models.TextField(blank=True, null=True) note = models.TextField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) date = models.DateTimeField(blank=True, null=True) def __str__(self): return str(self.id) + "st_folio" class St_work(models.Model): class Meta: unique_together = (('idObra', 'idSTFolio'),) idObra = models.ForeignKey('Work', on_delete=models.CASCADE) idSTFolio = models.OneToOneField('St_folio', on_delete=models.CASCADE) def __str__(self): return self.idObra.name + "/st_folio" + str(self.idSTFolio.id) class Pro(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name The important class are St_work and St_folio, my problem is that in this moment I can't add photos to St_folio and not replace previous one, my idea is that in table St_folio I could something like this... idST | idFolio | path_img | Others fields st1 | folio1 | image1 | ..... st1 | folio1 | image2 | ..... But in this moment I can't create something like this, because idST with idFolio are created from Web app, while that to … -
can you change the name of the Django admin 'is_staff' flag
I need to change the name of the is_staff flag in django admin. -
Django Rest Framework OPTIONS actions only shows POST
I'm trying to build a front end that will examine the options available to the use to show different UI elements (like an edit button). I'm able to pull OPTIONS from my django rest framework back-end, but the only action it shows is POST. I am using ModelViewSet with DjangoObjectPermissions. I'm receiving this as the response header: Access-Control-Allow-Headers:accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with, access-control-allow-methods Access-Control-Allow-Methods:DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin:* Access-Control-Max-Age:86400 Allow:GET, POST, HEAD, OPTIONS Content-Length:405 Content-Type:application/json Date:Wed, 02 Aug 2017 19:40:08 GMT Server:WSGIServer/0.1 Python/2.7.12 Vary:Accept X-Frame-Options:SAMEORIGIN Here is the json sent back: { "name":"Project List", "description":"", "renders":[ "application/json", "text/html" ], "parses":[ "application/json", "multipart/form-data" ], "actions":{ "POST":{ "id":{ "type":"integer", "required":false, "read_only":true, "label":"ID" }, "description":{ "type":"string", "required":true, "read_only":false, "label":"Description" }, "name":{ "type":"string", "required":true, "read_only":false, "label":"Name", "max_length":80 } } } } I have tried to read the allowed actions from the response header but that is proving to be impossible. Is there any way to have Django Rest Framework display all available actions for the user? -
How to show /account/profile without pass the user like parameter?
I want to show User profile in url /account/profile. I have a detail class based view, class UserDetail(generic.DetailView): model = User slug_field = 'username' slug_url_kwarg = 'username' template_name = 'myuser/user_detail.html' I have a error -> AttributeError at /accounts/profile/ Generic detail view UserDetail must be called with either an object pk or a slug. How can I charge the username without pass it like parameter in the url?(ie: /account/prifle/username), the user is already auntenticad. I see something similar here: http://programtalk.com/vs2/?source=python/12247/horas/apps/profiles/views.py but doesn't work to me. I tried modify get_queryset, dispatch, and nothing work, I don't know where can modify to get the right result. Any idea? Thanks -
Why is my Django form posting again from the index page?
I'm new to Django and have been following a few printed and online tutorials to start developing a basic web application. I've gotten to the point where I have: An index page (template) A form (template) A basic model A view function to handle the form The required URL patterns My form allows me to enter the name of a file and saves it in the database. The form works, it saves the data to the database and the user is returned to the index page. All works fine. My problem is this: If I'm returned to the index page after submitting the form and I hit refresh in the browser it tries to submit the same data again, even though the form isn't being displayed. Even though I can see the index page content the URL in the browser address bar still has the URL of the add_media form. It's all very odd! Here's some code: The view functions for index and add_media: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.template.context_processors import request from .forms import MediaForm from .models import Media # Create your views here. @login_required def index(request): media_list = Media.objects.order_by('title') context_dict … -
Single Sign-On between salesforce and Django
Currently i have a application which is being built using Django Framework. I am planning to implement single sign-on feature that is available under Salesforce. Such that it give me the ability to bypass the login of my Django Application when i am signed on to salesforce. Does anyone know the best library which will help me to solve this issue. -
Overriding a django model default value in the default form?
I have a model that looks something like: class DooDad(models.Model): doo_dad_dogue = models.BooleanField(default=True) Trouble is, that default needs to be manipulated by... stuff that is irrelevant to this question. If I were creating the form that creates the object, the solution would be trivial. I'm still using the django default form for creating these things, though, and I'd rather keep it that way. I tried the obvious: class DooDad(models.Model): doo_dad_dogue = models.BooleanField(default=True) def __init__(self, *args, **kwargs): super(DooDad, self).__init__(*args, **kwargs) self.doo_dad_dogue = False ...which I suspect would have terrible side effects, but was worth experimenting with. The form still comes up with the box checked. -
Wagtail multisite on same domain
I need to create a multisite configuration that let me use the same domain for different sites. Some examples of what URLs I need to achieve: subdomain.example.com (Home for all sites) | ---subdomain.example.com/common-page/ (Common page for all sites) | ---subdomain.example.com/common-page-2/ (Common page for all sites) | --- subdomain.example.com/news/ (News from all sites) | --- subdomain.example.com/site-1/ (Redirects to Home subdomain.example.com) | --- subdomain.example.com/site-2/ (Redirects to Home subdomain.example.com) | --- subdomain.example.com/site-1/news/ (Site 1 news) | --- subdomain.example.com/site-3/news/ (Site 3 news) | --- subdomain.example.com/site-1/contact/ (Contact form site 1) | --- subdomain.example.com/site-3/contact/ (Contact form site 3) I could create this structure on just one site, but it would then be a pain to manage it on the wagtail admin. -
Securely storing "environment" variables in GAE
Following from this question and this one, what's the best practice today? Is it to use custom metadata? https://cloud.google.com/compute/docs/storing-retrieving-metadata#custom -
How to send own string in response using WebSockets
I am trying to create real-time chat between Django backend and Angular 4 frontend using PostgreSQL database. Let's assume that I would like to create chatbot for instance like A.L.I.C.E. I am not sure but it seems to me that the most optimal solution would be to use websockets? I would like to write message on frontend, press enter and send my message to backend. Then I would like to get a response. I am trying to do this in the way shown below, however I would like to send in response my own string, not the one that is sent from frontend. routing.py: from channels.routing import route from backend.consumers import ws_connect, ws_receive, ws_disconnect channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] consumers.py: # In consumers.py from channels import Group # Connected to websocket.connect def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_receive(message): Group("chat").send({ "text": message.content['text'], }) print(message.content['text']) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
Django templates inheritance between apps
In Django templates there is extends tag used like {% extends "base.html" %}. I want if possible to name templates in several apps the same (like templates/bookkeeping/bookkeeping.html). I want the more specialized app (which handles bookkeeping for a particular project) to extend a template in a less specialized app (which handles common tasks for bookkeeping for several our projects) with extends. Particularly in the less specialized app I create a template without much design. In the more specialized app I want to present the same information but with a particular design (CSS, etc.) What can be done about this in Django 1.11? If it is impossible to use extends of a template with the same template name (but different app), what are other possible ways to solve the problem? I could check existence of derived.html and fall back to base.html if there is no derived.html, but this would lead to writing tedious Python code. Is there a better way? -
How to disable prefetching in Celery 3.1?
How do you disable prefetching in Celery 3.1 with a RabbitMQ backend? The answers to this similar question suggest setting CELERYD_PREFETCH_MULTIPLIER = 1 in my Django settings. I've changed this setting, and I'm running my worker with: celery worker -A myapp -l info -n workername-%(process_num)s@%%h -Q longtaskqueue -P solo Yet in my worker's log I see lines like: [2017-08-01 21:59:29,600: DEBUG/MainProcess] basic.qos: prefetch_count->8 Why is it listing a prefetch of 8 instead of 1? My "longtaskqueue" processes tasks that each can take 30 minutes or more to complete, and the problem I'm seeing is one worker hogging several tasks, while other workers have nothing to do, effectively disabling Celery's distributed computing model. I only want a worker to claim one task at a time and not request another until its current task is complete. -
sendgrid to send mails in my django project
I would like to send a mail to the respective user when his post is liked by someone .....so I am a beginner to django ....I tried with django but they suspend my account everytime .....can anyone help me please?? import sendgrid import os from sendgrid.helpers.mail import * sg=sendgrid.SendGridAPIClient(apikey='api-key') from_email = Email("mymail ") to_email = Email("user'smail") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) -
Django/Python - Unable to decode FILE Upload
I'm working with Django v1.11 and Python. I'm attempting to upload a file and then parse it. The file has some odd encoding, so I initial wrote a test script and discovered the file was using utf-16 encoding. With that test script (which I used outside of Django) I used: inputFile = open(inputFilePath, 'rt', encoding='utf-16') When using Django, I am having trouble doing the decoding. In my views.py I use: if "specFile" in request.FILES: specFilePath = request.FILES['specFile'] if(request.POST['specType'] == 'Absorbance'): doStuff(specFilePath) Which goes to the simple method: def doStuff(specFilePath): for line in specFilePath: print(line) Here I get encoded text: b'\xff\xfe#\x00#\x00B\x00L\x00O\x00C\x00K\x00S\x00=\x00 \x006\x00\r' b'\x00\n' b'\x00P\x00l\x00a\x00t\x00e\x00:\x00\t\x00e\x001\x00\t\x001\x00.\x003\x00\t\x00P\x00l\x00a\x00t\x00e\x00F\x00o\x00r\x00m\x00a\x00t\x00\t\x00E\x00n\x00d\x00p\x00o\x00i\x00n\x00t\x00\t\x00A\x00b\x00s\x00o\x00r\x00b\x00a\x00n\x00c\x00e\x00\t\x00R\x00a\x00w\x00\t\x00F\x00A\x00L\x00S\x00E\x00\t\x001\x00\t\x00\t\x00\t\x00\t\x00\t\x00\t\x002\x00\t\x002\x006\x000\x00 \x002\x008\x000\x00 \x00\t\x001\x00\t\x002\x004\x00\t\x003\x008\x004\x00\t\x001\x00\t\x001\x006\x00\t\x00\t\x00\r' ... When putting in line = line.decode(encoding='latin1') b'\xff\xfe#\x00#\x00B\x00L\x00O\x00C\x00K\x00S\x00=\x00 \x006\x00\r' b'\x00\n' b'\x00P\x00l\x00a\x00t\x00e\x00:\x00\t\x00e\x001\x00\t\x001\x00.\x003\x00\t\x00P\x00l\x00a\x00t\x00e\x00F\x00o\x00r\x00m\x00a\x00t\x00\t\x00E\x00n\x00d\x00p\x00o\x00i\x00n\x00t\x00\t\x00A\x00b\x00s\x00o\x00r\x00b\x00a\x00n\x00c\x00e\x00\t\x00R\x00a\x00w\x00\t\x00F\x00A\x00L\x00S\x00E\x00\t\x001\x00\t\x00\t\x00\t\x00\t\x00\t\x00\t\x002\x00\t\x002\x006\x000\x00 \x002\x008\x000\x00 \x00\t\x001\x00\t\x002\x004\x00\t\x003\x008\x004\x00\t\x001\x00\t\x001\x006\x00\t\x00\t\x00\r' ... When putting in line = line.decode(encoding='utf-16') I get the error message: UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x0d in position 24: truncated data I'm not sure where to go from here. Is there some other way to do the decoding? Also, apologies for any errors or poor phrasing in this question. This is my first Stack Overflow question ever asked and Django/Python are just tools I use in my work in the scientific side of Drug Discovery platform development. -
Django - Template displays edited user context info despite ValidationError
Hi I'm working on a form to edit a user's profile. It properly updates the fields upon successful submission without any validation errors. The problem I'm having is that if the form does return a validation error upon submission and I've changed the name on the form, the template will display this new name instead of the old name. I'm assuming this is because it uses the user context provided by the POST request. Is there any way to properly display the user's old name until the form is actually successfully submitted? Below is my code. forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms import ModelForm class UserProfileForm(UserCreationForm): first_name = forms.CharField(label="First Name", required=True) last_name = forms.CharField(label="Last Name", required=True) email = forms.EmailField(label="Email", required=True) class Meta: model = User fields = ("first_name", "last_name", "email", "username", "password1", "password2") def clean_email(self): email = self.cleaned_data.get('email') if email: if User.objects.filter(email=email).exists(): raise forms.ValidationError('This email is already in use.') return email def save(self, commit=True): user = super(UserProfileForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user class EditProfileForm(ModelForm): first_name = forms.CharField(label="First Name", required=True) last_name = forms.CharField(label="Last Name", required=True) email = forms.EmailField(label="Email", required=True) password1 = forms.CharField(label="New Password", widget=forms.PasswordInput) password2 = forms.CharField(label="Repeat New … -
Django Form Fields Not Displayed
Hello i can't make my form work. The button is displayed but the charfield never shows up. I tried to use a if statement with the "sent" parameter and it worked. I just followed the django doc. I did not find a solution in other posts. Here is my forms.py: from django import forms class CharacterForm(forms.Form): character_name = forms.CharField(label='Search', max_length=30) views.py: from django.shortcuts import render from .forms import CharacterForm def get_character(request): if request.method == 'POST': form = CharacterForm(request.POST) if form.is_valid(): character_name = form.cleaned_data['character_name'] sent = True else: form = CharacterForm() return render(request, 'perso:index', { 'form': form, 'character_name': character_name, 'sent': sent }) My form in template: <form action="{% url "perso:index" %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> Here is what appears in the browser: <form action="/perso/" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='IWmBEknyibHw4LpvjnyfLWKcUOXLbw27RdHgR7GjhTDelCLGZ51QeF3y9wRyC0Mg' /> <input type="submit" value="Submit" /> </form> The charfield is missing. No error in the console. -
No Reverse Match
Reverse for 'details' with arguments '('Federal Airports Authority of Nigeria (FAAN)',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['details/(?P[a-zA-Z0-9 w+ ]+)/$'] This is my urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<company_name>[a-zA-Z0-9 w+ ]+)/$', views.details, name='details'), url(r'^full_list/$', views.full_list, name='full_list' ), ] This is the models.py class CompanyDetail(models.Model): name = models.CharField(max_length=300) company_logo = models.FileField(default='') company_info = models.TextField() company_address = models.TextField() tag = models.CharField(max_length=300) def __str__(self): return self.name This is my views.py def details(request, company_name): company = CompanyDetail.objects.get(name=company_name) return render(request, 'company_profiles/details.html', {'company':company} ) def full_list(request): lists = CompanyDetail.objects.all() return render(request, 'company_profiles/full_list.html', {'lists':lists}) This is the template {% extends 'company_profiles/base.html' %} {% block content %} {% for company in lists %} <p> <div class="alert alert-info" role="alert"> <a href="{% url 'company_profiles:details' company.name %}" class="alert-link">{{ company }}</a> </div> </p> {% empty %} <p>No companies found</p> {% endfor %} {% endblock content %} I only get no reverse match when there are spaces in the company name. -
Django add system check
I have a Django project which uses third-party apis and I want to check if they are up (my credentials are correct, the schema is right, etc.). I have read about the System check framework, but I cannot get it to run. I do not know where to put the checks or how to run them. I have tried this: >> web[my_app]/apps.py class WebConfig(AppConfig): name = 'web' def ready(self): register(example_check, Tags.compatibility, deploy=True) def example_check(app_configs, **kwargs): errors = [] check_failed = False if check_failed: errors.append( Error( 'an error', hint='A hint.', obj=1, id='myapp.E001', ) ) return errors But I run ./manage.py check web and it detects no errors. -
django website working, but django manage.py cannot connect to db
I'm trying to run a django migration to update my database, but "manage.py migrate" can't connect to my postgresql db. The odd thing is: my django website (which is exactly the same code) is working including connecting to the db. Error messages: psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.xxxxxx"? and django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL -
How to make Django admin honor grammatical cases in languages like Polish?
Django allows overwriting verbose_name and verbose_name_plural of a Model, which allows us to specify correct plural forms of Model names for non-English languages (for example Kandydaci as a plural of Kandydat instead of the default Kandydats which looks weird in Polish). However, this is far from enough for languages with grammatical cases. For example, Django Admin gleefully displays us something like that: (Where Zaznacz kandydat do zmiany stands for Select kandydat to change - Kandydat is a name of a Model) This is incorrect. In this sentence the model name should have been displayed in accusative case, which is kandydata. However, I cannot simply specify that verbose_name of this Model is Kandydata, since would also affect all places where nominative case is expected instead - I've found one such place so far, and this is the heading of the table column: This is incorrenct since the table heading should be called Kandydat not Kandydata. How to fix this?