Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djano url routing for one app
I am trying to return different templates for different urls (having just one app), so basically I want to return: One template for:http://127.0.0.1:8000/projects/ Another template for:http://127.0.0.1:8000/formpage/ I have the project urls.py: `from django.conf.urls import url,include from django.contrib import admin from appone import views urlpatterns = [ url(r'^admin/', admin.site.urls), #home page url(r'^$', views.index, name='index'), url(r'^projects/', include('appone.urls')), url(r'^formpage/', include('appone.urls')), ]` And the app urls.py: `from django.conf.urls import url,include from django.http import HttpResponse from . import views urlpatterns = [ url(r'^$', views.projs, name='proj'), url(r'^$', views.form_view, name='form_view') ]` I have the views and templates , that are good, but I do not understand how can I return them based on the url, because for the moment I return the first view from app urls.py, for both urls. -
Django admin list view show external url data in custom column
we have a list view something like below Now lets say we want to add one more column in the view which doesn't exist in model. so we can do that by creating a method inside admin class. class PageAdmin(admin.ModelAdmin): list_display = ["id", "title", "slug", "author", 'updated', 'custom_field'] def custom_field(self, obj): # logic... return True # or False based on above logic This is simple. Now lets take a more complicated scenario where I need this column to be populated based on the result of goodreads.com search. I mean I'll search objects title on goodreads and find the exact title if found then will return True else False. For e.g there is a page object and title of this is hunger games so when I search this, I'll get https://www.goodreads.com/search?utf8=%E2%9C%93&query=hunger+games I'll parse the result and check if exact title exist in top 10 results. class PageAdmin(admin.ModelAdmin): list_display = ["id", "title", "slug", "author", 'updated', 'custom_field'] def custom_field(self, obj): # search on goodreads.com, parse results and match with obj.title return True # or False based on above logic The problem with this approach is that it makes admin page very slow.. since it will get data for all objects in a page(normally … -
Can anyone recommend an open source platform for workflow management?
I am about to start building a workflow platform for document management. It's a relatively simple concept requiring user accounts, form submission, and form review/approval between users (think analyst->manager->director). Documents are attached to forms, and the forms have pre-configured fields. Is there a solid opensource framework that anyone can recommend that would provide simple building blocks for this approach? I'm thinking like how Bootstrap is a great framework for CSS, is there a platform that handles user accounts and workflow basics well? I was thinking about starting with Django but would also appreciate views on other platforms. -
How to undo serialize list on Django
I serialized a list of Django models like this: serialize_list = serializers.serialize("json", my_list) and now I want to deserialize it and get back a list of Django models. Instead, when I do deserialize_list = serializers.deserialize("json", serialize_list ) I get a list of DeserializedObject models and not the original list. My question is: how can I get the original list back? -
Are Django test fixtures loaded multiple times?
In my tests, I have a Django super class with the sole purpose of setting up data and defining some utility methods used in the tests. It also has the fixtures used in the different TestCase subclasses. class MasterTest(django.test.TestCase): fixtures = ['appname/fixtures/fixture1.json', 'appname/fixtures/fixture2.json'] class TestCase1(MasterTest): pass class TestCase2(MasterTest): pass My questions is whether when running TestCase1, TestCase2 and others, the fixtures defined by MasterTest will be run multiple times (one for each case) or only one, since they are defined in the super class. If they are loaded every single time, is there a way to load fixtures only once? -
Why doesn't None put in variable?
Why doesn't None put in variable? I wrote in code like def check(request): if len(request.POST.get('access_key')) >= 25: return HttpResponse('<h1>Hello</h1>') elif request.POST.get('access_key', None) == None: id_json = {} return JsonResponse(id_json, safe=False) else: return HttpResponse('<h1>Good</h1>') Now I put anything to access_key in POSTMAN like I think in this case the program goes into elif request.POST.get('access_key', None) == None:,but now it goes into else:. I really cannot understand why the null value is not recognized as None. I wrote print(type(request.POST.get('access_key'))) and blank is printed out. I wanna make a system if no value is put, and the program should go into elif request.POST.get('access_key', None) == None:. How should I fix this? -
create custom model field in django
I want to create custom model field that accepts strings in special format then convert and store it as integer and restore and convert it to the previous format , also need to change it's form field to render as a Char Field , what should I do?! I've done it but it doesn't work correctly class JalaliEpochTimeField(models.BigIntegerField): description = "A field to save strings in Jalali date format as epoch (big int) in db" def from_db_value(self, value, expression, connection, context): if value is None: return value return epoch_to_khayyam(value) def to_python(self, value): print("to_python") if isinstance(value, JalaliEpochTimeField): return value if value is None: return value return khayyam_str_to_epoch(value) -
Error while running two django apps on different ports of a server
I'm trying to run two django apps on different ports of a server using Apache and WSGI. Here is my VehicleDataEntry.conf (listening to port 80) file: <VirtualHost *:80> ServerAdmin webmaster@example.com ServerName 104.218.50.242 DocumentRoot /website_data/sites/VehicleDataEntry/static/ WSGIScriptAlias / /website_data/django/VehicleDataEntry/VehicleDataEntry/wsgi.py Alias /static/ /website_data/sites/VehicleDataEntry/static/ </VirtualHost> WSGIPythonPath /website_data/django/VehicleDataEntry/ <Directory "/website_data/sites/VehicleDataEntry/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory "/website_data/django/VehicleDataEntry/VehicleDataEntry"> <Files wsgi.py> Require all granted </Files> </Directory> QuotationMaker.conf (listening on port 8080): <VirtualHost *:8080> ServerAdmin webmaster@example.com ServerName 104.218.50.242 DocumentRoot /website_data/sites/QuotationMaker/static/ WSGIScriptAlias / /website_data/django/QuotationMaker/QuotationMaker/wsgi.py Alias /static/ /website_data/sites/QuotationMaker/static/ </VirtualHost> WSGIPythonPath /website_data/django/QuotationMaker/ <Directory "/website_data/sites/QuotationMaker/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory "/website_data/django/QuotationMaker/QuotationMaker"> <Files wsgi.py> Require all granted </Files> </Directory> Now the VehicleDataEntry's wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ["DJANGO_SETTINGS_MODULE"] = "VehicleDataEntry.settings" application = get_wsgi_application() application = DjangoWhiteNoise(application) QuotationMaker's wsgi.py file: VehicleDataEntry's wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ["DJANGO_SETTINGS_MODULE"] = "VehicleDataEntry.settings" application = get_wsgi_application() application = DjangoWhiteNoise(application) The Problem: VehicleDataEntry app is running without any problem, however, when I try to access QuotationMaker on port 8080, it returns 500 Internal Server Error. When I checked the httpd/logs/error_log, I get the following error: ImportError: No module named QuotationMaker.settings I know there is something wrong … -
Django Pillow saving thumbnail image
When trying to save only the thumbnail version of the form posted image I get the following error. 'JpegImageFile' object has no attribute 'write' Using either of the following will produce the same error. I think that what I'm missing here is some kind write mode definition. The Image.open only accepts 'r' mode though. Model save method def save(self, *args, **kwargs): img = Image.open(self.image) img.thumbnail((250, 250), Image.ANTIALIAS) img.save(img, 'JPEG') super(EventPost, self).save() Formviews form_valid method def form_valid(self, form): img = Image.open(form.cleaned_data['image']) img.thumbnail((250, 250), Image.ANTIALIAS) img.save(img, 'JPEG') form.save(commit=True) return super(FormPage, self).form_valid(form) -
how to import date time data from excel into django model(mysql)?
I have a question about django admin import file. my excel data include DateTime data like 2010/10/10 13:10 , i want to import it into mysql by django admin. I used DateTimeField in models. What is the time data format? how to do this? -
django + apache + mod_wsgi + ssl error, hasattr not defined
Only when I use SSL, apache refuses to start, and I see this error in error.log: File "c:\python36-32\lib\site-packages\PIL\Image.py", line 585, in del NameError: name 'hasattr' is not defined If I comment out the line Include extra/httpd-ssl.conf, then apache will start fine. (but without ssl of course) I checked the httpd-ssl.conf file, and I think my certificate is correctly set. And this error does not imply anything. I couldn't find a solution online. -
How to import mixin into all serializer - Django Rest Framework
I am having n- number of serializers in my current app.. i want to add one more mixin in header like ModelSerializer into all serializer like, class AdminSerializer(CustomMixin, serializers.ModelSerializer): now i am applying manually.. is their a way to override to apply all together? -
Django - Delete particular field data from model
I am trying to delete a field's data from Django model. Suppose I have a model named UserData and I want to delete city field for record_Id = 1, without deleting the data from other fields for record_Id = 1. I used: UserData.objects.filter(city="London").delete() but it deletes the whole record. I tried this method on SO, but gives attribute error Delete field from standard Django model . Let me know how to do this. Thanks! -
ImportError: cannot import name 'DependencyWarning' I cannot do anything
I got an error, ImportError: cannot import name 'DependencyWarning' Traceback (most recent call last): File "C:\Users\xxx\AppData\Local\Continuum\anaconda3\envs\py36\Script s\pip-script.py", line 6, in <module> from pip import main File "C:\Users\xxx\AppData\Local\Continuum\anaconda3\envs\py36\lib\si te-packages\pip\__init__.py", line 21, in <module> from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarni ng ImportError: cannot import name 'DependencyWarning' . I searched solution in google,so I found pip uninstall requests maybe solve this problem but in this time also cannot import name 'DependencyWarning''s error happen.When I run command pip uninstall pip,same error happens. I cannot do anything,so how can I fix this? By the way,now I cannot use request arguments like def happy(request): if len(request.POST.get('key', None)) ==2: print("Happy!!") always request.POST.get('key', None) get None.Is this problem link with this error? -
Access GET request in another method django
I have a form elements in my html. <form action="" method="GET"> <input type="text" name="start_date" placeholder="From" value="{{ request.GET.start_date }}"> <input type="text" name="end_date" placeholder="To" value="{{ request.GET.end_date }}"> </form> I want to access to the start_date and end_date inside one of my view.py methods, but Im getting None all the time. So far I have tried: temp = request.GET.get('start_date', None) temp = request.GET['start_date'] What might be the problem? How can I access start_date and end_date? -
Is there a way to validate fields without form tag and forms.py?
As the title said,I've been figuring out how to put error messages per field on html with django, since we were taught to do ajax without the use of forms.py nor form tags. Is there a solution for this? Or am I required to create forms for each? Example: edit account function html {% for user in users %} <!--start EDIT MODAL --> <div id="editAcct-{{user.id}}" class="modal fade" role="dialog" aria-hidden="true"> {% csrf_token %} <div class="modal-dialog"> <div class="modal-content"> <div class="form-horizontal form-label-left input_mask"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close" required><span aria-hidden="true">×</span> </button> <h3 class="modal-title" id="myModalLabel">Edit {{ user.username }}</h3> </div> <input type="hidden" name="pkid" id="pkid" class="form-control" value="{{ user.id }}"> <div class="modal-body"> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="id-num">ID Number </label> <div class="col-md-8 col-sm-6 col-xs-12"> <input type="number" name="id-num" id="id-num-{{ user.id }}" class="form-control" value="{{ user.profile.employeeID }}" required> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">First Name </label> <div class="col-md-8 col-sm-6 col-xs-12"> <input type="text" id="first-name-{{ user.id }}" name="first-name" class="form-control" value="{{ user.first_name }}" required> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Last Name </label> <div class="col-md-8 col-sm-6 col-xs-12"> <input type="text" id="last-name-{{ user.id }}" name="last-name" class="form-control" value="{{ user.last_name }}" required> </div> </div> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="user-name">Username </label> <div class="col-md-8 col-sm-6 … -
How to Integrate Django Administration within my own Website
I have a webpage and an option to create an admin in that (Only front end is developed), once the admin is created(Upon clicking on the Create Admin button), script should create An actual Django admin and should have permission to view the webpage. How I can do this is in Django? -
POST method with 2 form in CBV | Django?
I have 2 forms in one template: UserEditForm and UserRoleForm. As you can see UserRoleForm is a custom Form. How to save form data by post method in Class Based View? get method works fine but I cant save data by post method. Next code raise error which you can see below. It seems to me I try to save forms incorrectly in post method. Where is my mistake? forms.py: class UserEditForm(UserChangeForm): class Meta: model = User exclude = ('groups', 'is_superuser', 'is_staff', 'user_permissions',) class UserRoleForm(forms.Form): CHOICES = ((0, _('Admin')), (1, _('Moderator')), (2, _('Simple User'))) user_role = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) def __init__(self, *args, **kwargs): super(UserRoleForm, self).__init__(*args, **kwargs) self.fields['user_role'].widget.attrs = { 'id': 'user_role', } view.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm second_form_class = UserRoleForm model = User def post(self, request, *args, **kwargs): form = self.form_class(self.request.POST) second_form = self.second_form_class(self.request.POST) if form.is_valid() and second_form.is_valid(): new_user = second_form.save(commit=False) user_role = second_form.cleaned_data['user_role'] if user_role==0: new_user.is_superuser=True elif user_role==1: new_user.is_staff=True elif user_role==2: new_user.is_superuser=False new_user.is_staff=False new_member.save() form.save() data = dict() data['form_is_valid'] = True context = {'users': User.objects.order_by('username')} data['html_users'] = render_to_string('users/users.html', context) else: data = dict() data['form_is_valid'] = False data['form_errors'] = form.errors return JsonResponse(data) ERROR: Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) … -
How to switch between multiple database servers in Django automatically.?
I have set up a Master remote MySQL database server and a replica of it configured as a slave database for my Django application. Both running on amazon ubuntu ec2 instance. How can I configure Django to access slave database automatically in case the Master database is down.? -
"Invalid Credentials given" error with valid credential (o-auth-provider)
I'm following OAuth2 provider tutorial. After setting up everthing correctly, I'm getting this error. Invalid Credentials given What am I doing wrong with request? I checked my username and password but it's 100% valid. curl -X POST -d "grant_type=password&username=admin&password=j1357924680" -u"TEAfdIRw5cE664Pd4X31wuD7y08er8Suim3SdZsr:dI65CQwo9glm9LN63twmqDSY2DHR9bbPqlSEIwktaOzMfAS7sSFirzCKi9enogNZmyHjqQeIYIqtwKY6RIUC7Lto22s4vDtB0Y7F5unffLdktHXPyPn7j593IAeHfTDp" http://localhost:8000/o/token/ (If you want to see its actual source code) https://github.com/jbaek7023/DRFOAuth2 OAuth2 is very complicating -
Should you deploy django with wsgi?
Do you need to deploy django with wsgi? I am running Django on a Docker instance and it seems like often the recommended solution is just to use Django's development server, i.e. the command python manage.py runserver. When exactly is a web server such as wsgi needed -- and in this instance, in a containerized application, is the django development server enough for production applications? -
is update_session_auth_hash and session are different?
I can use default 'login' form to login using django.contrib.auth.views for user to login. The source code for the same has some session with update_session_auth_hash(). I am wondering if this is same as session in django.contrib.sessions ??? All I want is to create a session when I use default login form from django.contrib.auth.views -
Allow users to upload images to my S3 bucket - Django
Can anyone give me a walkthrough of cors and policy setup on s3? I've followed various tutorials for settings up the AWS settings such as access key, bucket name, with boto and storages. Collectstatic works fine but whenever logged in to a user account to say upload a profile image it says that the bucket is read-only a 500 error is hit. My forms work fine everything is fine on local. Just an AWS issue moving to production. Ideally, only users from the website would be able to upload images. SO, not allowing open access. -
How to deploy a django repo from github to ansible locally?
I am beginner to ansible . I am trying hard but not succeeding . This is the git repo :https://github.com/Atif8Ted/test_blog It is a django based app . It is also hosted on heroku . And I want to host it locally on my ubuntu machine . How to do that . I am unable to follow the documentation . -
How do I customize a user registration form so it only requires email and password fields?
I'm following this tutorial on making simple registration forms in Django. I'd like to make a user registration form that requires only two fields: "Email" and "Password." No second password field, just one. So far, My views.py looks like this: def register(request, template="register.html", redirect='/'): if request.method=="POST": form= RegisterForm(request.POST) if form.is_valid(): form.save() email= form.cleaned_data.get("email") raw_password= form.cleaned_data.get("password1") user= authenticate(email=email, password=raw_password) login(request, user) return redirect('/') else: form= RegisterForm() return render(request, template, {"form": form}) forms.py has this class in it: class RegisterForm(UserCreationForm): email= forms.EmailField(label=_("Email"), max_length=254) class Meta: model= User fields= ("email",) register.html looks simple: {% extends "base.html" %} {% block main %} <h2>Register</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> {% endblock main %} In urls.py, I have this line in urlpatterns: url("^register/$", views.register, name="register"),. But my registration forms looks like this, with an Email field and two Password fields: http://i.imgur.com/b359A5Z.png. And if I fill out all three fields and hit "Register," I get this error: UNIQUE constraint failed: auth_user.username. Any idea why I'm getting this error? And how can I make sure my form only has two fields: Email and Password?