Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find existing JWT token for user
I've got a function to manually create a new AccessToken for a user (using the rest_framework_simplejwt library): from rest_framework_simplejwt.tokens import AccessToken def create_access_token_for_user(user): access_token = AccessToken.for_user(user) Now I'm trying to write a test to verify that this is actually working as expected, and I can't seem to find any way of getting the AccessToken for a given user. The test should look something like: def test_access_token_created(client): user = create_user() create_access_token_for_user(user) access_token = AccessToken.get_token_for_user(user) # This, but real assert access_token is not None # Or some check to see if it exists The rest_framework_simplejwt docs don't seem to have anything that does this, or at least nothing that I've been able to use correctly. -
How do I get the ID of an image
I'm a Django beginner, how do I get the ID of each image uploaded with form? class Image(models.Model): imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL) upload_image=models.ImageField() def upload(request): if request.method == 'POST': form=UploadForm(request.POST, request.FILES) if form.is_valid(): post=form.save(commit=False) post.imageuploader_profile=request.user post.save() return redirect.... else: form=UploadForm -
How to return httpresponse in dajngo?
My scenerio I declare two functions and pass HTTP response also but it's not working .can you please tell me how to fix this issue. def sample1(): return HttpResponse('hi', status=200) def sample2(): sample1() return HttpResponse('hello', status=200) sample2() I got the output hello but i need hi only .what are mistake has occurred. -
2006, MySQL server has gone away
I’m running a Django application with MySQL db. An error 2006, MySQL server has gone away occurs some time after start when application tries to get query set of objects from database I have tried: set large value of wait_timeout at /etc/my.cnf (larger than CONN_MAX_AGE in settings.py in Django project) and restart server set large value of max_allowed_packet in /etc/my.cnf (up to 2G) make a thread that makes query to mySQL every minute call django.db.close_connection() before the access to db and nothing helps solving the problem -
Saving in django forms using FormView
I'm creating a form that will change the state of reserve book, I have this class LibraryReserveForm(CrispyFormMixin, forms.Form): def __init__(self, *args, **kwargs): self.manager = kwargs.pop('manager') super(LibraryReserveForm, self).__init__(*args, **kwargs) def save(self): self.instance.reserve_status = 'approved' self.instance.save() return self.manager models.py class ReservedBooks(TimeStampedModel): BOOK_RESERVE_STATUS = Choices( ('for_approval', "For Approval"), ('approve', "Approved"), ('cancelled', "Cancelled"), ('rejected', "Rejected") ) reserve_status = models.CharField( _('Status'), max_length=32, choices=BOOK_RESERVE_STATUS, default='for_approval' ) ... view class LibraryReserveView( ProfileTypeRequiredMixin, MultiplePermissionsRequiredMixin, FormView, ): model = ReservedBooks template_name = 'library/reserved_list.html' form_class = LibraryReserveForm def get_form_kwargs(self): kwargs = super(LibraryReserveView, self).get_form_kwargs() kwargs.update({ 'manager': self.request.user.manager, }) return kwargs urls url( r'^reserve/(?P<pk>\d+)/$', views.LibraryReserveView.as_view(), name='reserved' ), everytime I submit the button I print something in the save() method of the forms but its not printing something therefore that method is not called. How do you called the save method ? Thanks -
Django Queryset : Get the Max number of M2M items by M2M category
I've been stuck for hours on a queryset issue. Here are my models : class AssetCategory(models.Model): name = models.CharField('Category name', max_length=255) class Asset(models.Model): name = models.CharField('Asset name', max_length=255) category = models.ForeignKey(AssetCategory, on_delete=models.SET_NULL) class Product(models.Model): name = models.CharField('Product name', max_length=255) assets = models.ManyToManyField(Asset, related_name='products') I would like to be able to get the list of categories with the max number of assets a product has (whatever this product is) For example, if I have : Product 1: 2 assets in a category A 1 asset in a category B Product 2: 5 assets in a category A 0 assets in a category B I would like to be able to know that : the category A, in all my products, get a maximum of 5 assets the category B in all my products get a maximum of 1 asset I tried to play with aggregate or annotate, on different tables, but I don't succeed to get what I want.. The closest thing I tried was : asset_categories = AssetCategory.objects.annotate(max_in_product=Count('asset__products')) But of course it just gives me for each category, the sum of assets used in my products so in my example : Category A : 7 Category B : 1 -
'ModelFormOptions' object has no attribute 'concrete_fields' in django
I am updating a my model. but it's showing me this error: 'ModelFormOptions' object has no attribute 'concrete_fields'. kindly guide me what is mistake i'm doing. Your help will be appreciated. Thank You views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) data=Product.objects.get(id=product_id) form = EditProductForm(instance=data) args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) def post(self, request, product_id): data = Product.objects.get(id=product_id) form = EditProductForm(instance=data) form = EditProductForm(request.POST, request.FILES, instance=form) if form.is_valid(): productadded = form.save(commit=False) productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) TRACEBACK File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Adil Ijaz\Desktop\onlineProject\market\stock\views.py", line 109, in post form = EditProductForm(request.POST, request.FILES, instance=form) File "C:\Users\Adil Ijaz\Desktop\onlineProject\market\stock\forms.py", line 39, in __init__ super(EditProductForm, self).__init__(*args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py", line 293, in __init__ object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\Adil … -
How can i generate static api documentation for django rest APIs?
I went through the documentation and tried to use swagger and coreapi, but both are interactive, I want same api documation with out interation. Is is possible? -
Django select last rows of all types
In django I have a table that contains rows with a column "type" and a column "inserted_date". I would like to select the last inserted rows of all types. How can I do this in django? -
How to redirect the user to the desired link after registration?
How to redirect the user to the desired link after registration? What I do is not working. I want to redirect to "new_channel". Thanks in advance. views.py class RegisterFormView(FormView): form_class = UserCreationForm success_url = "main/my_newsagent/new_channel.html" template_name = "main/register.html" def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) urls.py urlpatterns = [ path('', views.index, name='index'), path('main/register/', views.RegisterFormView.as_view(), name='register'), path('main/login/', views.LoginFormView.as_view(), name='login'), path('main/logout/', views.LogoutView.as_view(), name='logout'), path('main/my_news_agent/', views.my_newsagent, name='my_newsagent'), path('main/my_news_agent/new_channel', views.new_channel, name='new_channel'), path('main/edit_profile', views.edit_profile, name='edit_profile'), path('main/my_newsagent_page', views.my_newsagent_page, name='my_newsagent_page'), path('main/my_newsagent/new_channel.html', views.new_channel, name='new_channel'), ] -
Passing forms values/strings into views.py and back to template
I know that there's a lot of topics with this matter, but I just can't get my code working. Can you please help me what is wrong with my Django website school project. So the problem gets easier to understand lets assume that I want to make a basic search bar to my site, where: user can submit a word the word goes into views.py file where from views.py file it will get back to template with render function My current code looks like this: HOME.HTML CODE <!-- Submit hashtag search --> <form action="/search/" method="get" > <input type="text" name = "q"> <input type="submit"value="Search"/> </form> <h1> hashtag </h1> VIEWS.PY CODE from django.shortcuts import render import tweepy, csv, sys, re from website import twitterAPI # This is supposed to make the homescreen blank before submitting any word to the search box def home(request): return render(request, 'website/home.html') def about(request): return render(request, 'website/about.html') # When submitting a word to the search box this function should # return the word back to home.html as a 'context' def search(request): hashtag = 'You submitted: %r' % request.GET['q'] context = {'hashtag': hashtag} return render(request, 'website/home.html', context) Currently, the website opens like it should (blank page with a search … -
python project is not running in visual studio
hi i made this simple project https://github.com/dharmendrak603/myfirstproject and it was running properly earlier and i moved out to some other project, but now when i want to run this project it gives me error below. actually i don not remember the virtual envirment name aslo but i remember that it should be one of denvx or 111 . i am new to django and python. please help. django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Generate access token using user instance (not username, password and grant_type)
I'm using Django REST Framework and using this library to provide token based authentication to the frontend applications. There is Login with Google implementation using django-allauth plugin. I want to generate access token when user login using social account. For handling social login and generating social account, I have created this view. class GoogleLoginView(LoginView): """ Enable login using google """ adapter_class = GoogleOAuth2Adapter serializer_class = CustomSocialLoginSerializer def login(self): self.user = self.serializer.validated_data['user'] self.token = TokenView().create_token_response(self.request) return self.token def post(self, request, *args, **kwargs): self.request = request self.serializer = self.get_serializer( data=self.request.data, context={'request': request} ) self.serializer.is_valid(raise_exception=True) url, header, body, status_ = self.login() return Response(json.loads(body), status=status_) The request data has user instance along with client_id and client_secret of the application. But this gives error '{"error": "unsupported_grant_type"}' Version django-oauth-toolkit==1.3.0 -
include credentials in ajax request (Django REST)
my server packages are: Django==3.0 django-cors-headers==3.2.1 djangorestframework==3.11.0 djangorestframework-simplejwt==4.4.0 and i configured CORS as mentioned here CORS config in settings.py is: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None my api login view: class BaseLogin(APIView): renderer_classes = [JSONRenderer] permission_classes = [IsAnonymous] def post(self, request): ... ... response = Response('Logged in', status=status.HTTP_200_OK) response.set_cookie(key='access', value=f'Bearer {str(access)}', expires=datetime.fromtimestamp(access['exp'])) response.set_cookie(key='refresh', value=str(refresh), expires=datetime.fromtimestamp(refresh['exp'])) # login login(request, user, backend='django.contrib.auth.backends.ModelBackend') return response In frontend we use Vue CLI jquery ajax for Login: $.ajax({ url: "https://something.ngrok.io/api/v1/accounts/login/student/", crossDomain: true, data: { eu: "username", password: "pass" }, xhrFields: { withCredentials: true }, type: "POST", success: function(data, textStatus, request) { console.log(request); }, error: function(request, textStatus, errorThrown) { console.log("error"); } }); and here is ajax for an endpoint that needs Authorization header: $.ajax({ url: "https://something.ngrok.io/api/v1/accounts/vc/user-email/", crossDomain: true, xhrFields: { withCredentials: true }, type: "GET" }).done(function(data, status, xhr) { }); after login we have access and refresh tokens in browser -> storage -> cookies. as we know, can not access cookies that been set by server in js code. The problem is we get 401 unauthorized in protected views and reason is we don't have 'Authorization: Bearer Token here' in request headers. do we need extra config in server or ajax requests? Thank … -
Inserting the same values of string (as a key ) in the dictionary
I was writing the python code in Django. I was facing a problem, wherein I have three fields which are optional: Contact Name Contact Number Contact Email Ram 9888812345 *Blank*(Meaning not present) Ram *Blank(Meaning not present)* ram@gmail.com Shyam 8776532211 shyam@hotmail.com Shyam 7862126121 radhe@gmail.com For this, I had written code as follows: contact_validation = {} for row in df: if not row['Contact Name']: row['Contact Name'] = 'Name' if not row['Contact Number']: row['Contact Number'] = 'Number' if not row['Contact Email']: row['Contact Email'] = 'Email' if (row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']) not in contact_validation.keys(): contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()] = [] contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()].append(row['Name']) else: contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()].append(row['Name']) For this, Currently I have an output as below: {'Ram-9888812345-Email': ['CRM_TestVenue_26_March_23'], 'Ram-Number-ram@gmail.com': ['CRM_TestVenue_26_March_2'] 'Shyam-8776532211-shyam@hotmail.com':[Test2], 'Shyam-7862126121-radhe@gmail.com':[Test3]} But I required the Output as follows: {'Ram-9888812345-ram@gmail.com': ['CRM_TestVenue_26_March_23','CRM_TestVenue_26_March_2'], 'Shyam-8776532211-shyam@hotmail.com':[Test2], 'Shyam-7862126121-radhe@gmail.com':[Test3]} Can anyone please suggest some piece of code or advice.? What needs to be changed? -
How to acheive a forward assignment of m2m object in django?
I know this is a weird question and also aware that django doesn't allow forward creation of m2m objects. Firstly my models.py is: class Option(models.Model): option = m.CharF(...) class Question(models.Model): question = m.CharF(...) answer = m.CharF(...) option = m.m2m(Option) class Test(models.Model): name = m.CF(...) question = m.m2m(Question) As you can see my model, it is a structure for online question paper. I know that only existing questions and options can be added while creating a new test object. How can i achieve my objective of creating the Test, Question and Option objects at the same time. After searching around stackoverflow and some googling, i came to know about .add() but that didn't suite my goal. Any solutions? If you can, please do add a views.py for it. That would be of great help. -
Why does floatformat prevent value from showing on django template
I am trying to format my float values on django template as follows. {{ product.invoicePrice|floatformat:2 }} without the |floatformat:2 part, the invoicePrice shows on the template but once I add the |floatformat:2, nothing is displayed. Any ideas why? -
Ajax connection error between views.py and html Template
I using ajax to loading speed better. But the ajax connection is not working properly. This is the template code that without Jquery document.getElementById('{{ key }}_execute').addEventListener('click', function (event) { var xhr = new XMLHttpRequest(); xhr.open('POST', './more', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById('{{ key }}_more').innerHTML = xhr.responseText; } } xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var data = 'sample'; xhr.send(data); }); and this is view.py def more(request): if request.method == 'POST': adfd = request.POST.get('data') return render(request, 'score/more.html', {'a' : adfd}); if this code is right, the result have to be "test". but it print "None" i think this code can't give a parameter well. But it's working well without error. Is any advise to give and take a information well? -
Difference between resolve(path).url_name & resolve(path).view_name in Django
Can anyone tell me the difference between resolve(path).url_name and resolve(path).view_name in Django? resolve is a method in django.urls module. Please see this link : https://docs.djangoproject.com/en/3.0/ref/urlresolvers/#resolve I went through the description in link but could not understand it. It seems similar to me. -
Django: is_valid() method is always return false when use with ModelForm
is_valid() method is always returning false when i use forms.ModelForm in forms.py to create form,so that i can save all values getting from form which is input by user.This code works fine with forms.Form but not with forms.ModelForm forms.py from django import forms from .models import student class student_data(forms.ModelForm): name=forms.CharField(widget=forms.TextInput,max_length=20) id=forms.IntegerField() address=forms.CharField(widget=forms.TextInput,max_length=50) class Meta(): model=student fields=['name','stu_id','address'] here is models.py from django.db import models # Create your models here. class student(models.Model): name=models.CharField(max_length=20) stu_id=models.IntegerField() address=models.CharField(max_length=60) class Meta: db_table='student' here is views.py from django.shortcuts import render from django.http import HttpResponse from .models import student from .forms import student_data def my_data(request): stu1_name='' stu2_name='' stu_name='' myform=student_data(request.POST) if (request.method=="POST" and myform.is_valid()): stu_name=myform.cleaned_data['name'] stu1_name=myform.cleaned_data['id'] stu2_name=myform.cleaned_data['address'] myform.save() else: myform=student_data return render(request,'show.html',{'student':stu_name,'id':stu1_name,'address':stu2_name}) html file for form <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <form name="form" action="/payment/show/" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Add Me</button> </form> </div> </body> </html> -
How to interact with web site urls ? I have Djoser installed with Django rest framework
I have Djoser installed in Django Rest framwork. I could login using '/token/login/' command by providing {email:'',password:''} field through Postman (it is POST command and I enter through Postman body section as raw data) Djoser documents says that in order to access user info,I need to provide below details in post command $ curl -LX GET http://127.0.0.1:8088/auth/users/me/ -H 'Authorization: Token b704c9fc3655635646356ac2950269f352ea1139' {"email": "", "username": "djoser", "id": 1} Please advice how to send GET request to Django server using postman or browser url, I am a newbie so I dont know to interace with urls Thanks in advance -
Python Django: Pillow installation works but django doesn't recognise it
I am learning to write a basic online shop webapp with Django. I am follow instructions from https://www.youtube.com/watch?v=jZ3DhppbUnM&t=269s, all seems to be fine but I found myself in a loop. When running C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop> Then after installation in PyCharm project terminal (myshop) C:\Users\Llewellyn\myshop>pip install Pillow Collecting Pillow Downloading Pillow-7.0.0-cp38-cp38-win_amd64.whl (2.0 MB) |████████████████████████████████| 2.0 MB 1.7 MB/s Installing collected packages: Pillow Successfully installed Pillow-7.0.0 (myshop) C:\Users\Llewellyn\myshop> and rerunning python manage.py makemigrations in commandprompt I get the same error? Which is confusing because I just installed the package? The complete problem..' C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop>python -m pip install Pillow Requirement already satisfied: Pillow in c:\python36\lib\site-packages (7.0.0) C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop> … -
Django MultiValueDictKeyError when sending multiple select data
I want to render a multivalueDict in the template for iteration. How is that possible?I get MultiValueDictKeyError with the below code @require_POST def mail_forward_dynamicForm(request): receivers = request.POST['receivers'] return render(request, 'mail_forward/dynamic_form.html', {'receivers':receivers }) -
Forbidden(403) permission access error on Apache2.4 on windows machine
I am running my Django app on Apache2.4.38. I have given all the necessary parameters and access to the Apache server. Still, I am receiving a 403 error when I try to access the Application URL. httpd-vhosts.conf: Listen 8084 WSGIPythonPath "D:/WebAttendance/" <VirtualHost *:8084> SSLEngine on SSLCertificateFile "D:/Desktop/Python/WebAttendance/certs/development.crt" SSLCertificateKeyFile "D:/Desktop/Python/WebAttendance/certs/development.key" WSGIScriptAlias / "D:/Desktop/Python/WebAttendance/WebAttendance/wsgi.py" DocumentRoot "D:/Desktop/Python/WebAttendance" <Directory "D:/Desktop/Python/WebAttendance/"> <Files wsgi.py> AllowOverride All Require all granted </Files> </Directory> <Directory "D:/Desktop/Python/WebAttendance/home/static/"> Require all granted </Directory> Alias /static "D:/Desktop/Python/WebAttendance/home/static" ErrorLog "D:/Desktop/Python/WebAttendance/log/error.log" CustomLog "D:/Desktop/Python/WebAttendance/log/access.log" common </VirtualHost> Error: Forbidden You don't have permission to access / on this server. -
python-celery docker container not able to read images and files passed by python-model docker container
docker-compose.yml version: "3" networks: app-tier: driver: bridge services: python-api-celery: &python-api-celery build: context: /Users/AjayB/Desktop/python-api/ networks: - app-tier volumes: - .:/python_api/ - .:/python_model/ environment: - PYTHON_API_ENV=development command: > sh -c "python manage.py makemigrations && python manage.py migrate" python-api: &python-api <<: *python-api-celery ports: - "8000:8000" command: > sh -c "python manage.py runserver 0.0.0.0:8000" python-model: &python-model build: context: /Users/AjayB/Desktop/Python/python/ ports: - "8001:8001" networks: - app-tier environment: - PYTHON_API_ENV=development volumes: - .:/python_model/ - .:/python_api/ depends_on: - python-api command: > sh -c "cd /python-model/server/ && python manage.py migrate && python manage.py runserver 0.0.0.0:8001" python-celery: &python-celery <<: *python-api-celery depends_on: - redis command: > sh -c "celery -A server worker -l info" redis: image: redis:5.0.8-alpine hostname: redis networks: - app-tier expose: - "6379" ports: - "6379:6379" command: ["redis-server"] Application workflow: I hit APIs passing image to python-api on port 8000., python-api then calls python-model at port 8001 to predict the outcome of an image., which is then passed to python-celery to display images and results in mail. The docker-compose build went smooth, I'm able to run all the 5 containers.., output of docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES xxxxxxxxxxxx integrated_python-celery "sh -c 'celery -A se…" 13 minutes ago Up 5 seconds 8000/tcp integrated_python-celery_1 …