Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetching Values from models including duplicates
I have my models designed like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) The data stored in the authors field is like this: authors Author A Author A Author B Author B Author C Now in my views.py file I am trying to query the data like this: allAuthors = Books.objects.all() for a in allAuthors(): print(a) The output displayed is : Author A Author B Author C Why are the duplicates not displayed? How can I show the duplicates as well? Sorry if I am missing the obvious. Thanks for your time in advance. -
Django template not rendering at all
I have all my django views and templates working, however, when i tried to make this new, simple one it simply wouldn't render. views.py: def ListRefView2(request): return render(request, "reference/test.html", context) urls.py: from django.urls import path from .views import ( ListRefView, ListRefView2, CreateRefView, DetailRefView, UpdateRefView, DeleteRefView, ) urlpatterns = [ path('', ListRefView), path('test2/', ListRefView2), path('<str:slug>/delete/', DeleteRefView), path('<str:slug>/edit/', UpdateRefView), path('<str:slug>/', DetailRefView), path('test2/', ListRefView2) ] test.html <h1>Hello </h1> I am trying to get "Hello" to show up via the "ListRefView2" view -
Adding to multiple foreign keys at once from Django Admin
I have this FAQ model which has a foreign key to Organization. `# Create your models here. class Faq(BaseModel): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) faq_title = models.CharField(max_length=100) faq_content = models.CharField(max_length=1000) faq_category = models.CharField(max_length=50) class Meta: unique_together = (("organization", "faq_title"),)` From the Django Admin I can add an FAQ to an Organization. How can I make it so that I can add to all Organizations at once in the Django Admin? The goal is to have some FAQ's available to all organizations, and some FAQ's to just one or two organizations. -
Django runserver not working after adding channels
I get an error when trying to run my server. Error: PS C:\Programming\Python\Django\Messager> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 11, 2021 - 18:17:54 Django version 3.1.7, using settings 'Messager.settings' Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\routing.py", line 28, in get_default_application module = importlib.import_module(path) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'messager' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run application=self.get_application(options), File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\management\commands\runserver.py", line 132, in get_application return StaticFilesWrapper(get_default_application()) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\routing.py", line 30, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION … -
How to set password to user in database directly?
I have a website for university timetable connected to microsoft sql server, there I have django table auth_user. Users can't register by themselves, university provides them with username and password. So in the table auth_user I have to fill data manually, but how can I fill the field which is responsible for password since it has to be hashed? I found only way to set password is to log in as admin, and change passwords in admin site, but that is not quite correct in terms of working with database as if I had to fill more than 100 students, it would be tiresome to do so. Maybe there is another approach to fill passwords directly in the database? -
Chaining Queries in Django
I am building a data processing app which allows user to upload multiple excel sheets, which is processed and returned back to user. I have created 3 models - 1st model is overall, 2nd model is capturing individual excel workbooks, in the 3rd model excel workbooks are opened and data for each excel sheet (sheets within workbooks) is captured. I need advise on 3 things: Is my model structure efficient given that users will be uploading multiple excel sheets? Given that users may do upload multiple times in a day, how do I retrieve the latest batch of files for processing? I need to take user inputs against each sheet uploaded by user (3rd model) in a single view while parallelly showing a preview of the table to the user? Please help with your opinions. class UserUpload(models.Model): number_of_workbooks = models.IntegerField(blank=True,null=True) file_size = models.FloatField(blank=True,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE,null=False,blank=False) multiple_sheets = models.BooleanField(blank=False,default=False) var_1 = models.BooleanField(blank=False,default=False) class FileUpload(models.Model): file_field = models.FileField(blank=False,upload_to=user_directory_path) userupload = models.ForeignKey(UserUpload,related_name='user_uploads',on_delete=models.CASCADE) class FileSheetData(models.Model): fileupload = models.ForeignKey(FileUpload,related_name='file_sheets',on_delete=models.CASCADE) sheetname = models.CharField(blank=False,max_length=256) var_2 = models.BooleanField(blank=False,default=False) var_3 = models.PositiveIntegerField(blank=False,default=0) -
Is there any way to get request data in django serializer?
This is the sample view where I am taking some query_params and I want to access the same in serializer which will I use in this view accordingly. class SomeApi(APIView): def get(self, request): username = request.query_params.get('username') page = request.query_params.get('page') phone = request.query_params.get('phone') if username and page and phone: return Response({'message':'some message'}, status=status.HTTP_200_OK) return Response({'message':'error'}, status=status.HTTP_400_BAD_REQUEST) This is a sample Serializer where I want to get query_param phone if available and write some logic to return an extra method field. class SomeSerializer(serializers.ModelSerializer): class Meta: model = Some fields = '__all__' def get_isPhone(self, obj): phone = ??? #HERE I WANT TO GET phone query_params which is passed in API call if phone: return phone else: return 0 -
How to display the foreign key and many-to-many fields in Django admin `list_display`?
How to display the foreign key and many-to-many fields in Django admin list_display? models.py: class Book(models.Model): title = models.CharField(max_length=150, blank=False) class Character(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='character') name = models.CharField(max_length=50) class Author(models.Model): book = models.ManyToManyField(Book, related_name='author') name = models.CharField(max_length=50) admin.py: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'characters', 'authors') def characters(self, obj): ??? def authors(self, obj): ??? -
No 'Id' in the results of the Orderdict although id field is present in the serializers in Django Rest Framework
I tried to create an update api for Orders but in the result of the postman, I am getting this error KeyError at /api/updateorder/260 'id' I have put the id field both in OrderUpdate Serializer and OrderItemUpdateSerializer as you can see below. Also, I have printed the validated_data.pop('order_items'). In the result of print, I get Orderdict which has no id field. I don't know why id is not showing. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): return sum([_.price for _ in self.order_items.all()]) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property def price(self): total_item_price = self.quantity * self.order_variants.price return total_item_price My serializers: class OrderItemUpdateSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = OrderItem fields = ['id','order','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemUpdateSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['id','ordered','order_status','order_items','total_price','billing_details'] def update(self, instance, validated_data): instance.order_status = … -
Cloudinary shown incorrect url in Django
I have created a model with upload img to cloudinary but shown the incorrect link in django template which has 2 https:// inside of it. Please help. models.py: class Product(models.Model): img = models.ImageField(upload_to='product', height_field=None, width_field=None, max_length=100, default='https://res.cloudinary.com/dgdhnbsae/image/upload/vxxxx/product/xxxx.jpg') def get_img(self): return f"{'/media/product/'+self.img}" I have set the related configuration according to the tutorial setting.py: INSTALLED_APPS = [ xxxx 'cloudinary_storage', 'cloudinary', ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'xxxx', 'API_KEY': 'xxxxx', 'API_SECRET': 'xxxxx' } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' templates: <div class="featured__item__pic set-bg" data-setbg="{{ product.img.url }}"> However, turned out: https://res.cloudinary.com/xxxx/image/upload/v1/media/https://res.cloudinary.com/vxxxx/image/upload/xxxxx/xxxxx.jpg there has two https in side the url -
Store the last edited name of user after edited
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to store the last edited name of the user after edited the name. I mean, I want to store previous name after edited the new name. BUT when i try to access the name then it shows the updated name. I also tried by saving previous name while editing but it didn't worked for me. I also tried Tracking Who Made the Last Changes to a Model BUT i don't know how it works. Any help would be Appreciated. Thank You in Advance. -
Django Save image without using Django Forms?
I am trying to save the image without using Django forms in the media folder. The image should save in the media\seller_profile folder and its path has to be entered in a database like seller_profile\abc.png but somehow I am getting only abc.png missing seller_profile. Models.py class SellerProfile(models.Model): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, default=None, null=True) seller_profile_picture = models.ImageField(upload_to='seller_profile', default="seller_profile/empty_profile.png") def __str__(self): return self.email Views.py def profile(request): if request.method == "POST": profile_data = SellerProfile.objects.filter(email = str(request.user)).update( first_name = request.POST.get("First name"), seller_profile_picture = request.FILES["seller profile picture"], ) print("object File --->", request.FILES["seller profile picture"]) return redirect("/seller/profile") else: user_data = SellerProfile.objects.filter(email=str(request.user)) if len(user_data) == 0: SellerProfile.objects.create(email = str(request.user)) data_entered = {"First name": "Value not Provided"} else: data_entered = dict() data_entered["First name"] = user_data[0].first_name return render(request, "seller/profile.html", {"data_entered":data_entered}) seller/profile.html {% extends 'general/layout.html'%} {% block body %} <div class="container"> <div class="jumbotron"> <form method="post" enctype=multipart/form-data> {% csrf_token %} {% for attribute, placeholder in data_entered.items %} <div class="form-group"> <dt><label for="{{attribute}}">{{attribute}}</label> <dd><input class="form-control" id="{{attribute}}" name="{{attribute}}" type="text" placeholder="{{placeholder}}" required> </dd> </div> {% endfor %} <dt><label for="seller profile picture">Profile Picture</label> <dd><input class="form-control" id="seller profile picture" name="seller profile picture" type="file" required> </dd> </dt> <div class="form-group text-center"> <p> <input class="btn btn-primary " type="submit" value="Update"> </p> </div> </form> </div> </div> {% endblock%} -
Order by related fields of different models in Django Admin
I want to order by the business_name, but the ordering isn't working due to some relationships, below is my first model : class LoanApplication(models.Model): loan_id = models.CharField( 'Loan Application ID', max_length=40, unique=True, null=True, blank=True) loan_taker = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, null=True, blank=True, verbose_name='Customer Profile', related_name='loan_entries') submitted_date = models.DateTimeField( 'Submitted Date', null=True, blank=True) then, I have the CustomerProfile model as below : class CustomerProfile(models.Model): customer_id = models.CharField( 'Customer Profile ID', max_length=64, unique=True, null=True) cooperation_partner = models.ForeignKey( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Jurisdiction'), related_name='partner_user_profile') user = models.OneToOneField( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('User'), related_name='user_profile') tipster_partner = models.ForeignKey( TipsterPartner, on_delete=models.PROTECT, null=True, blank=True, verbose_name='Tipster Partner') So, I wanted to point to the Business model , it's as below : class Business(models.Model): business_id = models.CharField( 'Business ID', max_length=64, unique=True, null=True, blank=True) business_name = models.CharField(_('Business'), max_length=128) business_address_street = models.CharField( 'Business Address Street', max_length=50, blank=True) then, we have the last one which is the CustomerProfileBusiness as below : class CustomerProfileBusiness(models.Model): business = models.ForeignKey( Business, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Business'), related_name='customer_profile_relation') correlative_id = models.CharField( _('Business ID'), max_length=64, unique=True, blank=True, null=True) customer_profile = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, verbose_name=_('Customer Profile'), blank=True, null=True, related_name='business') Now, I do the ordering in the Admin page of the LoanApplication as below : @admin.register(LoanApplication, site=admin_site) class LoanApplicationAdmin(admin.ModelAdmin): ordering = ( … -
DRF SearchFilter with Multiple Models and Uncommon Search Fields
I am using DRF SearchFilter with Multiple Model View to search across multiple models. However, the models do not share common search fields. DRF gives an error because ModelA does not contain b_name and c_name, etc. My quick and dirty workaround is to add dummy fields to the models as needed. Is there a way to allow fields names in search_fields even if the model doesn't have that field? Another approach is to aggregate 3 separate ListAPIViews with respective search_fields for ModelA, ModelB, and ModelC in to one view. Is that possible? class ModelA(models.Model): a_name = models.CharField(null=True, blank=True) a_title = models.CharField(null=True, blank=True) class ModelB(models.Model): b_name = models.CharField(null=True, blank=True) class ModelC(models.Model): c_name = models.CharField(null=True, blank=True) class SearchListView(ObjectMultipleModelAPIView): querylist = [ { 'queryset': ModelA.objects.all(), 'serializer_class': ModelASerializer, }, { 'queryset': ModelB.objects.all(), 'serializer_class': ModelBSerializer, }, { 'queryset': ModelC.objects.all(), 'serializer_class': ModelCSerializer, }, ] filter_backends = [filters.SearchFilter] search_fields = ['a_name', 'a_title', 'b_name', 'c_name'] -
Allow only emails to access site where logos are (Django)
I have a page mysite.com/logos containing images. I want to be able to link to those emails when sending out news-letters (instead of attaching them), but I don't want users (or others) to be able to access them. Right now people can just go to "mysite.com/logos" - I would prefer that'll throw an 403/404 error for all, apart from the emails (and admins). -
I am creating an ecommerce Website .I am not able to list out products from django using Rest API .i am using axios
The above is the code which I have written in my home.vue , when I run the local server it runs without any error but its not listing out the products . I am usig Django for the Backend and REST API to fetch details about product using api.The problem is that I am not able to list out products on the front-end.The below code is th Home.Vue that portion is not displaying while I am inspecting in Google Chrome. <div class="column is-3" v-for="product in latestProducts" v-bind:key="product.id" > <div class="box"> <figure class="image mb-4"> <img :src="product.get_thumbnail"> </figure> <h3 class="is-size-4">{{ product.name }}</h3> <p class="is-size-6 has-text-grey">${{ product.price }}</p> View Details </div> </div> <script> // @ is an alias to /src import axios from 'axios' export default { name: 'Home', data() { return{ latestProducts: [], } }, components: { }, mounted(){ this.getLatestProducts() }, methods: { getLatestProducts() { axios .get('http://127.0.0.1:8000/api/v1/latest-products/') .then(response => { this.latestProducts = response.data }) .catch(error =>{ console.log(error) }) } } } </script> -
Django HttpResponseRedirect(reverse())
return HttpResponseRedirect(reverse('pollresult', agrs=[str(obj.id)])) return HttpResponseRedirect(reverse('pollresult', agrs=[str(obj.id)])) TypeError: reverse() got an unexpected keyword argument 'agrs' -
How to pass parameters to request during testing?
I run the test via Client(). post, but request.POST does not contain the passed dictionary test.py from django.test import TestCase from django.test.client import Client class AccountTests(TestCase): def setUp(self): self.email = 's@s/com' self.name = 'John' self.mobile = "+799999999" def test_user_login(self): c = Client() response = c.post('/login-otp/', {'email': self.email, 'name': self.name, 'mobile': self.mobile}, follow=True) views.py def login_otp(request): mobile = request.session['mobile'] # the interpreter does not see the "mobile" key context = {'mobile': mobile} if request.method == 'POST': otp = request.POST.get('otp') -
How to resolve Django Administration Problem with "no such table"?
I am able to follow the instructions for Creation and Activation for Database Model from the book "Django for Beginners" by William S. Vincent. I am able to reach the first image, but then after that 'get' and 'post' requests probably are not working. adding my code for models.py : from django.db import models class Post(models.Model): text = models.TextField() The following is from admin.py file: from django.contrib import admin from .models import Post admin.site.register(Post) -
Using a django app as a central authentication system to other django apps
(I am relatively new to Django, so sorry if I was misunderstanding anything ^^") so let say I have app1 and app2, and I want to implement the same groups, roles and permission through these two apps by only having one database. my idea was to create a central back end server that the two app authenticate through and grabs the roles from it. essentially this can be used for SSO(Single sign on) later. but now the target is to authenticate the user logging through one app and get his roles and groups from there. In Django documentation I found "Authentication using REMOTE_USER": which should allow me to do remote authentication (which is my target), was able to make it run but how am I supposed to give it the link of the Django authentication server. my understanding is that after setting this remote user authentication, all groups, roles and permission checks doesn't need to be changed since Django should have access to the remote server that it authenticates through. I hope that I wasn't misunderstanding "Authentication using REMOTE_USER" concept. also if there is any other ideas on how to implement this, please let me know. Thank you ! -
WAGTAIL - users who don't have access to publish pages are also getting option to approve and publish pages in home admin page
I am using wagtail for a website and I have created a group for editors which has add and edit permission for all the pages. Editors have to submit pages for moderation for publishing but they are also getting the Awaiting your review section on the home page and they have the right to publish a page in that section. I don't know why this is happening. Is there any bug or Am I missing something? -
Django Admin Select All in a List
I am working on React DRF project. I have my models designed like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) My Admin Panel for the authors field shows data like this authors Author A Author B Author C Author D Currently, Only one the Author (for example - Author A) is selected by default. Manually, I am able to select multiple authors by holding the control key. Is there any way to automatically select all the Authors in the author list whenever data gets added to this field? Thanks for your time in advance. -
Django - create a list of IDs from Session and filter it
I have a view, where I add products via post request and add it in sessions, but after I filter this list, I didn't get any results: views.py: Artikler_List = Products.objects.filter(UserID_id=user_id) ... if 'add_product' in request.POST: product_id = request.POST.get('product_id') request.session['product_id'] = product_id request.session.modified = True return redirect('add_order_view') try: order_product_ids = request.session.get('product_id', []) print(order_product_ids) order_product_ids.insert(len(order_product_ids), Artikler_List.ID) #print(order_product_ids) choosen_products = Products.objects.filter(ID__in=[order_product_ids]) print(choosen_products) except: choosen_products = None Is it not the correct way to create a list? -
POST http://localhost:16/auth/registration/ 400 (Bad Request) in Django and Reactjs
I am making a registration in django and reactjs project, i use django rest auth for registration api, but i am having a problem, when i send request to server, it responses: POST http://localhost:16/auth/registration/ 400 (Bad Request) I don't know how to fix this, can anyone help me ? this is my code ! Register.js import React from 'react' import axios from 'axios' class Register extends React.Component { constructor(props) { super(props) this.state = { username: '', email: '', password1: '', password2: '', } this.OnChangeUsername = this.OnChangeUsername.bind(this) this.OnChangeEmail = this.OnChangeEmail.bind(this) this.OnChangePassword1 = this.OnChangePassword1.bind(this) this.OnChangePassword2 = this.OnChangePassword2.bind(this) this.OnSubmit = this.OnSubmit.bind(this) } OnChangeUsername(event) { this.setState({ username: event.target.value }) } OnChangeEmail(event) { this.setState({ email: event.target.value }) } OnChangePassword1(event) { this.setState({ password1: event.target.value }) } OnChangePassword2(event) { this.setState({ password2: event.target.value }) } OnSubmit(event) { event.preventDefault() axios.post('http://localhost:16/auth/registration/', { username: this.state.username, email: this.state.email, password1: this.state.password1, password2: this.state.password2, }) .then(res => { alert('Registered !') this.props.history.push('/') }) } render() { return ( <div> <form onSubmit={this.OnSubmit}> <input type="text" name="username" value={this.state.username} onChange={this.OnChangeUsername} /> <br></br> <input type="text" name="email" value={this.state.email} onChange={this.OnChangeEmail} /> <br></br> <input type="text" name="password1" value={this.state.password1} onChange={this.OnChangePassword1} /> <br></br> <input type="text" name="password2" value={this.state.password2} onChange={this.OnChangePassword2} /> <br></br> <button>Register</button> </form> </div> ) } } export default Register; -
Django Filter - how to call a single method for any combination of filter?
I'd like all my filters to route to a single method, so I can look at each and decide logic based on which ones are set. I have this working, but each filter is now calling the same method once, leading below code to print hi 4 times. Is there a best practice way to route all filters to a single method? I'd like hi to be only printed once here, and wondering if I can avoid using a hacky solution. class CityFilter(FilterSet): start_date_i = django_filters.DateTimeFilter(field_name='dept_date', method='filter_city') start_date_j = django_filters.DateTimeFilter(field_name='dept_date', method='filter_city') end_date_i = django_filters.DateTimeFilter(field_name='ret_date', method='filter_city') end_date_j = django_filters.DateTimeFilter(field_name='ret_date', method='filter_city') class Meta: model = models.City def filter_city(self, queryset, name, value): print('hi') data = self.data sdate_i = data.get('start_date_i') sdate_j = data.get('start_date_j') edate_i = data.get('end_date_i') edate_j = data.get('end_date_j') # do expensive stuff and build queryset from all filter name / values return queryset