Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"No active account found with the given credentials" in django-rest-framework-simple-jwt
I can't optain jwt with django-rest-framework-jwt. After I post-requested with jwt-optaining-url, it said "No active account found with the given credentials" even though the given information(email, password) is correct. I think I've created a user with serializer in a wrong way. but can't come up with any new way. login view @csrf_exempt def facebook_login(request): body = dict(request.GET) code = body['code'][0] params_access = { "client_id": FACEBOOK_APP_ID, "redirect_uri": FACEBOOK_REDIRECT_URI, "client_secret": FACEBOOK_SECRET, "code": code } tokens = requests.get("https://graph.facebook.com/v5.0/oauth/access_token", params=params_access).json() access_token = tokens['access_token'] params_debug = { "input_token": access_token, "access_token": f'{FACEBOOK_APP_ID}|{FACEBOOK_SECRET}' } debug = requests.get("https://graph.facebook.com/debug_token", params=params_debug).json() params_user = { "fields": ["email"], "access_token": access_token } user_fb_data = requests.get("https://graph.facebook.com/me", params=params_user).json() user_email = user_fb_data['email'] user = User.objects.filter(email=user_email) if not user: user_data = { 'email': user_email, 'username': user_email, } user = UserSerializer(data=user_data, partial=True) if user.is_valid(): user.save() print("saved!!!!!!!!!!!!!!!") else: print("error", user.errors) jwt_data = { 'email': user_email, 'password': access_token } jwt = requests.post(JWT_OPTAIN_URL, data=jwt_data).json() access_token = jwt['access'] refresh_token = jwt['refresh'] data = { 'access_token': access_token, 'refresh_token': refresh_token } return Response(data, status=status.HTTP_201_CREATED) Serializer class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = super().create(validated_data) user.set_password(self) user.save() return user class Meta: model = User fields = ('email', 'username', 'refreshToken', 'password') extra_kwargs = {'password': {'write_only': True}} I expect the jwt is created with email and password information. -
How to make an English Test Web Application
I've been assigned to make a website in Python using Django. I think that an English Multiple-choice Test Website must be great but I don't know how to save the questions and answers in database and connect them with Python Django. Actually, I really want to use Microsoft SQL Server. Could you help me with that? -
Django: How to grant user account from user table in excel
I have an excel spreadsheet of student information, I want to create accounts with my username and password, what should I do? -
Django admin table functionality
Django has a nice sortable table system in the admin. I would like to know how can I use that in my regular templates. I couldn´t find any info about this. Any clues welcome. Thanks in advance. -
(Django) How can I embed the login form inside the landing page (main page) of the website?
I want to have the user login directly on the landing page that the website starts on. This page has username and password input boxes as well as a "login" button, but I can't seem to connect it such that it performs the task of logging in. Right now it just redirects to the same page with the message "This page isn't working. HTTP Error 405." I have already managed to make a separate page for logging in (it works), but I want to remove it and just have the user login from the main page. The part of my landing page index.html that will contain the form: <form class="login-container" method="POST"> <div class="input"> <input class="username_field" type="username" placeholder="E-Mail or Username" value="{{ form.username }}"> </div> <div class="input"> <input class="password_field" type="password" placeholder="Password" value="{{ form.password }}"> </div> {% for field, error in form.errors.items %} {% if field != '__all__' %}{{ field }}{% endif %} <span style="color:red">{{ error | striptags }}</span> {% endfor %} <button type="submit"></button> </form> My existing login.html that works: {% load static %} <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'login.css' %}"> </head> <body> <h1 style="text-align:center;">Log In to Planda</h1> <div class="container"> <img src="{% static 'planner/images/planda.png' %}" class="center"> … -
Django Saleor: How build contact form?
I develop an ecommerce site with the Django Saleor framework: https://getsaleor.com/ It's really well designed, thanks to the developers and the community! But I have a small problem: I would like to create a contact form but I have not seen anything about it either in the documentation or elsewhere... Does anyone know what is the best way to do it? When I add HTML directly after creating a page from the dashboard, it is not interpreted. I have the basics with Django development but I don't know how to integrate my form into the page created from the dashboard. Thank you in advance and at your disposal for any further information. Regards, Ouaip :) -
Why is Django looking for templates in the wrong directory
Why is Django looking for Template in the wrong directory? django is looking here: sempire\double_ch_control_app\templates\double_channel_control.html instead of conventionally here: sempire\double_ch_control_app\templates\double_ch_control_app\double_channel_control.html I have more than one app on the django project but this very app keep looking up templates on the wrong directory -
how can I implement this idea?
I have a Post model and a Tag model each related with a many to many field, the tag is describing the post somehow, like #frontend_development or #coding ,meaning a way to classify the posts and to reach the posts related to certain topics. the thing is when creating the post , the creator does not type the tags in tag section like here on Stackoverflow , instead , they choose from a pre existing list of tags fetched from the database and they can choose more than one tag . but I wanted more functionality .. to classify those tags to make it easier for the creators to choose from .. say hundreds of tags , by grouping every similar tag from the same type together by a subject, like both #coding and #frontend_dev both belong to the Tech subject/ #entrepreneurship and #Human_Resources both belong to the Business subject , so I have made a third model called SubjectTag related to the Tag model with a many to many field also. is that a good implementation ? the problem is , I want the post creator to be able to choose from the list of subject tags and automatically … -
django not giving me the file even though it the link is directed to the file
I am trying to download a file when a link is clicked. The link is generated dynamically using javascript when the file has been created. In my template the function that adds the links looks like: function Download(desiredLink) { var a = $('<a />'); a.attr('download',desiredLink); desiredLink = {{MEDIA_URL}} +desiredLink+'.docx'; a.attr('href',desiredLink); a.text("Download"); $('body').append(a); }; I have specified the MEDIA_URL in my settings.py file like: MEDIA_ROOT = os.path.join(BASE_DIR, 'documents/') MEDIA_URL = '/documents/' The link generated has the correct url when I inspect it. But when I click the button it tries to download the file but says Failed-No file. Any solution would be appreciated. Thanks in advance -
Making Pagination work with django-filter library and CBV
I know a related question has been asked before here: how can I use pagination with django_filter but I really tried to make it work with mine but because am use a custom LinkWidget or class i find it hard to included the pagination in to my ResultsFilter class or even get it to work with views and template. Here is my code so far: filter.py #filter.py # I didn't do much just changed so filters would be displayed as text/url just like django admin works instead of FORMS # and i also add style to the returned <li> class MyLinkWidget(widgets.LinkWidget): """docstring for ClassName""" def __init__(self, **karg): # super().__init__() super(widgets.LinkWidget, self).__init__(**karg) def option_string(self): return '<li class="list-group-item list-group-item-dark"><a%(attrs)s href="?%(query_string)s">%(label)s</a></li>' class ResultsFilter(FilterSet): important = AllValuesFilter(widget=MyLinkWidget(attrs={"class":"list-group"})) viewed = AllValuesFilter(widget=MyLinkWidget(attrs={"class":"list-group"})) class Meta: model = Results fields = ['viewed', 'important',] views.py class ResultView(ListView): paginate_by = 3 model = Results template_name = 'results_filter.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ResultsFilter(self.request.GET, queryset=self.get_queryset()) return context and finally template file is: results_filter.html <div class="filter_header"> <span class="l">Filter by Viewed</span> {{filter.form.viewed}} </div> <div class="filter_header"> <span class="l>Filter by Viewed</span> {{filter.form.important}} </div> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ … -
get a dictionary type variable from frontend
i am creating a attendance system website, so the attendance page opens up with table having columns roll no, date, attendance. the rollno. column loads the rollno. from the variable passed from backend. i want to create a dictionary in frontend having rollno.,date,attendace(AS true or false) and this dictionary variable holds value of upto 50 students and then pass the data to backend. i am successful in getting the list of rollno. in frontend but didnt get how to pass the attendance data of 50 students to backend the page shows a table with roll no. date attendance(t/f) and get this data in backend. -
how to create the correct context in Django
from django.shortcuts import render def index(request): context = { 'title' = 'test' } return render(request,'index.html',context) 'title' = 'test' ^ SyntaxError: invalid syntax -
Couldn't locate 'figures.py' in the app directory (Django-matplotlib integration)
I did everything exactly as mentioned in this link: https://django-matplotlib.readthedocs.io/en/latest/ When I go to the admin page and click on Add My Model. I get the error ImportError at /admin/my_app/mymodel/add/ Couldn't locate 'figures.py' in the app directory. figures.py is in the same directory as models.py as suggested in the documentation. If anyone has tried to include matplotlib in django in this manner, I would like to know what I did wrong. Beginner here. Please be patient. -
Form do not work after submitting once python Django
Posting views, urls and html to be clear. I am printing search results in a html tables on submit. Form and result display on the same page. My form works as expected only once, if I try to use the form second time after printing the search result for the first search criteria it throws me error saying: AttributeError 'NoneType' object has no attribute 'replace'. And the url is pointing to the definition which is returning me the response(stream_response) like : localhost/stream_response .To put the form to work I need to manually refresh the page then the form works as expected (back to localhost/checkProject.html). Also, there are three dropdown items which I am printing from database upon initial page load. After, one search the drop down values are disappeared too. You can see the dropdowns on the below html. views.py def stream_response(request): data_list = []; flag = 0; if request.method == 'POST': request.GET.get('Check') flag = 0; field = request.POST.get('inputValue') projectName = request.POST['projectName'].strip() communityPartner = request.POST.get('communityPartner').replace('-','') campusPartner = request.POST['campusPartner'].replace('-','') academicYear = request.POST['academicYear'].replace('---','') print(sqlfiles.checkProjectsql(projectName,communityPartner,campusPartner,academicYear)) cursor = connection.cursor() cursor.execute(sqlfiles.checkProjectsql(projectName,communityPartner,campusPartner,academicYear),params=None) rows = cursor.fetchall() if(rows != []): print("why am i here") for obj in rows: if (projectName.strip().lower() in obj[0].split("(")[0].strip().lower()): flag =2 if(projectName.strip().lower() == obj[0].split("(")[0].strip().lower()): flag=1 … -
NameError: name 'crewForm' is not defined for form_class
So I'm getting a NameError: name 'crewForm' is not defined for form_class even though I have created a form in the forms.py file with the same name. I have almost done the same thing in a different app in the same project and it worked but for some reason this isn't working views.py: from django.shortcuts import render from staff.models import Crew from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy # Create your views here. class CrewListPageView(ListView): model = Crew context_object_name = 'crews' template_name = 'staff/staff_home.html' class CrewAddPageView(CreateView): template_name = "status/crew_add.html.html" model = Crew form_class = crewForm success_url = reverse_lazy('crew_list') forms.py: from django import forms from staff.models import Crew class crewForm(forms.ModelForm): class Meta: model = Crew fields = ('crewid', 'name', 'crew_dob', 'company', 'role') labels = { 'crewid': ('Crew ID'), 'name': ('Name'), 'crew_dob': ('Date Of Birth'), 'company': ('Company'), 'role': ('Role'), } views.py: from django.urls import path,include from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('',views.CrewListPageView.as_view(), name ='crew_list'), path('add/',views.CrewAddPageView.as_view(), name = 'crew_add'), ] -
Server Error (500) when I trun debug = False in django settings.py
I had turned the debug=False and allow_hosts but still Server Error (500) why? while when I turn it to True it works perfectly SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost','127.0.0.1','*'] it has to show the home page on website -
How do i host django website using a2hosting and filezilla?
I am trying to host a django website using a2hosting server.Files can be uploaded via filezilla client.I successfully uploaded my file on filezilla.But the problem is,i can't access my website using my domain.it always shows ubuntus default page.How can i access my website.What changes are made for accessing my website? -
In Python dev_appserver.py Development server not start
I am using Windows 10 and I am completed all the process given by sympy-gamma document https://github.com/sympy/sympy_gamma/ . but at the end when i am configuration file for App Engine (needed to run the development web server): $ python deploy.py --generate-only --generate-test 1000 and run development web server and run this code will give me error: $ dev_appserver.py . server is started but port 8080 Display:- This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500 and at terminal part it display Error like:- -
How to attach S3 file to email in Django
I'm trying to attach a media file saved in an S3 bucket to an email, which I'm doing with this line of code: email.attach_file(standard.download.url) The model is defined as follows: class Standard(models.Model): name = models.CharField(max_length = 51) download = models.FileField(upload_to="standard_downloads/", null=True, blank=True) def __str__(self): return self.name Within settings.py I have defined my media files as follows: AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } DEFAULT_FILE_STORAGE = 'sme.storage_backends.MediaStorage' MEDIA_ROOT = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME When trying to run the code I'm getting No such file or directory: 'https:/bucket-name.s3.amazonaws.com/media/standard_downloads/filename.ext Please note it is showing as https:/ (a single /). How do I correct this? -
Request continue even after redirect through Django Middleware
I have created custom Middleware in users/middleware.py file. Till yesterday, the request was terminating after middleware return HttpResponseRedirect. but today the request keeps continuing and reloads the profile page. below is my middleware.py file. I am using Django 2.1.7 from django.utils.deprecation import MiddlewareMixin import pytz from django.urls import reverse_lazy , reverse from django.utils import timezone from django.http import HttpResponse ,HttpResponseRedirect class TimezoneMiddleware(MiddlewareMixin): def process_request(self, request): request.session['timezone'] = 'Asia/Kolkata' timezone.activate(pytz.timezone('Asia/Kolkata')) class CheckProfileMiddleware(MiddlewareMixin): def process_request(self,request): if request.user.first_name == "" or request.user.last_name == "": if 'profile' not in request.path_info: request.session['is_incomplete']=1 # return HttpResponse("ok") return HttpResponseRedirect(reverse('profile')) else: request.session['is_incomplete']=0 return None basically I want to redirect the user to the profile page if his profile is incomplete. below are my middleware in setings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'users.middleware.TimezoneMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middleware.CheckProfileMiddleware', ] When I use return HttpResponse it stops execution but it continue execution on HttpResponseRedirect -
Override detail url to appear as list
Since I am using request.user to determine the user from the JWT that was used to authenticate the request, I think it is a little misleading to keep the normal approach of /users/pk/ since changing the pk url parameter will have no impact on the user being interacted with. For example, I'd like to make a PATCH request to /users/ & retrieve the user's id from request.user rather than making the request to /users/1/, getting the user id from the url param. users/viewsets.py class UserViewSet(viewsets.ViewSet): def list(self, request): queryset = get_user_model().objects.get(id=request.user.id) serializer = UserSerializer(queryset) return Response(serializer.data) def create(self, request): post_data = request.data serializer = UserSerializer(data=post_data) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response(serializer.data, status=201) print(request.data) return Response({"error": "Data is invalid."}, status=400) def update(self, request, pk=None): post_data = request.data obj_instance = get_user_model().objects.get(id=request.user.id) serializer = UserSerializer(instance=obj_instance, data=post_data, partial=True) if serializer.is_valid(): serializer.save(owner=request.user) return Response(serializer.data, status=204) print(request.data) return Response({"error": "Data is invalid."}, status=400) def partial_update(self, request): post_data = request.data obj_instance = get_user_model().objects.get(id=request.user.id) serializer = UserSerializer(instance=obj_instance, data=post_data, partial=True) if serializer.is_valid(): serializer.save(owner=request.user) return Response(serializer.data, status=204) print(request.data) return Response({"error": "Data is invalid."}, status=400) def retrieve(self, request): queryset = get_user_model().objects.filter(id=request.user.id) user = get_object_or_404(queryset, pk=request.user.id) serializer = UserSerializer(user) return Response(serializer.data) def get_permissions(self): if self.request.method == "POST": self.permission_classes = (AllowAny,) return super(UserViewSet, self).get_permissions() … -
best python projects (for students)
list of project ideas for python -
How can I download a word document created by a django app on the same app
I have a django app the creates a word document from a template. After user input I make an ajax request to my views.py and create the document. After the document is created I want it to be downloaded from the server. The document is saved in the static/documents folder. In my template I have the following: $.ajax({ url: '/ajax/result/', data : { 'values': JSON.stringify(dataJson), 'general': JSON.stringify(generalData) }, method: 'GET', contentType: "application/json", dataType: 'json', success: function (data){ Download('documents/'+document.getElementById('id_file_name').value+'.docx'); alert(data); }, error: function(data) { alert("something went wrong"); } }); function Download(url) { document.getElementById('my_iframe').src = url; }; The Download function is the function that downloads the document. I can get the file name of the document since it is from user input. I am currently getting a 404 error on my console. Thanks in advance -
Show copyright notice footer in Django Grappelli
In Django Grappelli, the action/submit row is always displayed at the bottom of the change list/ change form. I would like to display a site copyright notice either in its place or below it. I tried setting Django ModelAdmin setting save_on_top to True, but it does not work with Grappelli. Any suggestions how best to do it? -
Error while installing django in ubuntu 18.04
The image is a screeenshot of the errors occuringI'm trying to install Django in ubuntu 18.04 in a virtual environment using command 'pip install Django' but it gives many errors as shown in the picture. One of the errors is : "Exception: Traceback (most recent call last): File "/home/sagar/Documents/glug_aud/env/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl/urllib3/response.py", line 302, in _error_catcher yield