Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I use clean() to fetch Product of provided Product id in Django Form?
Is it semantically correct in Django to fetch a Product object of provided Product id in the clean() function? forms.py def clean_product(self): product_id = self.cleaned_data['product'] try: product = Product.objects.get(id=int(product_id)) except ValueError: print('error') raise ValidationError('Invalid value') return product views.py def submit_new(request): status = 'fail' if request.method == 'POST': form = NewBForm(request.POST) if form.is_valid(): ... b = form.save(commit=False) b.product = form.cleaned_data['product'] boost.save() status = 'success' return JsonResponse({'status': status}) -
If value is not given in form its not storing null value defaultly?
I created a form in django.I need to set imagefield as optional so i gave required=False.And in my model i gave default = None.My problem is if the user doesn't set profile picture the default value None is not storing in database? forms.py class Register(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Username = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) Firstname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=30) Lastname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=40) Confirm_Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) picture = forms.ImageField(required = False) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='media',default=None) views.py def register(request): if request.method == "POST": form = Register(request.POST,request.FILES) pro=Profile() if form.is_valid(): email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.create_user(username=User_name, password=Password,email=email, first_name=firstname,last_name=lastname) if form.cleaned_data['picture']: pro.image = request.FILES['picture'] pro.user = user pro.save() redirect('/') -
Google multiple accounts: Oauth2: 'NoneType' object has no attribute 'provider'
I've already read this and this, but my problem is different: I have 2 accounts on gmail, and it works when I try with the second one, which is not admin and which has no account information. For the first one, even if I remove the authorization access and google asks me again which account and if I agree with giving my email, I still get the 'NoneType' object has no attribute 'provider'. As a note, I've managed to make it work with facebook and twitter, that's why I'm stuck here, you can try it here, your gmail, facebook or twitter will work, I don't know what could the problem come from: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'bla' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'bla' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Switch object create from static data to dynamic data django rest framework viewsets
I have a django rest framework viewset. Within the viewset, I want to create a view that creates a new object based on the data entered in the django rest framework backend page. I currently have it right now that I hard coded just to test and see if i can add. I not want to switch it to dynamic data that is passed into the view. I cant seem to figure it out. I tried just getting rid of the data and **data in the request but that broke it and i couldnt get it to work. viewset create view: @permission_classes((IsAuthenticated)) def create_user(self, request): data = { 'version':1, 'path':'testingpath5', 'namespace':'testingnamespace1', 'value':'testin value 3', 'user_id':1, 'person':request.user } queryset = Preference.objects.create(**data) serializer = PreferenceSerializer(queryset) return Response(serializer.data) I want to be able to create a new object based on the data that is passed in from the django rest framework backend page. -
Nginx, SPA & Sphinx Doco Authentication
I have an SPA app which uses Azure AD for authentication. It's working well and now I've added some user doco using Sphinx. I've configured Nginx so the doco is available via /app/doco. This works well, however now I would like to also secure it so only Azure AD authenticated users can access the doco. To do this I have made use of the auth_request (http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) module. This works if I am using standard Django authentication but when I use Azure AD authentication it isn't working as the request does not have the users token included etc. The way I understand the auth_request module to work is: User attempts to access /app/doco (which includes the users token) Nginx is configured to check if the user is authenticated by going to /app/auth_check (custom Django view) which returns either 200 or 404 If 200, user is given access to /app/doco It feels like that above approach is flawed, trying to hit a square peg through a round hole? Will something like the above work or is there another tool/approach that better fits? -
Django puts spaces in first Line of TextField
I'm creating a webapp where I can present a documentation. In my documentations I often have some code snippets so I used prism (https://prismjs.com/) to format the text I enter in a textfield on the admin page. The Problem is that whenever I enter code in the textfield it makes spaces on the first line like that: import { Pipe, PipeTransform } from '@angular/core'; import { UserService } from '../user.service'; My code looks likt this: Template: <pre><code class="language-{{ subdoc.language }}"> {{ subdoc.code }} </code></pre> -
How to combine more than one querysets in django
Here i am trying to combine query-sets from different models and i tried like this.But this code is giving me error: How can i solve this ?? Exception Type:TypeError Exception Value: unhashable type: 'list' def search_all(request): q = request.GET.get('q') if q: courses = Course.objects.filter(title__icontains=q) students = Student.objects.filter(name__icontains=q) teachers = Teacher.objects.filter(name__icontains=q) users = User.objects.filter(username__icontains=q) all_results = list(chain(courses,students,teachers,users)) # all_results = courses | students | teachers | users return render(request,'all_search_results.html',{all_results:all_results,'q':q}) else: return redirect('home') -
How to get QuerySet values separately?
How I can to get values from QuerySet separately? The result of my QuerySet now is „, ]>“ How I can get 5, 90 to separate variable ? -
SwingTime in Djnago
I have a table in my ORM from which I want to calculate the total weight and display it on a calendar and for the same I want to use SwingTime but I was not able to use it. Models.py class Quiz(models.Model): total_trucks = models.IntegerField(default=0) offered_price = models.IntegerField(default=0) weight = models.IntegerField(default=0) posted_on = models.DateTimeField(auto_now_add=True) Now I can get the total weight like this: total_weight = Quiz.objects.aggregate(Sum('weight')) But how Do I use it with SwingTime? I find another useful Link but was not able to understand it completely to use but it also solves the problem. Any help is appreciated. -
How to store a dataframe object between API calls?
My Django app will allow the users to upload an Excel file and will then analyze and visualize data in this file. To handle the Excel files, I have introduced a model with FileField: class DataFile(models.Model) file = models.FileField(upload_to='data_files') Next, I want to create some API views for this app that would take the file uploaded by user, manipulate it with Pandas dataframe object and return the manipulated data. For example: def some_api_view(request): data_file = DataFile.objects.last() dataframe = pandas.read_excel(data_file.file.path) maniupulated_dataframe = # ... dataframe manipulation goes on here ... # return JsonResponse({'manipulated_dataframe': manipulated_dataframe'}) My concern is that each API view like this will need to read the Excel file on its own. Is it possible to design the API in a way that would allow reading the file into a dataframe only once (since it will always be the same file), and then the API views would only be responsible for retrieving this dataframe, manipulating it and returning manipulated data? I am using an SQL database, so I cannot store the dataframe object itself in the database. Also, I would rather avoid pickling it. -
How to authenticate user from standalone react frontend with django backend (same domain, different ports), using a third-party CAS authentication?
I'm setting up a django backend with Django REST framework for providing APIs, with authentication implemented through a third-party CAS server. Currently my backend authentication has been successfully implemented (using django-cas-ng package), which means I can implement different permissions for different groups of user. The django backend serves through localhost:8000 by default. Adding a standalone react frontend (localhost:3000 by default) seems complicating the authentication system. Requests (implemented by axios) sending from 3000 port to 8000 port are unable to authenticate. I've tried npm run build to build the static files and integrate them with django. Within the same 8000 port all the authentication and permissions work fine. Could anyone suggest how to implement authentication through different ports? -
How to display the values from a many to many filed after using .vlaues() in queryset?
I wrote a views function for my django applications which is: def index(request): influencers = Influencer.objects.all().order_by('followers').values() print(influencers) paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id).values() queryset = list(chain(paged_listings,user_list)) content = {'total_page_count': paginator.num_pages, 'influencer_count':paginator.count, 'data': queryset} return JsonResponse(content) It returns a JSON object. The problem is when I use .values() on the first line of the function it doesn't display the values from Many to Many field in the Respose. I tried writing an alternative function, which displays the values from the many to many field but shows error when the pagination influrnation is passed i.e. total_page_count and influencer_count. The alternative function is given below: def index(request): influencers = Influencer.objects.all().order_by('followers') paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id) paginate = {"total_pages":paginator.num_pages} queryset = list(chain(paged_listings,user_list)) ser_query = serializers.serialize('json', queryset,indent=3,use_natural_foreign_keys=True) return HttpResponse(ser_query,content_type='application/json') When I include paginate in queryset it gives the error 'str' object has no attribute '_meta' The model class for the views function is: class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=255) username = models.CharField('Username',max_length=255,unique=True) photo = models.URLField(blank=True,max_length = 500) categories = models.ManyToManyField(Category,blank=True,max_length=400) hashtags = models.TextField('Hashtags',blank=True) I want both the pagination and ManyToMany Field information in my JSON response. How should … -
save username and password in django login form
I am using the django User model to create a login form for my custom admin page. I want the username and password to be saved when I logout. I know saving username and password in login form is not a good idea but I am doing it as a test project so I don't want to keep entering the username and password everytime I log in. forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) remember_me = forms.BooleanField(required=False) views.py def login(request): if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user : login(request, user) if not remember_me: request.session.set_expiry(0) redirect_url = request.GET.get('next', 'dashboard') messages.success(request, 'logged in.') return redirect(redirect_url) else: messages.error(request, 'Invalid username or password') else: form = LoginForm() return render(request, 'login.html', {'form': form}) template <form action="" method="post"> {% csrf_token %} <input type="text" name='username'> <input type="password" name='password' required> <button type="submit">Log in</button> <input type="checkbox" name="remember_me" id="basic_checkbox_1" > <label for="basic_checkbox_1">Remember me</label> </div> </form> -
DRF - SerializerMethodField
I've an API view as below:- class ProfileAPI(generics.RetrieveAPIView): serializer_class = ProfileSerializer def get_object(self): try: return Profile.objects.get(user=self.request.user) except: return None # I don't raise NotFound here for a reason. # I don't want a 404 response here, but a custom HTML response, explained below. class ShopAndProfileDetailsSerializer(ProfileSerializer): html = serializers.SerializerMethodField() def get_html(self, obj): # some custom HTML response based on whether the user obj is `None` or not. if not obj: return NOT_LOGGED_IN_HTML return CUSTOM_HTML class Meta(object): model = Profile fields = ('html',) Now when the user is logged-in, I get the html key in the response. However, when the user is None (logged-out), I get an empty response. Why? and how can I rectify it? -
Does AmazonSES provide any api to know if the email was successfully sent?
So I am sending a few emails to clients using Amazon-ses. Does Amazon provide any api that tells me if the email was delivered successfully? Some of the mails I send have critical status. I am using django1.9 and python3. -
Django Display Data in view from existing database table without creating model
Fetch Data from already created database table and display in view without creating model I have tried python manage.py inspectdb Display data from already created database table without using model -
cant fix error: create() takes 1 positional argument but 2 were given and cant seem to fix it
I have a django rest framework view set. I want to create an object based on data that is passed in with the post request. I have it setup right now to create new object with dummy data before it starts to take information from the request. I am getting the following error: create() takes 1 positional argument but two were given. Here is my viewset method: @permission_classes((IsAuthenticated)) def create_user(self, request): data = { 'version':1, 'path':'testingpath1', 'namespace':'testingnamespace1', 'value':'testin value', 'user_id':1, 'person':request.user } return Preference.objects.create(data) -
ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-YYFUnW/psycopg2/
I'm trying to install requirements.txt file in python 2.7 in ubuntu but i get ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-YYFUnW/psycopg2/ What exactly does that mean, and how do I fix it? I already tried these commands: apt-get install python-bs4 sudo install --upgrade setuptools sudo apt-get update Error image -
Apache Server returning html file in var/www/html but not returning my website
I have a linux server (ubuntu) and am trying to set up apache, but the server is not running my actual django server, but instead running a html file in var/www/html. Running sudo systemctl reload apache2 works fine, so I think the problem involves the .conf file in /etc/apache2/sites-available/ called infosum.conf somehow. This is for a new linux server (ubuntu). The project is running django 2.2 and apache 2.4. When running python manage.py runserver 0.0.0.0:8000, the server works fine, but when on the apache server it just returns that html file. /etc/apache2/sites-available/infosum.conf (infosum is project name) Alias /static/ /home/username/infosum/staticfiles <Directory /home/username/infosum/staticfiles> Require all granted </Directory> Alias /media/ /home/username/infosum/media/ <Directory /home/username/infosum/media> Require all granted </Directory> <Directory /home/username/infosum/infosum> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/username/infosum/infosum/wsgi.py WSGIDaemonProcess django_app python-path=/home/username/infosum python-home=/home/username/infosum/venv WSGIProcessGroup django_app /home/username/infosum/infosum/wsgi.py import os import sys sys.path.append('/home/username/infosum/infosum') # add the virtualenv site-packages path to the sys.path sys.path.append('/home/username/infosum/venv/Lib/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'infosum.settings') application = get_wsgi_application() -
Django - User Search
I'm trying to filter ListView based on post method from search bar in my basetemplate. So making it works like: Insert name --> SearchBar-->GET Method-->SearchView class(in views.py)--> render html with usernames. I have done this, but it wont work. Could you please tell me what I'm doing wrong? views.py in my user app class SearchView(ListView): model = User template_name = 'blog/list_of_users.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') if query: postresult = User.objects.filter(username__contains=query) result = postresult else: result = None return result urls.py in my blog app path('users_search/?search=<str:username>', user_view.SearchView.as_view(), name='user_search'), search form in html <form class="example" method="GET"> <input type="search" placeholder="ユーザー検索..." name="user_name"> <button type="submit"> 検索 </button> rendered html with user names {% for result in all_search_results %} {{ result.username }} {% empty %} add something to show no results {% endfor %} -
Django Duration Field convert to MM:SS:CC format?
I have the following model called Competition. I am trying to store the records for each swimmer as freestyle_50 as mm:ss:cc where cc refers to centisecond i.e 1/100 of second. Is there anyway i can solve this problem using duration field? Also in Forms class Competition(models.Model): swimmer = models.ForeignKey( Swimmer, blank=True, on_delete=models.CASCADE, related_name='swimmer_competition' ) freestyle_50 = models.DurationField( blank=True, null=True, ) freestyle_100 = models.DurationField( blank=True, null=True, ) -
How to Create Django Project without default Django Database table
I'm trying to make Django project but when creating that Django Project There are serval table created in Database which I dont Want. I need Django Project Without any Default Database Table Database tables are: auth_group auth_group_permission auth_user django_migration django_admin_log django_content_type I tried Disabling django.contrib.admin In Installed Apps # 'django.contrib.admin', # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'data.apps.DataConfig', ]``` The Expected result should be Django shouldn't create Default table in database -
Overwrite fields in Django Serializer
I am new in Django and I would like to overwrite the field value in create and update method of serializer. Here is my model=> class Holiday(models.Model): HolidayDay = models.DateField() Created_DT = models.DateTimeField() Created_Usr = models.CharField(max_length=20) LastModified_Usr = models.CharField(max_length=20,blank=True) LastModified_DT = models.DateTimeField(blank=True,null=True) def __str__(self): return str(self.HolidayDay) Here is my serializer=> class HolidaySerializer(serializers.ModelSerializer): class Meta: model=Holiday fields = [ 'id', 'HolidayDay', 'Created_DT', 'Created_Usr', 'LastModified_Usr', 'LastModified_DT' ] def create(self,validated_data): validated_data['Created_Usr'] ="Testing" return Holiday.objects.create(**validated_data) I would like to update Create_usr field value in create method and LastModified_usr field in update method. But why I can't overwrite the create_usr field as "Testing"? Here is my views=> def post(self,request): holiday = request.data.get('holiday') serializer = HolidaySerializer(data=holiday) serializer.is_valid() print(serializer.errors) if serializer.is_valid(): holiday_saved=serializer.save() return Response({"success":"Holiday '{}' created successfully".format(holiday_saved.HolidayDay)}) def put(self,request,pk): save_holiday = get_object_or_404(Holiday.objects.all(),pk=pk) data = request.data.get('holiday') serializer = HolidaySerializer(instance=save_holiday,data=data,partial=True) if serializer.is_valid(raise_exception = True): holiday_saved=serializer.save() return Response({"sucess": "Holiday '{}' updated successfully".format(holiday_saved.HolidayDay)}) -
How to show more objects in my html with django (queries)
I want to show more queries within my html page but it only shows a single object. I do not know how to add more This is in mysql, html, django1.11 and python 2.7.15 views.py def administrador(request): alumno = Alumnos.objects.get(pk=1) context = { 'alumno': alumno } mapa = mapas.objects.get(pk=4) context2 = { 'mapa' : mapa} competencias = Competencias.objects.get(pk=1) context3 = { 'competencias' : competencias} return render(request, 'competencias_app/competencias.html',context) <form action="/competencia" method="POST"> {% csrf_token %} <div class="container-alumnos"> <div> <select id="carrera" name="Carrera"> <option value="1">TICS</option> <option value="2">Carrera</option> <option value="3">Carrera</option> <option value="4">Carrera</option> <option value="5">Carrera</option> </select> </div> <div> <select id="Alumno" name="Nombre"> <option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option> </select> </div> <form action=""> <label for="ID">ID</label> <input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br> <label for="apellidos">Apellidos</label> <input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br> <label for="Correo">Correo</label> <input type="input" name="Correo" disabled value="{{alumno.correo}}"><br> </form> </div> <select id="opciones" name="Semana"> <option value="1">Semana 1</option> <option value="2">Semana 2</option> <option value="3">Semana 3</option> <option value="4">Semana 4</option> <option value="5">Semana 5</option> </select> <div class="container-listas"> <select name="OS" size=9> <option selected value="0"> Elige una opción </option> <optgroup label="{{mapa.nombre}}"> <option value="1">{{competencias.nombre}}</option> <option value="2">Nombre Competencia</option> <option value="3">Nombre Competencia</option> </optgroup> <optgroup label="Mapa - Nombre"> <option value="10">Nombre Competencia</option> <option value="11">Nombre Competencia</option> <option value="12">Nombre Competencia</option> </optgroup> </select> i need add object mapa and competencias. The object alumno i dont have problem -
Django Elastic Search Help: Trouble with settings.py configuration
I new in django elastic search... When i am not getting what to put in host section: ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9200' }, } I didnt configure django default localhost, my django localhost server is defult http://127.0.0.1:8000/ , Whenever i put the host id in elastic_dsl, it fires me error that raise ConnectionError("N/A", str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError((<urllib3.connection.HTTPConnection object at 0x7f486a65c550>, 'Connection to 192.168.1.10 timed out. (connect timeout=10)')) caused by: ConnectTimeoutError((<urllib3.connection.HTTPConnection object at 0x7f486a65c550>, 'Connection to 192.168.1.10 timed out. (connect timeout=10)')) in my current situation, Can anyone help me to put what in ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } I am in trouble doing it.... Thank You so much