Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
set default image on model from s3 bucket
For user profiles i have a default image on the model image = models.ImageField(default='default.jpg', upload_to='profile_pics') I now have this image in the s3 bucket. How can I reference this image from the s3 bucket and not local if I try and use the direct image path on the model https://uploadfiles.s3.amazonaws.com/profile_pics/default.jpg or the bucket path 'uploadfiles/profile_pics/default.jpg i get the error This backend doesn't support absolute paths I'm not sure how else I would reference the image I do have proper access to the buckets and uploading is working properly -
How to merge more than one queryset in django
I'd like to merge more than one queryset and keep a common column called "line_nm" I have created some queryset with a formula, for: day, week and year models.py class PbaSetOperator(models.Model): work_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) prodc_qty = models.IntegerField(blank=True, null=True) work_mh = models.FloatField(blank=True, null=True) in_house = models.FloatField(blank=True, null=True) reduction = models.FloatField(blank=True, null=True) views.py set_operator_today = set_operator.filter(work_ymd = date).values('line_nm').order_by('line_nm').annotate( set_operator_today_value=(480 * (Sum('in_house') / Sum('work_mh')) set_operator_week = set_operator.filter(work_ymd__range = (getWeekStart(), getWeekEnd())).values('line_nm').order_by('line_nm').annotate( set_operator_week_value=(480 * (Sum('in_house') / Sum('work_mh')) set_operator_year = set_operator.filter(work_ymd__range = (getYearStart(), geYearEnd())).values('line_nm').order_by('line_nm').annotate( set_operator_year_value=(480 * (Sum('in_house') / Sum('work_mh')) The expected result is a queryset like bellow: 'line_nm':01, 'set_operator_today_value':100, 'set_operator_week_value':110, 'set_operator_year':115 How can I do it? I have tried the chain method of itertools and convert to a list, however without success. There is a common column called "line_nm" and I want to use it like a left join. -
How to modify unchanged model admin inlines?
Kind of duplicate of both of these: How to force-save an "empty"/unchanged django admin inline? How to force creation of unchanged django admin inline object in django 1.9 But I am still wondering is there any better way to do it in any later Django updates? I aimed to modify my model admin stacked inline objects (pre or post save doesn't matter) when parent model admin instance is changed. I tried overriding save_formset and save_related in model admin class as written in Django docs here and here using commit=False. For example: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.any_field = "value" instance.save() The method formset.save(commit=False) returns inline form instances only if they are changed on Django Admin panel as mentioned in django docs, but it doesn't return list of inline objects if they are not changed, even after sending commit=False. I need to edit those inline objects regardless if they were changed on admin panel or not. -
Django how to stop BackgroundScheduler when application stops
I'm currently running a scheduled task with BackgroundScheduler, it works fine but when a finish the app execution with Ctrl+C for example, the job is still present in django_apscheduler_djangojob table, so any time further that I run the application the previous job will start again and a new one will be launched either, resulting in duplicates. def start(): scheduler = BackgroundScheduler(timezone='America/Sao_Paulo') scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job(telemetry.requestData, 'interval', minutes=1, name='requestData', jobstore='default') register_events(scheduler) scheduler.start() -
Django ASO booking system
Hey i have a problem about make proper booking system in my ASO sercvice. I wanna that when customer fill a form to make reservation can see the nearest available days. I tried to making somethink in init of this form but cant undestand how to refer to calendar queryset. Someone could give me some tips or code how to handle this issue? -
Django relation views not showing checklists that belong to each task
I want to display under each task, each checlists that belong to the given task My models class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() due_date = models.DateTimeField() teams = models.ForeignKey(Team, blank=True, null=True, on_delete=CASCADE) tasks = models.ManyToManyField("Task", blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task(self): return self.tasks.count() @property def num_task_completed(self): return self.tasks.filter(task_completed = True).count() class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def __str__(self): return self.title def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) task = models.ForeignKey(Task, blank=True, null=True, related_name='tasks', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def return_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title and in my view where … -
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) …