Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I log out, I find this error "detail": "Authentication credentials were not provided."
I am using django-rest-knox, when I logout using knox_views.LogoutAllView.as_view(), it gives me this error "detail": "Authentication credentials were not provided." note: I am using a custom user model(AbstarctUser and BaseUserManager) here is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email','birth_date','first_name','last_name') # there is a registerserializer too class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") and here's views.py class LoginView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user= serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
DRF Project Static Files Problem On Server
I'm trying to host the project I prepared on PythonAnywhere. Even though I run the collectstatic command, I can't get any results. When I visit the url, the design does not appear, the same is true for the Admin. When I looked, the requested address is static file instead of static_base. But static_url and static_root should have different names anyway. Do I need to add something related to this field in the urls.py file? Because I haven't seen anything like it when I read it. Settings.py import os from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication' ], } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME" : timedelta(minutes = 15) } ALLOWED_HOSTS = ["talhakoylu.pythonanywhere.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "book", "country", "account", "school", "nested_inline", "quiz" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to add more fields in django-allauth User model?
I want to add more fields in Django allauth user model. I created a User-Profile model in a one-to-one relation with auth-user and tried to create user-profile object in form.py. But this method is not working. Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): profile_picture = self.cleaned_data['profile_picture'] user.save() UserProfile.objects.create(user=user, profile_picture=profile_picture) return user -
DetailView + input button
I would like to add a button to "validate" a user towards the next step of his registration. The staff member have to "validate" the user in the user detail page. So I created a DetailView view with template with all the details of this user. But I would like to know if it is possible to write code in DetailView function to allow the user to increment his step_registration variable when I click on "validate" ? Here is my DetailView function : views.py class StudentDetailView(DetailView, LoginRequiredMixin): model = Student login_url = login student_detail.html {% block content %} <h1>Etudiant: {{ student.user.firstname }} {{ student.user.firstname }}</h1> <ul> {% if student.photo %} <li> Photo :<img src="{{ student.photo.url }}", width = 250, height = 300>"> </li> {% endif %} <li> Etat de l'inscription : {{ student.step_registration }}</li> <li> Date de naissance : {{ student.birthdate }} </li> </ul> <button class="btn btn-secondary"> Validate ! </button> {% endblock %} The step registration variable is called "step_registration", so I want to do student.step_registration += 1 when a staff member click on "validate" -
CS50 Project 1 Search bar Question: How do I make the search bar filter through the entries to find the possible ones and display them in a list?
I am working on CS50 Project 1 to make a search bar that searches through the possible wikipedia-like entries using Django. If you type in the exact name of the title, you will be redirected to that entry page. How do I display a list of possible entries using the query? views.search def search(request): entry_list = util.list_entries() query = request.GET.get("q", "") if query in entry_list: return redirect(get_entry, query) else: results = [] for entry in entry_list: if query in entry: results.append(entry) return render(request, "encyclopedia/index.html", { "entry": results }) index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href = "wiki/{{ entry }}"><li>{{ entry }}</li></a> {% endfor %} </ul> {% endblock %} If anything but the exact title is searched for, the user receives a blank page. How do I fix this? -
how to modify the field value of a model when another field value of another model changes?
I have 4 models: reputation, goldbadge, sylverbadge and bronzebadge would like to add 1 in the bronzebadge model when the reputation model score reaches 100 score and this must be done automatically here are my models class reputation(models.Model): score=models.BigIntegerField(default=0) user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="reputation_user") def __str__(self): return self.score class goldBadge(models.Model): score=models.BigIntegerField(default=0) user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="goldbadge_user") def __str__(self): return self.score the other models are almost identical My concern is that when saving the reputation model we will first check if the score is greater than or equal to 100 if yes then we increase the value of sylverbadge by 1 I am only a beginner in python and django so your help will do me a lot of good thank you for your answers already -
Django -Python Copyfile using win32api permission denied
I was looking to implement a copy on the server where I click a button on the client side html of my web server and the server implements a copy of a particular file inside the server from a fixed destination to another destination inside the server itself. The server is windows based so I was using the win32api CopyFile method but it shows access denied error . How can I resolve this issue? I have tried setting permissions of the drive. It seems as if Django needs administrative privileges for this but not sure. Other solutions are welcome. -
django models containing list of another model
I have to implement adding different pages/urls to the favorities from a list of pages. I am using django and have a user class inbuilt and provided by django, a page class like this class Page(models.Model): ... category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=TITLE_MAX_LENGTH) url = models.URLField() Below is category class class Category(models.Model): ... name = models.CharField(max_length=NAME_MAX_LENGTH, unique=True) ... I have to store this list of pages per user as their favorites. I can think of it like many users will store many pages and therefore, add a field to the User model like this : pageToSave = models.ManyToMany(Page) or I can think of it like one user saves many pages and implement it like this class Page(models.Model): ... category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=TITLE_MAX_LENGTH) url = models.URLField() **fk = models.ForeignKey(User, on _delete=models.CASCADE)** Which if any approach is correct or otherwise, what can you suggest? -
I tryed to create a db usign python and django and have a method "DELETE" that don't execute and return error 500 in postman
Just new to python programming, Django SQL, and try to create a DB, verify it with Postman and SQLLiteStudio! Using Django to create a DB and python (3.9.6).When I run the DELETE method, in postman return error 500 without executing DELETE. {In my cmd I don't see any error msg} [error msg in Postman trying to execute DELETE ] : https://i.stack.imgur.com/tspKr.png Views : from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments,Employees from EmployeeApp.serializers import DepartmentSerializer,EmployeeSerializer # Create your views here. @csrf_exempt def departmentApi(request,id=0): if request.method=='GET': departments = Departments.objects.all() departments_serializer = DepartmentSerializer(departments, many=True) return JsonResponse(departments_serializer.data, safe=False) elif request.method=='POST': department_data=JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!!" , safe=False) return JsonResponse("Failed to Add.",safe=False) elif request.method=='PUT': department_data = JSONParser().parse(request) department=Departments.objects.get(DepartmentId=department_data['DepartmentId']) department_serializer=DepartmentSerializer(department,data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method=='DELETE': department=Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Succeffully!!", safe=False) Models: from Django.DB import models class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Employees(models.Model): EmployeeId = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Department = models.CharField(max_length=100) DateOfJoining = models.DateField() PhotoFileName = models.CharField(max_length=100) Serializers: from EmployeeApp.models import Departments, Employees class DepartmentSerializer(serializers.ModelSerializer): class Meta: model=Departments fields=('DepartmentId','DepartmentName') class EmployeeSerializer(serializers.ModelSerializer): class Meta: model=Employees fields=('EmployeeId', 'EmployeeName', 'Department', 'DateOfJoining', 'PhotofileName') … -
Django admin 'view on site' returns NoReverseMatch, but urls all work from elsewhere
I posted an earlier version of this question here, but most of that has been cleared up and now I just have this one more narrow issue I can't solve: I consistently get NoReverseMatch errors when using ‘view on site’ from within the admin. This is an example of the error: NoReverseMatch at /admin/r/10/5/ Reverse for 'WorklogDetail_url' with keyword arguments '{'app_label': 'ktab', 'slug': 'hattie-and-deadline'}' not found. 1 pattern(s) tried: ['ktab/work/(?P[-a-zA-Z0-9_]+)/$'] However, if I type the url into the address bar myself, or click on it from ListView, it comes up just fine. I've learned that 'view on site' does not use my view, but one called 'shortcut'. I also understand that this view searches by content type and object id, rather than my kwargs or slug. I verified that both are correct in the admin's url format, like /admin/r/10/5/, but I don't know what the '/r/' stands for. Anyway, that's where I'm stuck. Your help appreciated. Thanks. -
Cannot use a slash in a variable for filtering a Django query?
While querying data for a template this is working: prev_season_gws = PlayerGW.objects.filter(player=player, season="2020/21") This is not working: previous_season = functions.previous_season # The function is returning a string of "2020/21" prev_season_gws = PlayerGW.objects.filter(player=player, season=previous_season) Why isn't it working with a variable? I also tried to wrap the previous_season variable with the str() function without success. -
Duplicate app naming issue in Django without renaming the app
I know there are a few other posts about this out there and renaming my messages app might solve the issue, but I don't want to change the name of my messages app, and the label solution from this post just returns this error instead: django.core.exceptions.ImproperlyConfigured: The app label 'email.messages' is not a valid Python identifier. And the above error is after adding the label and default_app_config fields to MessagesConfig like the other post suggests: class MessagesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'messages' label = 'email.messages' default_app_config = 'messages.apps.MessagesConfig' My INSTALLED_APPS in settings.py is as follows: INSTALLED_APPS = [ # my apps # 'accounts', 'subscribers', 'django_filters', 'accounts.apps.AccountsConfig', 'core', 'messages', # 'messages.apps.MessagesConfig', # 'email.messages', # django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And I'm getting this error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: messages What's the actual workaround for this (other than renaming messages to a different app name)? Thanks... -
How can i control model fields in for loop in django?
I am new to django. I am trying to build an Quiz web application that puts one question at a time and as soon as student select one answer on radio button , it immediately shows response whether his ans is correct or incorrect. If incorrect, it shows them the right ans.Then after clicking on submit button next ques appears. After last question, result is shown to them. I have 2 problems- 1.My first problem is i am not able to put one ques at a time from all set of questions. However i am able to put all questions at a time. How can i do that? 2.My second problem is i don't know , how i will go to next ques after clicking on submit button. Below are my files. Please help me with this. I will be highly grateful to you. -
how to fetch product size too with product and its quantity in django
I want to fetch user selected size with the quantity and product but I don't understand how to do that any how idea to achieve that i try to look documentation but didn't find one any idea how to do that my views.py for add to cart class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> right now I am only able to fetch its item id and quantity any suggestion will be appreciated thank you -
ModuleNotFoundError: No module named 'ckeditor', how do i solve this?
I have ckeditor installed inside venv. in my setting, i also added ckeditor and ckeditor_uploader in my setting, i also added to requirements.txt. but nothing seems to work still get ModuleNotFoundError: No module named 'ckeditor' here is my setting.py THIRD_PARTY_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'images/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } urls.py urlpatterns = [ path('_ckeditor/', include('ckeditor_uploader.urls')), ] models.py from ckeditor_uploader.fields import RichTextUploadingField class About(models.Model): name = models.CharField(max_length=50) about_text = RichTextUploadingField() def __str__(self): return str(self.name) -
How to filter a child object's parent field for Django
I want to have a form with fields that are filtered based on Django group model name field. For example, I have a model that is connected to Django User model which is connected to Django group model like so: class customUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name I have added a row of data in Django group using Django admin panel called 'Teacher'. What I'm trying to do is to have my form list only customUser that is listed as "Teacher" in Django group model. My form: class myForm(ModelForm): class Meta: model = customUser fields = ['user '] def __init__(self,*args,**kwargs): super (myForm,self ).__init__(*args,**kwargs) **# What I want to achieve but doesnt work.** self.fields['user'].queryset = customUser.objects.filter(user.group.name = "Teacher") Any help is greatly appreciated. -
Django dirtyfields - can we access the before and after state?
I'm interested in using django-dirtyfields to track if a field is changed. I also want to access what the field was before and after the change and I'm not sure how to do this. class GradeBookSetup(DirtyFieldsMixin, models.Model): user = models.OneToOneField(CustomUser, on_delete=CASCADE) scale_mode = models.CharField(max_length=7, blank=True, default='MOE') def save_model(self, request, obj, form, change, *args, **kwargs): # need to save user to each object obj.user = request.user if self.is_dirty(): dirty_fields = self.get_dirty_fields() if 'scale_mode' in dirty_fields: if scale_mode_before == 'MOE' and scale_mode_after == 'MOEPLUS': super().save_model(request, obj, form, change, *args, **kwargs) I looked at the source code for dirtyfields but I'm not at the level yet which I can understand everything that it's doing and how I can access values from it. -
Best practice in avoid page reload issue during payment
I have been coding a Django ecommerce project and there is a issue with page reload during payment that causes my program to crash. When the customer uses their mobile device the workflow is: Customer fills in a form with: name email some comments The form is being sent to the backend via a post. A new html page is rendered together with the payment UI embebbed in the same page. The payment UI is rendered by payment vendor's javascript code Customer enters a mobile phone number in the payment UI to allow MobilePay payment option and clicks Pay. Now another app installed on client's phone the MobilePay app opens, and the customer confirms the payment there. Immediately as the client is being diverted to this app my website generates a new page with error This web page requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page ERR_CACHE_MISS Then at MobilePay app once the payment is complete the client is directed back to their browser … -
build a school grade tracking mobile app for parents in flutter and django
I hope you are doing well. I need to build a school grade tracking mobile app for parents in flutter and django. I don't know much about flutter. Has anyone worked on this project before? Could you help me? Could I have a source code to get inspiration from it ? -
What is the difference between a path and a url?
profile.image.url profile.image.path These are the two ways in usage...What's it working? -
No Output from views.py file after getting POST from template file (Django)
I have been trying to get details filled in a form,back in a python file using django. Everything seems fine but the form details are not getting displayed in the terminal. views.py file: from django.shortcuts import render from basicapp import forms # Create your views here. def index(request): return render(request,'basicapp/index.html') def form_name_view(request): form = forms.FormName() if request == "POST": form = forms.FormName(request.POST) if form.is_valid(): #DO SOMETHING print("Validation SUCCESS") print("NAME: " + form.cleaned_data['name']) print("EMAIL: " + form.cleaned_data['email']) print("AVANODA KARUTHTHU: " + form.cleaned_data['text']) return render(request,'basicapp/form_page.html', {'form' : form } ) form_page.html file : ( I have removed the Bootstrap CDNs ) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Forms</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, shrink-to-fit=no"> </head> <body> <div class="container"> <div class = "jumbotron"> <h2> Fill out the form </h2> <form method="POST" action = ""> {{ form.as_p }} {% csrf_token %} <input type="submit" class = "btn btn-primary" value = "Submit"> </form> </div> </div> </body> </html> Please help. Thanks in advance . -
Django Form BidForm(request.POST or None) sometime load form data otherwsie null
I have following BidForm Class... class BidForm(ModelForm): # listing = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Bids fields = ('listing', 'bid_price') # def clean_bid_price(self): # data = self.cleaned_data["bid_price"] # listing = self.instance.listing # if listing.last_high_bid: # if data <= listing.last_high_bid.bid_price: # raise forms.ValidationError('bid price less than last bid price') # else: # if data < listing.starting_bid_price: # raise forms.ValidationError('bid price less than starting price') # return data The moment I uncomment either listing field or clean_bid_price validation method, the form can not load the form data and I get form instance with instance object set to None type. However if I leave it as it is as well then I debugged full init method and could not see form loaded with post data till the last line of init is done. However somehow magically the instance object of form has post data. Already spent quite a lot of time trying to debug simple function but not sure why it's failing. -
could not import CSV file to database in pgadmin
I got a CSV file and I want to import it to the created table in pgadmin a part of my CSV file is: Bernard,http://dummyimage.com/151x100.png/dddddd/000000,"",664-411-7541,bdhenin0@pagesperso- orange.fr,true,2020-09-06 Rafaellle,http://dummyimage.com/142x100.png/ff4444/ffffff,"",354-258- 6044,rephson1@ed.gov,true,2021-05-11 Erminia,http://dummyimage.com/241x100.png/5fa2dd/ffffff,"",802-987- 7344,eklimpke2@sourceforge.net,true,2021-05-10 and my model is: class Realtor(models.Model): name=models.CharField(max_length=200) photo=models.ImageField(upload_to='photos/%y/%m/%d/') description=models.TextField(blank=True) phone=models.CharField(max_length=50) email=models.CharField(max_length=50) is_mvp=models.BooleanField(default=False) hire_date=models.DateTimeField(default=datetime.now(),blank=True) and here is the screen of pgadmin: enter image description here -
Django how to show all child objects under their parent in html?
I want to show my all child objects under it's parent in my html template. How to do it in Django? #html {%for i in contact %} {% if not i.parent %}#shwing only parent objects ticket #parent_id{{i.message}} #here I want to list all child object of my parent {%endif%} {%endfor%} here is my models.py: class Contact(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') name = models.CharField(max_length=250) email = models.EmailField(max_length=500) message = models.CharField(max_length=2000,blank=True,null=True) parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) -
Maximum size of payload sent as POST request (Django)
Say I have a Django project (not Django REST) and I have an API endpoint. I have my payload structured as data = `{"cred":"averystrongpassword","books":"['book1','book2'...]", "prices":"['100','150',...]"}` request.post("http://myapp.com/api/, data = data) right now books and prices are a length of max, say, 30 each - but this might grow to thousands. Is there a limit of byte-size a payload can contain (both from the sender i.e the requests module) and the API (Django) or does it all boil down to performance?