Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filter additional filtering
There is a model structure of the following form class Industry(models.Model): name = models.CharField(max_length=255) class Category(models.Model): name = models.CharField(max_length=255) industry = models.ForeignKey('Industry', null=True, blank=True) class Franchise(models.Model): name = models.CharField(max_length=255) categories = models.ManyToManyField('Category') industries = models.ManyToManyField('Industry') And I have a regular filter: class FranchiseFilterSet(django_filters.FilterSet): industries = django_filters.ModelMultipleChoiceFilter( queryset=Industry.objects.all(), widget=forms.CheckboxSelectMultiple, ) categories = django_filters.ModelMultipleChoiceFilter( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, ) the idea is to implement a filter so that when selecting the industry without selecting its category displays all franchise of selected industry (without category matching) I have implemented an additional filter class CategoryMultipleChoceFilter(django_filters.ModelMultipleChoiceFilter): def filter(self, qs, value): categories_list = [] categories_list.extend(value.values_list('id', flat=True)) if value: industries = self.parent.data.getlist('industries') for industry_pk in industries: industry_instance = Industry.objects.filter(pk=industry, category__in=value) if not industry_instance.exists(): category = Category.objects.filter(industry=industry_pk) categories_list.extend(category.values_list('id', flat=True)) return super().filter(qs, categories_list) for "categories" field: class FranchiseFilterSet(django_filters.FilterSet): ... categories = CategoryMultipleChoceFilter( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, ) this solution works, but I'm not sure that it is correct. perhaps there is a more elegant solution? -
Django: 'ContactView' object has no attribute 'form'
I'm trying to follow this tutorial (https://hellowebapp.com/news/introduction-to-class-based-views/) and have made this view: class ContactView(FormView): form_class = ContactForm success_url = reverse_lazy('index') template_name = 'app/contact.html' def form_valid(self, form): contact_name = self.form.cleaned_data['contact_name'] contact_email = self.form.cleaned_data['contact_email'] form_content = self.form.cleaned_data['content'] template = get_template('contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content }) content = template.render(context) email = EmailMessage( 'New contact form submission', content, 'Your website ' + '', ['youremail@gmail.com'], headers={'Reply-To': contact_email} ) email.send() return super(ContactView, self).form_valid(form) However when I submit the form I get the following error: 'ContactView' object has no attribute 'form' The error seems to be related to this part: contact_name = self.form.cleaned_data['contact_name'] contact_email = self.form.cleaned_data['contact_email'] form_content = self.form.cleaned_data['content'] where 'form' is an unresolved reference. How do I fix this error? Any help is much appreciated! I'm using Python 3.5 and Django 1.9. -
django.contrib.auth.views.login not working with django-username-email cuser.CUser
I'm refactoring a django 1.9 application from using django.contrib.auth.models.User to using django-username-email cuser.CUser. The application model has been updated to use CUser. I can create users using management scripts and through the /admin/ interface. I updated the login template to post email and password values instead of username and password. Attempts to log in with a valid email and password return the login page with no errors reported. I don't know how to debug what is going wrong and would appreciate help. Here is the relevant urls.py configuration: from django.contrib.auth.views import ( login, logout_then_login, ) ... url(r'^login/$', login, {'template_name': 'intermap/login.html'}, name='login'), Here is the refactored login.html form: <form name="form_login" action="." method="post" role="form">{% csrf_token %} {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> {% for e in form.non_field_errors %} <strong>ERROR!</strong> {{ e }} {% endfor %} {% if form.email.errors %} {% for error in form.email.errors %} <strong>Email address</strong> {{ error|escape }} {% endfor %} {% endif %} {% if form.password.errors %} {% for error in form.password.errors %} <strong>Password</strong> {{ error|escape }} {% endfor %} {% endif %} </div> {% endif %} <div class="form-group"> <input type="email" class="form-control input-lg" name="email" placeholder="Email address" autofocus autocomplete="off"> </div> <div class="form-group"> <input type="password" class="form-control input-lg" name="password" … -
How to add rows in Django admin model list view?
This question is similar to this but this feature might have already been implemented in, say, Grappelli or some separate patch. -
VSCode automatically removes new lines
I'm currently building an app using Python and Django. And when I am writing in my HTML files, I am putting some Jinja templating logic in it. Well, when I hit save in VSCode, it automatically pushes it back up a line and it's incredibly hard to read that way. I have examples below to show what I mean. Before So this is before I hit save and what I want it to look like. After This is after I hit save. I am sure there's either a super simple setting I can change (which I've tried looking through). Or a plugin that I can install. But if there are neither, maybe I'll have to build my own plugin?? haha Thanks for helping! -
Horizontal view and Submit button in Crispy form Does not work
The Vertical Layout in crispy form is working by default but the horizontal layout for the form and Submit button are not appearing .. i think there is some problem with init but the compiler shows it all right views.py class sessioncreate(LoginRequiredMixin,CreateView): model=Sessions #fields=['title','abstract','track','speaker'] form_class=SessionForm def form_valid(self, form): form.save(); return HttpResponseRedirect('/sessions') form.py from django.forms import ModelForm from app.models import Sessions from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class SesionsForm(ModelForm): class Meta: model=Sessions fields=['title','abstract','track','speaker'] def __init__(self, *args, **kwargs): super(SessionForm, self).__init__(*args, **kwargs) self.helper=FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-offset-1 col-sm-2' self.helper.field_class = 'col-sm-8' self.helper.add_input(Submit('submit', 'Submit')) session_form.html {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {% crispy form %} </form> {% endblock %} -
Django admin tabular inline getElementById not working
I have to pass input dynamic id(it keeps changing for every new line add) of django's admin tabular inline field and passing one lines id is not reflecting for next lines. var total_lenght = document.getElementById("id_orderitem_order-0-quantity").value.length; Above code only reflects for first row, but I want "getElementById" which should reflects for all newly added dynamic rows Here below is my sample dynamically created html input lines <input id="id_orderitem_order-0-quantity" name="orderitem_order-0-quantity" onkeypress="return my_func(event)" step="0.01" type="number"> <input id="id_orderitem_order-1-quantity" name="orderitem_order-1-quantity" onkeypress="return my_func(event)" step="0.01" type="number"> <input id="id_orderitem_order-2-quantity" name="orderitem_order-2-quantity" onkeypress="return my_func(event)" step="0.01" type="number"> <input id="id_orderitem_order-3-quantity" name="orderitem_order-3-quantity" onkeypress="return my_func(event)" step="0.01" type="number"> . . . . etc -
Where to instantiate an object used in several parts of a Django/Python application?
I realize this is a very basic question. Please see the disclaimers and context below if this just seems plain stupid! I often have an object representing a resource -- for example a Redis queue -- that is used in several places in my Django application. However, the resource is not necessarily invoked in every single HTTP request. Should I: Instantiate the object once, and import it into the relevant modules? Or, instantiate the object locally in each module where it is needed? Option 1 shared.py from redis import Redis from rq import Queue queue = Queue(connection=Redis()) views1.py from shared import queue # ... use the queue views2.py from shared import queue # ... use the queue views3.py # we don't use the queue here, so no import Option 2 views1.py from redis import Redis from rq import Queue queue = Queue(connection=Redis()) # ... use the queue views2.py from redis import Redis from rq import Queue queue = Queue(connection=Redis()) # ... use the queue views3.py # we don't use the queue here, so no need to instantiate it Disclaimers & Context I'm sure this question seems elementary and perhaps somewhat goofy. I realize both methods work -- I'm really asking … -
Django model inheritance, set_all() on child
An example situation as follows: ## in models.py class Form(models.model): name = models.CharField() class A(models.Model): form = models.ForeignKey(Form) class B(A): name = models.CharField() ## in view.py form = Form.objects.get(id=1) form.b_set.all() # doesn't work form.a_set.all() # works I would like to access all the related B Objects via the parent class A foreign key but I can't seem to do this. And if I access them via A then I just get the generic parent class query set. Thank you. -
Remove user in Django
I would like to remove user in Django frmaework. I know that probably I can use some library like allauth but I want to do this on my view. I didn't find any tutorial for that so I am trying to do this learn-by-mistakes way. Ok. so in urls I have: urlpatterns = [ ('^remove$', views.remove_user, name="remove"), ] forms: class RemoveUser(forms.ModelForm): class Meta: model = User fields = ('username',) views: http://pastebin.com/1eYDG3ah I can access website and type text in textfield. When I type random username I get error "user does not exist" so everything ok, but when I type correct username I get message: "A user with that username already exists" and this user is not removed. Please, can you help me with that? -
Django - ImageField save to user folder fails
I can successfully upload a file but I can not state the folder as the logged in username. I have tried the following: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class Document(models.Model): user = models.OneToOneField(User) document = models.ImageField(upload_to=user_directory_path) uploaded_at = models.DateTimeField(auto_now_add=True) but receive the following error: Django Version: 1.9.6 Exception Type: RelatedObjectDoesNotExist Exception Value: Document has no user. The form is as follows: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) With the view as follows: @login_required def profile(request, extra_context={}): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('profile') else: form = DocumentForm() return render(request, 'meta/profile.html', { 'form': form }) Any advice would be appreciated, Alan. -
Django Multiple Databases " relation does not exist "
I am using two databases, one of Mysql other is PostgreSql. Mysql is defined for 'default', PostgreSql is defined for 'location_db' and I have 5 app, let say 'a, b, c, d, location' apps, All apps should run every things on 'default' database except location app, I Just do ' python manage.py runserver ' then every things works fine, and even site works fine, but when I am at admin page and then click ' location ' admin model it runs error * relation "location_locationmodel" does not exist * at the other hands, if I click 'abcd' admin models, it just works fine. 1) this is router.py class LocationRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to location_db. """ if model._meta.app_label == 'location': return 'location_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to location_db. """ if model._meta.app_label == 'location': return 'location_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the events app is involved. """ if obj1._meta.app_label == 'location' or \ obj2._meta.app_label == 'location': return True return None def … -
Django popping out data in a serializer returns empty
I have a problem, this line isn't popping any data despite me passing the data... company_data = validated_data.pop('company', None) Does anyone have any idea why I'm not getting any data passed into my serializer? Thank you everyone ahead of time! These are parts of my serializer... class UserSerializer(serializers.ModelSerializer): company = CompanySerializer(required=False) .... class Meta: model = User fields = ('id', 'email', 'username', 'password', 'first_name', 'name','phone', 'company') extra_kwargs = {'password': {'write_only': True}} .... def create(self, validated_data): profile_data = validated_data.pop('user_profile', None) company_data = validated_data.pop('company', None) This next part is part of my views.... @api_view(['GET', 'POST']) def users_list(request): """ List all users or create a new user """ if request.method == 'GET' and request.user.is_superuser: if request.user.is_superuser: records = User.objects.all() serializers = UserSerializer(records, many=True) return Response(serializers.data) else: return Response(status=status.HTTP_403_FORBIDDEN) elif request.method == 'POST': mutable = request.POST._mutable request.POST._mutable = True request.data["username"] = request.data["email"] request.POST._mutable = mutable serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) Here is my model... class Company(models.Model): date_of_subscription = models.CharField(max_length=100) company_name = models.CharField(max_length=100) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) user = models.OneToOneField(User, related_name="company", on_delete=models.CASCADE, primary_key=True) Thanks everyone! -
django-filebrowser 'Error finding Upload-Folder'
I have: Django 1.8.2 django-grappelli 2.7.3 django-filebrowser 3.6.4 django-tinymce 2.4.0 In INSTALLED_APPS: INSTALLED_APPS = ( 'grappelli', 'filebrowser', 'django.contrib.admin', In urlpatterns: from filebrowser.sites import site urlpatterns = patterns[ url(r'^admin/filebrowser/', include(site.urls)), url(r'^grappelli/', include('grappelli.urls')), url(r'^tinymce/', include('tinymce.urls')), url(r'^admin/', include(admin.site.urls)), ] Which seems to work correctly. My MEDIA_ROOT is set to 'D:\\sites\\my_site\\public_html\\media\\'. I have FILEBROWSER_DIRECTORY = 'D:\\sites\\my_site\\public_html\\media\\' set also in my settings, but still getting an error on browsing http://localhost:8000/admin/filebrowser/browse/: ImproperlyConfigured at /admin/filebrowser/browse/ Error finding Upload-Folder (site.storage.location + site.directory). Maybe it does not exist? -
how to access m.localhost:8000 with ip address
I make a website with Django. The local domain is localhost:8000 and 192.168.0.6:8000 I also create mobile version of the website. And its domain is m.localhost:8000 But I want to access mobile version with ip address. that's because I can't access that page with my mobile devices. m.192.168.0.6:8000 doesn't work. -
Django Pillow install on Amazon EC2
Currently I am on a mac os x os and trying to push a django app to amazon ec2 webserver (a linux one). Everytime I include Pillow==4.0.0 in requirements.txt I get the following error when I go to eb deploy: The headers or library files could not be found for jpeg, a required dependency when compiling Pillow from source. However I already sshed into my instanse and ran sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel Which had no effect. -
Django does not recieve TextArea content in POST, but all other fields are sent fine
I have a form in HTML, and I am using Django as a backend. All the other fields are sent and recieved fine, but application is not. apply.html <form action="/submit/" method="post"> {% csrf_token %} <div class="row"> <div class="three columns"> <label for="{{ form.username.id_for_label }}">Username</label> <input name="{{ form.username.html_name }}" class="u-full-width" type="text" placeholder="inventor02" id="{{ form.username.auto_id }}" maxlength="34" required> </div> <div class="three columns"> <label for="{{ form.discriminator.id_for_label }}">Discriminator</label> <input name="{{ form.discriminator.html_name }}" class="u-full-width" type="number" placeholder="4201" id="{{ form.discriminator.auto_id }}" maxlength="4" required> </div> <div class="six columns"> <label for="{{ form.current_rank.id_for_label }}">Current Rank</label> <input name="{{ form.current_rank.html_name }}" class="u-full-width" type="text" placeholder="Member" id="{{ form.current_rank.auto_id }}" maxlength="30" required> </div> </div> <label for="{{ form.application.id_for_label }}">Application</label> <textarea name="{{ form.application.html_name }}" class="u-full-width" placeholder="I would like to be staff because..." id="{{ form.application.auto_id }}" required></textarea> <input class="button button-primary" type="submit" value="Submit"> </form> views.py def submit(request): if request.method == "POST": form = ApplicationForm(request.POST) print(request.POST) if form.is_valid(): print(form) application = Application(username=form.cleaned_data["username"], discriminator=form.cleaned_data["discriminator"], current_rank=form.cleaned_data["current_rank"], application=form.cleaned_data["application"]) application.save() return HttpResponse("<h1>Success!</h1>") else: return HttpResponse("Invalid form request. Try again.") else: return HttpResponse("You're accessing this using the wrong method. Go to the <a href=\"/apply\">apply</a> page.") forms.py class ApplicationForm(forms.Form): username = forms.CharField(max_length=34) discriminator = forms.IntegerField(max_value=9999) current_rank = forms.CharField(max_length=30) application = forms.TextInput() models.py class Application(models.Model): username = models.CharField(max_length=34) discriminator = models.PositiveIntegerField() current_rank = models.CharField(max_length=50, default="Member") application = models.TextField() … -
How to integration testing of internal POST requests using Django?
I have a Django project using Django Rest Framework with two apps (events and logs) and associated endpoints /events and /logs Clients can POST to /events some information about an event, the processing of this will record a log in the logs app model. The logs can then be retrieved using GET on /logs. Whilst the events view can update through the logs view directly, I wanted to implement this through a POST call to /logs call to keep the interfaces more well defined and easier to split out into a completely separate service if required. The POST call is handled using requests package as follows: from rest_framework.views import APIView import requests class Events(APIView): def post(self, request): # Some event handling code... # Record log log_url = request.build_absolute_uri(reverse('logs')) requests.post(log_url, data=event) To test this works I boot up the server and do: POST /events/ (post some JSON data) GET /logs/ In this case I see some log data returned from the GET request, so I know that e2e the implementation works. However, when I try to automate this using django.test.LiveServerTestCase the response is always empty. from django.test import LiveServerTestCase from rest_framework.test import RequestsClient class AppsEndpointTest(LiveServerTestCase): def test_post_event_retrieve_logs(self): events_endpoint = self.live_server_url + … -
Should I add urls.py to cihld app?
I am making users' images upload system. But when I run server,I got a error, urlpatterns = patterns('') NameError: name 'patterns' is not defined. My app has 2 app,one of them is a parent and another is child. In a parent app of urls.py,I wrote from django.conf.urls import url from django.contrib import admin from django.conf.urls import include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'accounts/', include('accounts.urls')), url(r'api/', include('UserToken.urls')) url(r'^media/(?P<path>.*)$','django.views.static.serve', {'document_root': settings.MEDIA_ROOT}) ] in views.py of children app, from django.shortcuts import render # Create your views here. import os import uuid from PIL.Image import Image from django.views.generic import View from django.conf import settings class ImageTop(View): """ 画像に設定する画像処理 古い画像ファイルの削除処理 """ def get_image_top_path(self, filename): """ カスタマイズした画像pathを取得する UUIDにして画像ファイル名をhash化 :param self: インスタンス(model) :param filename: 元の画像ファイル :return: カスタマイズしたファイル名を含む画像パス """ prefix = 'test/' name = str(uuid.uuid4()).replace('-', '') extension = os.path.splitext(filename)[-1] return prefix + name + extension def delete_previous_file(self, function): """ 不要となる古い画像ファイルを削除する為のでコレータ実装 :param function: メイン関数 :return: wrapper """ def wrapper(*args, **kwargs): self = args[0] #保存前の画像ファイル名取得 result = Image.objects.filter(pk=self.pk) previous = result[0] if len(result) else None super(Image, self).save() #関数実行 result = function(*args, **kwargs) #保存前のファイルがあったら削除 if previous: os.remove(MEDIA_ROOT + '/' + previous.image.name) return result return wrapper<span style="font-family: Arial;"> </span> Run code snippetCopy snippet to answerExpand snippet in models.py of a child app, … -
showing a field of type list in django admin
I am new to django so don't know much about it. my problem is that i am using multiselect in models in one field. S when i am trying to show that field in admin using list_display, it's giving an error of unhashable type:list. please help. my models.py:: language = MultiSelectField( choices = LANG_CHOICES, null = False, blank = False, ) my admin.py:: from django.contrib import admin from .models import Newspapers class NewspaperAdmin(admin.ModelAdmin): list_display = ['id','language','title','price'] and error is: TypeError at /admin/newspapers/newspapers/ unhashable type: 'list' -
Django update an instance using another instance
For instance, I have instance a1 and a2. I'd like to update a1 to be same as a2. Following is what I came up with, not sure if it will work though and if there's a better way. a2_data = model_to_dict(a2, exclude=['id']) A.objcects.filter(id=a1.id).update(**a2_data) -
Custom django-revproxy permissions
I am using django-revproxy which proxies requests from my api to another api. How can i separate permissions for users? For example, i have url: urls.py: url(r'^posts(?P<path>.*)$', ProxyView.as_view(upstream='http://example.com/posts')), For admin i need all GET/PUT/POST/PATCH/DELETE requests on ProxyView, which i get by default, but for custom users i need custom permissions, for example, i need only GET request for one_user on ProxyView, GET/PUT for second_user. How can i implement this? -
Django channels randomly connecting only 2 people
I am familiar with channels and how to connect people to a chat as well as how to connect only 2 people. What I am interested in is how I can connect 2 people on a random basis from the people who are online or is that even possible? Example: User1 clicks a button and user2 clicks the button too and so they are in something like a list with people that are online, then I randomly pick the 2 of them to connect to each other in a private room only for them for a certain amount of time I will be glad to see some examples or if there is a similar project somewhere on the internet -
Permission denied when trying to open Firefox to run Selenium tests via Django's manage.py
I'm running on Ubuntu 16.04. I've been dealing with this issue for a while now, and I have not been able to find a solution on my own. When I run python3 manage.py test, my tests are to open a Firefox browser via Selenium and execute some functional tests. I get the same error message on every test I try to run; selenium.common.exceptions.WebDriverException: Message: Failed to start browser /home/spa/Desktop/firefox: permission denied I have tried to do chmod a+rwx on the firefox folder, but I still get the same error. Attempting to sudo python3 manage.py test results in the same issue. Any help would be appreciated. -
Amazon EBS Django 404 Error. The requested URL / was not found on this server
So I finally finished my project, creating dads website, and followed these instructions to deploy it to ebs: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html However, when I go to http://django-env.ethmrbkmgd.us-east-1.elasticbeanstalk.com/ I get the error: The requested URL / was not found on this server. On my local server the website runs perfectly. After researching I discovered that people said it had to do with trailing back slashes in urls.py but this seemed to not fix it. Another person recommended to change allowed hosts to ALLOWED_HOSTS = ['*'] but that has not work either. Here is my project layout suliman_baldo bin include lib media_cdn src .ebextensions django.config .elasticbeanstalk config.yml gallery main static suliman_baldo settings.py urls.py My urls.py file is from django.conf.urls import include, url from django.contrib import admin from gallery import views from django.conf.urls.static import static #testing from django.conf import settings from django.conf.urls import patterns urlpatterns = [ url(r'^/$', "gallery.views.gallery"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here are the config files django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: src/wsgi.py config.yml branch-defaults: default: environment: django-env environment-defaults: django-env: branch: null repository: null global: application_name: suliman_baldo branch: null default_ec2_keyname: aws-eb default_platform: Python 2.7 default_region: us-east-1 profile: eb-cli repository: null sc: null