Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python3.6 on CentOS certificate verify failed
My Django application is currently running on Python 3.4. I want to move it to 3.6, but I have an issue with SSL certificates. The same application works perfectly fine on python 3.4. It still works fine with python3.6 within Docker container and on Windows PC. The only problem is with CentOS and RedHat (both 6.5). My OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013. Full error: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)> What can I do to fix that? The problem is only for python 3.6.0 and python 3.6.1. Python 3.4 works fine with that code. -
Using pdb with supervisor
I am running my django app using docker compose. Ngninx and gunicorn are run via supervisor. However I can't seem to figure out how to debug using pdb. When I use: import pdb pdb.set_trace() After running the command docker-compose up, my app and database begin to run and the terminal screen remains active waiting for further output to display. When my code reaches pdb.set_trace(), the aforementioned terminal remains as is but the (pdb) interface does not appear. Would anyone know how I might be able to debug my application using pdb? Is there something else that I need to use? Thank you. -
post-save signal doesn't get called in Django
Whenever a new User instance is created, I want to create a Profile instance linked to it. To do this, I'm trying to use signals. here's code from models.py: @receiver(post_save, sender=User) def create_user_profile(sender,**kwargs): print(sender) And here's from view.py: @api_view(["POST"]) def register(request): username = request.data.get("username") first_name = request.data.get("first_name") last_name = request.data.get("last_name") email = request.data.get("email") password1 = request.data.get("password1") password2 = request.data.get("password2") user = User.objects.create_user(username,email,password1) if user: user = authenticate(username=username, password=password1) if not user: return Response({"error": "Login failed"}, status=HTTP_401_UNAUTHORIZED) token, _ = Token.objects.get_or_create(user=user) return Response({"token": token.key}) However, nothing gets printed to my Terminal when a new User is created. -
Django display a page title based on a variable stored in a view
I’m a bit stuck on how to display the titles for 2 pages that list articles of different categories using the same template. My article models have content, category (sport, politics, tech etc) and status. I want to display a page listing all sport articles and a page listing politics and I want to use the same template. I have tried storing the title as a variable in the view but this doesn't work Views.py def sport_landing(request): page_title = 'Sport' cat_landing = Article.objects.filter(status='published', category='sport', published_date__lte=timezone.now() ).order_by('-published_date') return render(request, "categorylanding.html", {'cat_landing': cat_landing} Template {% extends 'base.html' %} {% load humanize %} {% block content %} <div class="row category-landing-title"> <div class="col-xs-12"> {% page_title %} </div> </div> . . . Is this even the best way to do this? -
django how do I know which checkbox was checked
I did my best to find the answer, but didn't. My .html code: {% for beer in beers %} {{ beer.drink_name }} ................. {{ beer.price }} <div class="menu_choice"> <input name=beer_{{beer.id}} type="checkbox" class="inline" id="1"/> <select class="menu_choice_count"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </div></br> So there is a loop that prints data, a drop box and a check box. A list will be visible for the user. The user can then choose what to order and click 'order' button. Now based on the check box checked the particular item from the menu should be saved in my db. How do I do that? thank you all for your help. -
Allow one and only one field from fields subset in Django model
I have a model Model. This model have multiple attributes, three of them are: domaintld, subdomain, url - OneToOneFields. I'm trying to allow one and only one from these fields to be non empty. My approach works but I'm curious if it's there a better way to do this (I use PostgreSQL). def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.clean() super(Model, self).save(force_insert, force_update, using, update_fields) def clean(self): super(Model, self).clean() if not(((bool(self.url) ^ bool(self.domaintld)) ^ bool(self.subdomain)) and not(self.url and self.domaintld and self.subdomain)): raise exceptions.ValidationError("One and only one field can be used: url,domaintld,subdomain") -
How to prevent JWT Django (all-auth) from changing token when its username is updated?
I'm using all-auth / django-rest-auth for Authorization. When the User changes his/her username, Django (Django REST Framework) changes user's token and this makes user log-out from app; I set the app to logout if its user's token is invalid. What I want to do is that even if user changes username, email, or any field in User, it keeps token. Here is settings.py REST_USE_JWT = True AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', ) JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30), } ... Thanks! -
Changing help without refactoring the whole code
I have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc 1- If I pull NHL data inside a .csv file, will he be able to process information in Excel from that file? 2- Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. Please let me know if the question is unclear. -
Username and password authentication in django
I need to validate username and password in django app, below are the details view is, class HomeView(TemplateView): template_name = 'home.html' template_name2 = 'Logout.html' def get(self,request): form = LoginForm() posts=users_data.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) return render(request,self.template_name, {'form':form}) #template_name2 = 'Welcome.html' def post(self,request): form = LoginForm(request.POST) if form.is_valid(): #text=form.cleaned_data['post'] username = forms.cleaned_data.get("Username") password = forms.cleaned_data.get("Password") user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exist") return render(request, self.template_name1) else: form.save() return render(request, self.template_name2) else: return render(request, self.template_name1) after entering username and password it is giving me error and doing nothing. I am stuck at this point . Requesting for help. my form is, from django import forms from login.models import * from django.contrib.auth import authenticate,login,logout,get_user_model user=get_user_model() class SignupForm(forms.ModelForm): class Meta: model=users_data fields=('Name','Email','Username','Password') class LoginForm(forms.ModelForm): class Meta: model=users_data fields=('Username','Password') def clean(self): username = self.cleaned_data.get("Username") password = self.cleaned_data.get("Password") user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("This user does not exist") -
django-jquery-file-upload: filtering images only for a service
I've configured django-jquery-file-upload to upload files for a service. Here's the code for the view # encoding: utf-8 import json from django.http import HttpResponse from django.views.generic import CreateView, DeleteView, ListView from .models import Picture from .response import JSONResponse, response_mimetype from .serialize import serialize from accounts.models import UserService class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'accounts/upload-file.html' def form_valid(self, form): self.object = form.save() user_service = self.request.COOKIES.get('service_id', None) if user_service: exists = UserService.objects.filter(id=user_service) if exists: service = exists[0] obj = self.object obj.user_service = service obj.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') and from the models... # encoding: utf-8 from django.db import models from accounts.models import UserService class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) user_service = models.ForeignKey(UserService, related_name="uploads", blank=True, null=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) … -
What is the usage of dispatch in django class base view
Django ListView have a method dispatch(). According to Django documentation dispatch is The method that accepts a request argument plus arguments, and returns a HTTP response. Have been searching for more information but couldn't find any neither can understand properly. Can anyone explain me a bit deeper for a better understanding. -
pip install django~=1.11.0 command = AttributeError: 'tuple' object has no attribute 'filename'
I am trying to install Django after pip upgrade through command: pyhton -m pip install --upgrade pip Then, when i run this command: pip install django~=1.11.0 I get tons of errors : AttributeError : 'tuple' object has no attribute 'filename' Anyone with the quick solution? -
A bug or not a bug (get_paginate_by)
This is a code from Django itself. Please, pay attention that queryset is not used in the method. Well, I can't even imagine how it can be used here. Could you tell me whether this is a bug or not? If it is, I could raise a ticket at Djangoproject. If this is not a bug, we should clarify the purpose of this parameter in the comment. In this case I also could raise a ticket. Or everything is ok here? django/views/generic/list.py class MultipleObjectMixin(ContextMixin): def get_paginate_by(self, queryset): """ Get the number of items to paginate by, or ``None`` for no pagination. """ return self.paginate_by -
Django-admin forgot password not working
In Login.html I found that forgot password links but it does not appear on the screen so I delete the {% if password_reset_url %} section and it become like that but another error I have. As you can see the forgot password link not going to password_change form. So how can I configure that {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} -
Is there a simple method to make it as `""` instead of `None` in the template input?
In the template use the {{ data.user_data.id_card }} to show the value, but I get the None in it: Is there a simple method to make it as "" instead of None in the input? Because I think use the {% if %} is too trouble, and not concise in my code. If there is a template-filter method I can use? -
Check in a view whether it is tests running or not
Django 1.11.5 In production I am going to paginate lists by 10. But for testing purposes I want all the results be shown in the same page. Then with Selenium I select everything by class name, create a set of IDs and compare it with an expected set of IDs. Let's suppose my fixtures contain 28 objects. So, for me paginate by 30 will be Ok for testing purposes. So, I need a tool to check whether it is a test that is running right now or not. Well, at first I tried debug as an indicator: views.py if settings.DEBUG: PAGINATE_BY = 30 else: PAGINATE_BY = 10 tests.py class ComplexSearchForPlaces(StaticLiveServerTestCase): pass This is not a very good idea as in the debug mode and in production we should get more or less the same result. But I would be satisfied. But LiveServerTestCase seems to be setting DEBUG=False. I put a breakpoint - well, it is FALSE. Then I tried to catch the port. But ports seems to be changing. Proof: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#liveservertestcase The live server listens on localhost and binds to port 0 which uses a free port assigned by the operating system. Could you tell me how to check in … -
Downloaded boostrap.min.js does not work in Django template
Downloaded boostrap.min.js did not work in Django template but CDN boostrap.min.js did. Here my base.html code which did not work: Local boostrap.min.js not work i can even open the link of javascript in developer mode of Chrome When i change the code as below, it worked as normal : CDN boostrap.min.js work ps:This is just an example, in an other app, my downloaded boostrap CSS and static files like image and fonts worked but boostrap did not -
Django - Cycle Tag. How can I make it work?
I am a total newbie to Django. I am trying to implement cycle tag. To no avail. My view.py: def music(request): my_list = ['Ravel', 'Bach', 'Verdi', 'Janacek'] context ={'my_list': my_list} return render(request, 'music.html', context) My template file: <head> <style> .row1 { background: #FFFF00; } .row2 { background: #FF0000; } </style> <h1>Music</h1> </head> <body> {% for o in my_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr>{% endfor %} </body> What am I doing wrong? -
Django test: Setting cookie (Django 1.11+)
I have troubles setting cookie in Django test. class Test_views(TestCase): @classmethod def setUpClass(cls): pwd = '12345' cls.c = Client() cls.user_1 = UserFactory(password=pwd) cls.c.login(username=cls.user_1.username, password=pwd) super(Test_views, cls).setUpClass() @classmethod def tearDownClass(cls): super(Test_views, cls).tearDownClass() def test_set_cookie(self): session = self.c.session session['mycookie'] = 'testcookie' session.save() response = self.c.get(reverse('homepage')) ... I print the cookies in the Views to be sure: views.py ... def homepage(request): print(request.session.keys()) ... And indeed, the cookie mycookie doesn't exist. Apparently, that's the right way to set cookie: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.Client.session -
Django Check if Username already exists
Here's my forms.py, class RegistrationForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'first_name', 'password1', 'password2'] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] if commit: user.save() return user In views.py, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() .... How can I check if 'username' already exists. If it exists I wanna raise form validation error. How can I do that? Thank You :) -
Django - Modify Inlineformset Delete button
I do a custom UI/UX for an inlineformset. By default the inlineformset widget has a delete button. I wan to add and remove forms from inlineformset dynamic using javascript. In some cases the delete is just a button instead of the checkbox, in other cases is in a modal window. When a user click delete the form is removed from the page with javascript. So, I try to do this without using the default widget, render fields in the template, but I don't know how to tell Django witch fields to remove and if is necessary to readjust the ids and names of the fields. -
Referer checking failed (uri does not match referrer uri) error in Django app
I'm testing a basic Django app (fresh install) with gunicorn and nginx reverse proxy. I keep running into 403 errors of the following sort upon each and every POST request: Referer checking failed - http://ec2-xx-xxx-xx-xx.ap-south-1.compute.amazonaws.com/signup/ does not match https://ec2-xx-xxx-xx-xx.ap-south-1.compute.amazonaws.com/. This even comes if I'm trying to enter superuser credentials in the admin panel. There's no SSL installed on the server, hence I wanted to check the website in a purely http environment. However, it seems I keep getting forced to https. There's no overt flag I've set in settings.py to do this, nor does the error go away in incognito browsing (in case someone thinks it's HSTS persisting). What could be going on? Ask for more information in case you need it. -
CSRF_FAILURE_VIEW (from settings.py) being called on each post request. Need debugging assistance
I'm testing a Django app. I just did a fresh install on test AWS micro EC2 instance. Next, I installed Postgresql (and a connection pooler), then gunicorn with nginx reverse proxy, then ran syncdb and fired up the app to create a few users. I've used this app's virtual env on and off for over a year now. It's never failed me. However, currently the moment I enter anything and send a POST request, I am shown the default view I've set as CSRF_FAILURE_VIEW in settings.py. It even happens if I try to enter the admin panel. I'm using the same browser I've always used (Firefox), and tested it on a couple of other machines and browsers as well. django.middleware.csrf.CsrfViewMiddleware is part of my middlewares. django.core.context_processors.csrf is part of my template context processors. What could be going on? Can someone help me debug this? -
Field name `user_username` is not valid for model `Profile`
Error Name: Field name user_username is not valid for model Profile I'm building my Edit Profile View. Here is my views.py class ProfileEditAPIView(DestroyModelMixin, UpdateModelMixin, generics.RetrieveAPIView): serializer_class = ProfileEditSerializer def get_queryset(self): logged_in_user = User.objects.filter(username=self.request.user.username) return logged_in_user def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(queryset) return obj.profile def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) I can get user_id correctly but somehow I can't access to its username field This is serializers.py class ProfileEditSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( 'user_username', <<< 'title', 'gender', 'birth', 'height', 'height_in_ft', 'profile_img', ) Why can't we access to user's username? And how can we solve this? Thanks -
Images are not in ImageAndUser model
Images are not in ImageAndUser model.I wrote in views.py like @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = ImageAndUser() data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) index.html is <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <h2>SEND PHOTO</h2> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> SELECT FILE <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.However,now ImageAndUser model does not have the data.I really cannot understand why.But terminal says <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required</li></ul></li></ul> so I think i cannot get user data.However,I think user can access upload_save method after he log in the site, so I think the system has user data.I do not know why image&user data is not connected. models.py is class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images/', null=True, blank=True,) How can I fix this?What should I write it?