Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
use of select_related in this case of django rest?
I have a situation where I am not sure whether I would be using select_related or not. I have a model like this: class Example(models.Model): title = models.CharField(max_length=255, blank=True) message = models.TextField(blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_example", ) /................./ Now in my view I have use filtering logic like this: def get_queryset(self): search = self.request.query_params.get("search", None) if search_query is not None: queryset = Reactions.objects.filter( Q(user__name__icontains=search) | Q(user__email__icontains=search) ).distinct() Here Example model has a fk relation with User, so its a forward relation not a reverse relation. Should I be appeding .select_related('user').filter(...) in this above example to reduce the no of queries or there is no need here...I can't figure it out. -
Retrieve the distinct results with all columns fields in django model queryset
Query to be fetched from model Listingimages with distinct results. In my model featured_image expects multiple images as in form input attribute has multiple, but i need only one value from featured_image column with respective foreign key listingproducts_id. I am using the mysql DB. So please help me to solve the problem. My models looks as class Listingproducts(models.Model): title = models.CharField(max_length=200,null=True) price = models.IntegerField(null=True) descriptions = models.TextField(max_length=200,null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Listingimages(models.Model): listingproducts = models.ForeignKey(Listingproducts,on_delete=models.CASCADE, null=True) featured_image = models.ImageField(null=True, default='default.jpg') created = models.DateTimeField(auto_now_add=True,null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) images = Listingimages.objects.values('listingproducts').distinct() i tried in my view Above queryset returns only listingproducts column, Also i am not able to retrieve listingproducts column. -
Which correct folder and path to aditional js file
I'm trying to add a js file to specific ModelAdmin. In admin.py i have: ... class AdminProductImages(admin.TabularInline): class Media: js = ('users/js/img_produt_upload.js',) class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] ... settings.py ... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ... But with this set return 404 -
Django channels and file uploads
I'm learning Django on the fly so bear with me. My goal here is for a user to be able to upload a file, the server script process it and send the results on each iteration to the client live. My current structure is: User uploads a file (csv), this is read via views.py then renders the blank html view, JS in the html creates a new websocket, and well this is where I'm not able to pass data outside of consumers.py or process the data. I'm also not sure the structure of view > JS script > consumers > ? is the best route for processing files but I've not found much documentation on file uploads and channels. views.py from django.shortcuts import render import pandas as pd def someFunc(request): if request.method == "POST": global csvUpload csvUpload = pd.read_csv(request.FILES['filename']) return render(request, 'app/appPost.html') I render the view here first so that the blank page displays prior to the script running. appPost.html JS script var socket = new WebSocket('ws://localhost:8000/ws/app_ws/') socket.onmessage = function(event){ var data = JSON.parse(event.data); console.log(data); var para = document.createElement("P"); para.innerText = data.message; document.body.appendChild(para); } consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class WSConsumer(WebsocketConsumer): def connect(self): self.accept() self.render() async_to_sync(self.add_group)('appDel_updates_group') … -
Getting the product.id in my django slug product details
I'm having issues trying to get my product.id in my product_details templates. This is my views.py product_details def product_details(request, slug): data = cartData(request) cartItems = data['cartItems'] post = get_object_or_404(Product, slug=slug) context = { 'post': post, 'cartItems': cartItems, } return render(request, 'e_commerce/product_details.html', context) models.py class Product(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=200, unique=True, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) image = models.ImageField(upload_to='product_image', null=True, blank=True) digital = models.BooleanField(default=False,null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,default=1) description = models.CharField(max_length=250, default='', null=True, blank=True) size = models.CharField(max_length=200, null=True, blank=True, help_text='Input size of product') urls.py path('<slug:slug>/', views.product_details, name='product_details'),#e_commerce details page Then the product_details template: <div class="container"> <div class="card"> <div class="container-fliud"> <div class="wrapper row"> <div class="preview col-md-6"> <div class="preview-pic tab-content"> <div class="tab-pane active" id="pic-1"><img src="{{ post.image.url }}" /></div> </div> </div> <div class="details col-md-6"> <h3 class="product-title">{% block title %} {{ post.name }} {% endblock title %}</h3> <div class="rating"> <div class="stars"> </div> </div> <h5 class="product-description">{{post.description }}</h5> <h4 class="price">price: <span>NGN {{ post.price }}</span></h4> <h5 class="sizes">size: {{ post.size }}</h5> <h5 class="lead">Category: {{ post.category }}</h5> <hr> <button data-product=**{{product.id}}** data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> </div> </div> </div> </div> </div> Everything is working out fine and good except getting the product.id. I need it in order to consume the javascript function I created to … -
Django admin list filter using a model property
I have a model such as below: class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number = models.CharField(max_length=36, blank=True, null=True) external_number = models.CharField(default=None, blank=True, null=True, max_length=250) @property def is_external(self) -> bool: return self.external_number is not None And I register my model like below: @admin.register(Order) class OrderAdmin(ReadOnlyIDAdminClass): list_filter = ["number", "is_external"] list_display = ["id", "is_external"] But since is_external is not a db field, I get the following error: (admin.E116) The value of 'list_filter[1]' refers to 'is_external', which does not refer to a Field I have tried something like creating a custom filter: class IsExternal(admin.FieldListFilter): # Human-readable title which will be displayed in the # right admin sidebar just above the filter options. title = 'is external' # Parameter for the filter that will be used in the URL query. parameter_name = 'is_external' def lookups(self, request, model_admin): return ( ('True', True), ('False', False) ) def queryset(self, request, queryset): if self.value(): return queryset.filter(external_number__isnull=False) return queryset.filter(external_number__isnull=True) and then update my Admin: @admin.register(Order) class OrderAdmin(ReadOnlyIDAdminClass): list_filter = ["number", ("is_external", IsExternal)] list_display = ["id", "is_external"] But it raises: Order has no field named 'is_external' which I think makes sense, but is there anyway to do this? I feel like I am messing on … -
Self Teaching Django
What all topics should I learn if I am self Teaching Django ? I am thinking of learning from FREECODECAMP. Can anyone mention what all topics are must ? I appreciate if you can share links of videos which are beginner friendly and if you have any recommendations. -
How do I limit a django model's field choices using one of the previous fields?
The following is in my models.py: class SensorType(models.Model): hardware_type = models.CharField(max_length=100) is_static = models.BooleanField(default=False) # Some other fields class Sensor(models.Model): device_id = models.CharField(max_length=100, primary_key=True) sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # Some other fields class Asset(models.Model): name = models.CharField(max_length=100) sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # I need to use this field to filter below sensor = models.ForeignKey(Sensor, on_delete=models.PROTECT, limit_choices_to={'sensor_type': WHAT DO I PUT HERE?},) # Some other fields I need to limit the choices in the sensor field of asset so that only sensors with the sensor_type set in the field immediately above, show up. The reasoning behind this is that there will eventually be many sensors and it would be very useful to filter this. Initially I only need this to work from the admin page but this will eventually extend when I make my Create and Update Views. Is this even possible? I'm essentially trying to access attributes before the object has actually been created. After reading several other questions such as this one I have also looked into ModelChoiceField but the same issue exists of trying to access the form data before it has been submitted. I'm very open to changing the model structure if that is what is required. -
Django - Pass a file to a session in form_valid
I have the following code in views.py: class UploadFile(CreateView): form_class = UploadFileForm template_name = "tool/upload.html" success_url = reverse_lazy('tool:edit_columns') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['file'] = self.request.session['file'] return context def form_valid(self, form): form.instance.name = form.instance.file.name row_number = form.instance.header_row file = form.instance.file df = pd.read_csv(file) names = list(df.columns) return super().form_valid(form) And this code in forms.py: class UploadFileForm(forms.ModelForm): class Meta: model = CheckFile fields = ['file', 'header_row', ] I want to pass the file object and the columns names to the page edit_columns.html. I've been looking for infos and I think I have to use a session to pass the file object but with the code I tried, I have the following error: KeyError: 'file' Could you please help me? Thanks! -
Django: Is there a way to store request session in each tab
I have a use case with an admin who can access the user area when they click the link, it will open their area (user area is a separate app). Using jwt access admin logs in to user app. When doing that admin sessions gets expired. Is there a way to hold the admin session in the current tab when the user is opened on the new tab? -
Send current logged in user from Django backend to React frontend using axios
I am trying to send current logged in username from django backend to React frontend. I have created an endpoint currentuser/ that works perfectly fine in backend, it returns the expected result but when I call this api endpoint in React using axios,null value is returned there. Here's the code for backend #view.py from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.response import Response from rest_framework.views import APIView User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class LoggedInUserView(APIView): def get(self, request): serializer = UserSerializer(request.user) return Response(serializer.data) #urls.py urlpatterns = [ path('currentuser/', views.LoggedInUserView.as_view(), name='currentuser'), ] Here's the result when calling the api directly Here's the code for frontend class App extends React.Component { state = { users: [], } getUsers() { axios.defaults.headers.common['Content-Type'] = 'application/json'; axios.get(`http://localhost:8000/currentuser/`) .then(res => { console.log("res :", res); const user = res.data; console.log("response from backend", user); this.setState({ users: user }); console.log(this.state.users); }) .catch(err => { console.log("error:", err); }); console.log(this.state.users); } constructor(props) { super(props); this.getUsers(); } render() { return (.....) } }; export default App; Here's the result when calling the api from the frontend Any suggestions would be appreciated -
django navbar not across the top, showing top left box instead
when viewing my django app in the laptop it is showing the menu as expected acress the width of the screen but when trying to run that menu in the mobile it is shown as a small box on the top left of the screen. How to fix that? <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> </li> </ul> <div class="form-inline my-2 my-lg-0"> {% if user.is_authenticated %} so whay is that happening? how to fix that? Thanks. -
how to load a select widget with queryset data in django forms
I'm trying to load a dynamic select widget in my form with queryset data using the following code: forms.py class TransactionForm(forms.Form): # Payment methods payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) username = self.request.user.username self.get_mm_details = MMDetails.objects.filter(username=username) self.get_card_details = CardDetails.objects.filter(username=username) # add payment methods details to a dictionary for method in self.get_mm_details: entry = () entry += (method.method_name,) entry += (method.method_name,) self.payment_meth.append(entry) for method in self.get_card_details: entry = () entry += (method.method_name,) entry += (method.method_name,) self.payment_meth.append(entry) super(TransactionForm, self).__init__(*args, **kwargs) View.py form = TransactionForm(request=request) What can I do to make it work -
How to convert already exiting FBV to CBV in Django
everyone, happy year to you all! Please guys pardon me if this question seems easy for anyone. I just started learning Django last month. So, I'm pretty new to how to switch things together. I have created an FBV called article_view which actually works as expected. However, as I continue to learn I came to realize that CBV has the magic one that'll not only shorten my codebase but also comes with tons of methods that make me live longer :). So I decided converting my FBV to CBV will be the right to do also use that to practice my Django learning. So I created a CBV called ArticleView and added some context but for some reason, I can't seem to figure out how to fully replicate the FBV to CBV. Please I will greatly appreciate it if someone can help me with this. I have been struggling with this for almost a week trying to figure it out by myself and no luck. So I've come to the terms that I need some help. Funtion Based View: def article_view(request): articles = Article.objects.all().order_by('-published_on') this_page = request.GET.get("page", 1) pages = Paginator(articles, 5) try: page_obj = pages.page(this_page) except PageNotAnInteger: page_obj = … -
How to take requested data as json object in django views?
I'm submitting my form from postman. But i'm getting all key values as a list. I don't know why, how can i get key values without list. here is request.data i'm getting: {'from_email': ['dummyfirst54@gmail.com'], 'to_email': ['coolahmed21@gmail.com'], 'subject': ['hey man whats up ?'], 'html_body': [<InMemoryUploadedFile: email_test_template.html (text/html)>]} I'm expecting it to be like following. {'from_email': 'dummyfirst54@gmail.com', 'to_email': 'coolahmed21@gmail.com', 'subject': 'hey man whats up ?', 'html_body': <InMemoryUploadedFile: email_test_template.html (text/html)>} i'm requesting in a following way. -
My models are not getting displayed in html file
its showing blankspace for there value . i gave them value in admin panel admin.py models.py views.py index.html settings.py -
How to change the display format of datetime fields in the Django admin interface?
I already read in the django documentation that you have to change it in the settings and set USE_L10N to False. So i did it accordingly in settings.py: USE_L10N = False DATETIME_FORMAT = 'd.m.Y - H:i:s' USE_TZ = True USE_I18N = True TIME_ZONE = 'CET' LANGUAGE_CODE = 'en-us But my the datetime field of my objects are still displayed like this in the admin interface: 2022-01-18 15:00:56.421123+00:00 So why is the datetime still not displayed according to my settings.py, but like Y-m-d H:i:s.u? In my models.py i implemented __str__(self) like this: def __str__(self): return self.created my model: class My_model(models.Model): created = models.DateTimeField(auto_now_add=True) What am I missing here? -
Django: How to use an annotation from a parent queryset?
I have an Item class which can be annotated using a custom queryset add_is_favorite_for method: class ItemQuerySet(QuerySet): def add_is_favorite_for(self, user): """add a boolean to know if the item is favorited by the given user""" condition = Q(id__in=Item.objects.filter(favoriters=user).values("id")) return self.annotate(is_favorite=Condition(condition)) # True or False class Item(Model): objects = Manager.from_queryset(ItemQuerySet)() It works as expected. For example: >>> user = User.objects.get(id=1) >>> Item.objects.add_is_favorite_for(user) # each item has now a `is_favorite` field Now, I want to add a Factory Model and link Item Model to it this way: class Factory(Model): pass # ... class Item(Model): objects = Manager.from_queryset(ItemQuerySet)() advised_in = models.ForeignKey( Factory, on_delete=models.CASCADE, related_name="advised_items", ) I'd like to be able to return a Factory QuerySet, whose advised_items fields will all contain the is_favorite annotation too. I don't know how to do this, I saw no example of such a thing in the doc, maybe I missed it? -
why I am getting only one result only from the youtube api
I have a list of video ids as strings of different videos of youtube,but when I am fetching the data for all the video ids I am getting result for only last video. Here is my code : search_url = 'https://www.googleapis.com/youtube/v3/videos' parameter = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet', 'id' : ','.join(video_id) } data = requests.get(search_url,params=parameter) results = data.json()['items'] In the above code the video_id is a list containing video ids. I am getting a csv file which which has youtube video urls , and I am taking the video id from it and appending them in video_id list as: rows = [] video_id = [] file = request.FILES["file"].readlines() for f in file: rows.append((f.decode('utf-8'))) for row in rows[0:len(rows)-1]: video_id.append((row[-13:])) video_id.append((rows[len(rows)-1][-11:])) The complete code is : def home(request): if request.method == 'POST': rows = [] video_id = [] file = request.FILES["file"].readlines() for f in file: rows.append((f.decode('utf-8'))) for row in rows[0:len(rows)-1]: video_id.append((row[-13:])) video_id.append((rows[len(rows)-1][-11:])) print(len(video_id)) for v in video_id: print(v) search_url = 'https://www.googleapis.com/youtube/v3/videos' parameter = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet', 'id' : ','.join(video_id) } data = requests.get(search_url,params=parameter) results = data.json()['items'] channel_list = [] for result in results: data = { 'channel_name' : result['snippet']['channelTitle'] } channel_list.append(data) for list in channel_list: print(list) … -
Django Firebase Gmail Authentication
i'm creating a web app with django and i'm using firebase. i can authanticate with an e-mail and i can see my users on firebase console. i'm using firebase-admin for authantication and database operations. its working correctly. but i want to add gmail auth on my app. i added gmail authentication but its working with django-retsframework and i can see my gmail users in django admin panel. there is a problem, i cant use django rest framework here. i have to use only firebase. and i couldn't add my gmail users on firebase i have some ideas but i'm not sure for they are safe. as you know i can see credentials gmail users and i can take email and ID fields, and create one firebase auth. as i said i'm not sure this is safe. if this idea is not safe how can i save my gmail users with credentials like e-mail users ?? -
Djnago make an inner join using another inner join
How could I make inner joins in tables that share same FK. here is an example of some models: models.py class Property(models.Model): name = models.CharField(blank=True, max_length=1024) address = models.ForeignKey(Address, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) ... class Address(models.Model): country = models.CharField(blank=True, max_length=1024) state = models.CharField(blank=True, max_length=1024) ... class Category(models.Model): code = models.CharField(blank=True, max_length=1024) location = models.CharField(blank=True, max_length=1024) ... class Reservation(models.Model): check_in = models.DateField(blank=True, null=True) check_out = models.DateField(blank=True, null=True) property = models.ForeignKey(Property, on_delete=models.CASCADE) class Category_month_price(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) month = models.PositiveSmallIntegerField(blank=True, null=True) i'd like to create a view for category_month_price with all properties with same category_id and check if they don't have any check_in or check_out in a range period. Can i achieve this using inner joins with queryset.select_related? if yes, how could i do that? -
What method can I use to develop session control using Django?
Currently in the company I have developed about six applications with Django, these applications are managed in different databases since they are focused on different departments. They are asking me that access to these applications be done through a single credential, that is, if a user must handle two applications, they should not have two different access credentials, but rather they can access both applications with a single credential. I have consulted various sources, one person recommended me to develop an application that is only responsible for access, but I am a bit disoriented with this problem. I appreciate the help! -
why can't I import my models in Python shell?
I don't even know what this is. Works fine when I runserver. But I get an Error when trying to import in the Python Shell. My app is called auctions and my models.py (using AbstractUser) file is: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, blank=True) image = models.ImageField(upload_to="portraits", blank=True, default="default.jpg") def __str__(self): return f"{self.username}" class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) def __str__(self): return f"{self.name}" class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inventory") name = models.CharField(max_length=64) description = models.CharField(max_length=255) image = models.ImageField(blank=True, default="Megamind.jpg") starting_bid = models.PositiveIntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="1", related_name="stuff") active = models.BooleanField(default=True) favorited = models.ManyToManyField(User, blank=True, related_name="favorites") def __str__(self): return f"{self.name} of {self.owner}" -
Django: Uploading Avatar Imagefile to media-Folder of Custom User Profile is not working
I'm currently trying to create a Custom User Model for being able to add a Avatar-Imagefield to ever User. Therefore I've created a Model Profile with avatars as the directory (media/avatars/) for all Images: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('Avatar', upload_to="avatars", default="avatars/profil_picture_icon.png") I created the needed classes ProfileInline and UserAdmin: class ProfileInline(admin.StackedInline): model = Profile can_delete = False class UserAdmin(BaseUserAdmin): inlines = (ProfileInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) I also defined the media-directory inside the settings: MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' After that, I created a Form ProfileForm, where the User can upload the Image and a postsavereceiver to create a basic Profile-Model every time I'm creating a new User: class ProfileForm(forms.ModelForm): class Meta: model = models.Profile exclude = ('user',) def post_save_receiver(sender, instance, created, **kwargs): if created: user_profile = models.Profile(user=instance) user_profile.save() post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL) Inside my Template I then created a form with the Avatar-ImageField and a Save-Button to Upload that Image: <form action="/profil/" method="post" id="avatar_form"> {% csrf_token %} <img style="border-radius: 100px" id= "Profil_Image" src=" {{ user.profile.avatar.url }}"> {% load widget_tweaks %} {{ profile_form.avatar|add_class:"profile_form" }} <button id="update_button" style="left: 1210px; top: 385px" type="submit" form="avatar_form" name="avatar_update_btn" value="">Speichern</button> </form> Lastly inside my views.py the User can Update the Default-Image elif … -
Pass Context from serializer to serialzier
How can i pass context from 1 serializer to another like sub_variant = SubVariantSerializer( source='subvariant_set', many=True, context={"variant_id": ?} # i want to pass variant_id here ) I know serializer.SerializerMethodField() but dont want to use it here. Please suggest is it possible to send context serializer to serializer in below code? or how can i pass variant_id in further serializer MY CODE: # MODELS class Variant(models.Model): variant_id = models.AutoField(primary_key=True) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) class SubVariant(models.Model): sub_variant_id = models.AutoField(primary_key=True) variant_id = models.ManyToManyField(Variant) sub_variant_name = models.CharField(max_length=100) # SERIALZIER class SubVariantSerializer(serializers.ModelSerializer): new_field = serializer.SerializerMethodField() class Meta: model = SubVariant fields = "__all__" def get_new_field(self, obj): print(self.context['variant_id']) return self.context['variant_id'] class VariantServiceSerializer(serializers.ModelSerializer): sub_variant = SubVariantSerializer( source='subvariant_set', many=True, context={ "variant_id": ?? variant_id ?? }) class Meta: model = Variant fields = "__all__"