Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to include telugu language in django forms
Model: class Application(models.Model): full_name = models.CharField(max_length=40) father_or_husband_name = models.CharField(max_length=20) nominee_name = models.CharField(max_length=20) date_of_birth = models.DateField() job = models.CharField(max_length=20) address = models.CharField(max_length=20) mobile_no = models.CharField(max_length=10) Forms: class ApplicationForm(forms.ModelForm): class Meta: model = Application fields = ('full_name', 'father_or_husband_name', 'nominee_name', 'date_of_birth', 'job', 'address', 'mobile_no') In my template the fields display as: Full Name: Father Or Husband Name: Nominee Name: Date Of Birth: Job: Address: Mobile No: I want these fields in my native language Telugu. -
Connecting to Heroku Postgres with Django
I am trying to migrate my Postgres database that I created via Heroku, so that I can a superuser for my Django project. Using heroku run python manage.py migrate Produces the following error in my heroku logs django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I believe this is because the project cannot connect to the server, but I am not sure why. In my production settings.py, I have the following: from .base import * import dj_database_url ALLOWED_HOSTS = ['herokuappurl.herokuapp.com'] DATABASES = { 'default': { } } db_from_env = dj_database_url.config() print(db_from_env) DATABASES['default'].update(db_from_env) I printed the contents of db_from_env just to make sure that the credentials listed in the dictionary match what is in my heroku config. Can anyone point me in the right direction? Thank you. -
django aws s3 image resize on upload and access to various resized image
I would like to be able resize my uploaded image to various size categories: original medium (500kb) small (200kb) And save it to AWS S3. And later be able to access it. One strategy is to save it in filename_small.jpg, filename_medium.jpg, have a helper function to be able to append the _small, _medium to access those files. Im not sure how to save all the different files (resized) and then access it with the helper. https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): ... face_image = models.FileField(upload_to=upload_to('employee/face_image/'), blank=True, storage=MediaStorage()) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def update_employee_image(request): ... employee = Employee.objects.get(id = employee_id) employee.face_image = face_image_obj employee.save() I am using django-storages and S3Boto3Storage. My full working project is in the git links. -
Django: Trying to create a user score system
So instead of making this into a new app or actually add it to the User model I want to just calculate this in the view. So here are two lines of code that I've added to get the number of posts a user has created and then multiplying it by 10 (the value I'm giving to adding a post) in the view and then passing it into the template. However, I am getting an error. Not sure if I'm going about this in the best way, but heres what I have. Code the in the view: posts = UserPost.objects.filter(author=user) posts_count = posts.len() * 10 The error: AttributeError at /user/2/ 'QuerySet' object has no attribute 'len' I also tried with .count instead of .len() -
Automatically downloading PDF using Django running code on multiple ports
When a user uploads a PDF, it is modified using ReportLab and the modified PDF is automatically downloaded. Below is my code for processing the files and returning them. def process_report(request): # Handle file upload if request.method == 'POST': report_file = request.FILES.pop('file')[0] merged_pdf, namefinal = pdfAnalyzingFunction(report_file) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(namefinal) response.write(merged_pdf.getvalue()) return response else: return HttpResponseBadRequest('Must be Post') I am using Django to render and return content. The above code worked and was able to download files automatically when I just had some simple HTML on a localhost:8000 port. However, after building a frontend on a different port, localhost:3000, I was able to successfully run and generate a modified PDF but it no longer downloaded automatically (with the PDF modifying code running on the localhost:8000 port still). On my localhost:3000 port network tab I can see the uploaded file, and am wondering why it is not downloading. Request URL: http://localhost:8000/process_report Request Method : POST Satus Code: 200 OK Host: localhost:8000 Origin: http://localhost:3000 Referer: http://localhost:3000/ Unclear as to why it appears my PDF is rendering, but not automatically downloading now. Is there something I need to know about generating a response object on one port and attempting to … -
Django admin: using inlines through a ManyToMany relationship
Consider the following models.py, where a Group contains multiple Persons who each have zero or more Phone numbers. In this particular case, Persons who share a Group will often share at least one Phone number, so a many-to-many relationship is used. class Group(models.Model): name = models.CharField(max_length=30) class Person(models.Model): group = models.ForeignKey(Group) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Phone(models.Model): persons = models.ManyToManyField(Person) number = models.CharField(max_length=30) I would like to show these models in the Django admin, in a single view, as shown below. class PersonInline(admin.StackedInline): model = Person class PhoneInline(admin.StackedInline): model = Phone # also tried: Phone.persons.through @admin.register(Group) class GroupAdmin(admin.ModelAdmin): inlines = [PersonInline, PhoneInline] However, there is no foreign key between Group and Phone, so this raises a SystemCheckError (one of the following): <class 'myapp.admin.PhoneInline'>: (admin.E202) 'myapp.Phone' has no ForeignKey to 'myapp.Group'. <class 'myapp.admin.PhoneInline'>: (admin.E202) 'myapp.Phone_persons' has no ForeignKey to 'myapp.Group'. Is it possible to make this work through the Person model? The goal is for the Phone inline to show phone number records for all Persons in the Group (bonus: when adding a new Phone, the Person SelectMultiple widget will need to only show other Persons in the Group). I would prefer to avoid modifying any templates. A third-party … -
migrate database from Sqlite3 to Postgres = Django
I have a small app that I have build and I am planning on transfering it to a live environment. This app scales really quickly. I currently have Sqlite3 as the database stack I am using for my project. I wanted to know if it is smart for me to switch to PostgreSQL before I host my project in a live environment. My app is currently running through docker images and sqlite3 works find on docker, but I feel like later on when I am dealing with lots of requests, PostgreSQL would be better off for me. If it is a good idea to switch from sqlite3 to PostgreSQL, I know I have to do the following lines, but I am not sure what I have to change in the django settings python page...: python manage.py dumpdata > dump.json Change DB connection string in settings.py to POSTGRES python manage.py syncdb python manage.py loaddata data.json login to postgres db using psql - execute this to delete all the data in the content_types table truncate django_content_type RESTART IDENTITY CASCADE; python manage.py loaddata data.json So would the settings.py file look something like this compared to current setup: current: DATABASES = { 'default': { … -
getting checkbox value but it returned none in django templare
please help me a bit. I'm kind of stuck for a while now. Any advice would be nice. So, I want to pass a value from a checkbox to my view. Here my template that contains the checkbox. <form method="POST" action="{% url 'search:specs' %}"> {% csrf_token %} {% for page in all_page %} <div class="row"> <h1> {{ page.info }}</h1> <div class="well"> {% for item in page.searchitem_set.all %} <div class="list-group"> <input type="checkbox" id="items" name="compare" value="{{ item.id }}"> and this is my view def specs(request): compare_item = request.POST.get('compare') print(compare_item) #item1 = compare_item[1] item = get_object_or_404(SearchItem, id=compare_item) The print() command returns a None. -
the editable in django's field option
when i study the django model field, i see the "editable" in field option. says: if false,the field will not be disdplayed in the admin or any other ModelForm.They are also skipped during model validataion.Default is True. so,it means ,we can not see the value in django site? and form model can not use it ? and it will not check the value when we save it?(from the word, "They are also skipped during model validataion") Why we should use this "editable" attribute in django? or ,what is the situation should we use "editable"? i need a example ,which can guide me how to use the "editable" thanks very much. -
Django unicode has no attribute _meta
I'm a new to Python and Django! and working on django tutorial and somehow customizing the way to log in by using my own database. What I want is that a user only needs their email to login. However, when I log in my test website, I have ''unicode' object has no attribute '_meta' error. *views.py // login(request, email) is suspicious. def login_view(request): if request.method == "POST": form = LoginForm(request.POST) email = request.POST['email'] user = EmailAuthBackend.authenticate(email=email) if user is not None: login(request, email) return redirect('../mypage') else: return HttpResponse(email) else: form = LoginForm() return render(request, 'myapp/login.html', {'form': form}) *CustomBackend.py class EmailAuthBackend(ModelBackend): def authenticate(self,email=None): try: user = Customer.objects.get(email=email) return user except Customer.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except Customer.DoesNotExist: return None