Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting data from related tables using Django ORM
Using the Django ORM, how does one access data from related tables without effectively making a separate call for each record (or redundantly denormalizing data to make it more easily accessible)? Say I have 3 Models: class Tournament(models.Model): name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Team(models.Model): name = models.CharField(max_length=250) coach_name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Player(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING ) number = models.PositiveIntegerField() age = models.PositiveIntegerField() active = models.BooleanField(null=True,default=1) Note that this Player model is important in the application as it's a major connection to most of the models - from registration to teams to stats to results to prizes. But this Player model doesn't actually contain the person's name as the model contains a user field which is the foreign key to a custom AUTH_USER_MODEL ('user') model which contains first/last name information. This allows the player to log in to the application and perform certain actions. In addition to these base models, say that since a player can play on different teams in different tournaments, I also have a connecting ManyToMany model: class PlayerToTeam(models.Model): player = models.ForeignKey( Player, on_delete=models.DO_NOTHING ) team = models.ForeignKey( Team, on_delete=models.DO_NOTHING ) tournament = models.ForeignKey( Tournament, on_delete=models.DO_NOTHING ) As an example of … -
Using Validators in Django not working properly
I have recently learning about Validators and how they work but I am trying to add a function to my blog project to raise an error when a bad word is used. I have a list of bad words in a txt and added the code to be in the models.py the problem is that nothing is blocked for some reason I am not sure of. Here is the models.py def validate_comment_text(text): with open("badwords.txt") as f: CENSORED_WORDS = f.readlines() words = set(re.sub("[^\w]", " ", text).split()) if any(censored_word in words for censored_word in CENSORED_WORDS): raise ValidationError(f"{censored_word} is censored!") class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) -
Updating and Deleting Comments for Posts in Django
I have added a Comment system to posts in a Blog Project and I am trying to add an option to update and delete the comments by the users. I am trying to use the same concept as creating a Post and building a Class Based Views for these comments, creating a commment is working fine and it is appearing correctly, the only obstacle I am facing is the slug, when a user clicks on update or delete it is showing an error Cannot resolve keyword 'slug' into the field. Choices are content, created, id, post, post_id, updated, user, user_id which makes sense since there is no Slug in the comment Model. My question is how do refer back to the same page post.slug in the template without getting this error Here is the models.py class Post(models.Model): slug = models.SlugField(blank=True, null=True, max_length=120) ------------------------------------------------------------ class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', … -
Django pagination python dictionary
I hope you well. I’m developing a web using python and Django. I will love to paginate my dictionary “image_set_list” in order to see one element in one page, I mean, one element per page. The problem is that when I get the page, the result is None and pagination is not working. This is my view.py from django.shortcuts import render from django.http import HttpResponse import json from pathlib import Path import os from django.core.paginator import Paginator def detection_detail(request): # data planogram, bounding_boxes with open('detection/data.json', 'r') as json_file: data = json.load(json_file) # data image planogram image_name_location = data['image'] image_planogram = os.path.basename(image_name_location) # data product images with open('detection/data_product_images.json', 'r') as json_file: data_product_images = json.load(json_file) data_product_image = {x["id"]: x for x in data_product_images} images_reference = [] list_images = [] for product in data['bounding_boxes']: product_id = product['class'] product_ids = product['class_list'] image_p = data_product_image[product_id]["image_file"] image_p_list = [data_product_image[id]["image_file"] for id in product_ids] images_reference.append(image_p) list_images.append(image_p_list) image_set_list = {images_reference: list_images for images_reference, list_images in zip(images_reference, list_images)} #PAGINATION!! paginator = Paginator(image_set_list , 1) page = request.GET.get('page') print('page', page) #result is -> None set = paginator.get_page(page) context = { 'list_images': list_images, 'images_reference': images_reference, 'image_planogram': image_planogram, 'image_set_list': image_set_list, 'image_p_list': image_p_list, 'set': set} return render(request, "detection/detection_detail.html", context) And this is my … -
django how to use range inside of kwargs
I am trying to filter my queryset between two dates and I can't seem to figure out why this isn't working. Here is my code kwargs = { '{0}__{1}'.format(arg1, 'exact'): arg2, '{0}__{1}'.format('deleted', 'isnull'): True, '{0}__{1}'.format('event_date', 'range'): {date1, date2} } table = GeTable(Ge.objects.filter(**kwargs)) I want to be able to filter my queryset to only records between date1 and date2. Can someone point me in the right direction? -
Defining GOOGLE_APPLICATION_CREDENTIALS on elasticbeanstalk env breaks S3 connection
I have a django app deployed using elasticbeanstalk. I installed firebase admin sdk which requires GOOGLE_APPLICATION_CREDENTIALS field to be filled with path to credential. The problem is that right after I define GOOGLE_APPLICATION_CREDENTIALS on elasticbeanstalk console, Django's connection to S3 all breaks. What is happening and how to fix this? -
Page not found (404) Request Method:
please help me. I don't know why can't see the detail of product when i click a product. both first list work good just when i need to see detail of product in second list(filtered list) an 404 error shows. thanks here is my code below: my urls: from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('categories/<category>/', views.ProductListView.as_view(), name='product-list'), path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'), ] views: from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.views import generic from .models import Category, Product class HomeView(generic.ListView): model = Category template_name = 'home.html' class ProductListView(generic.ListView): template_name = 'product_list.html' def get_queryset(self): self.category = get_object_or_404(Category, title=self.kwargs['category']) return Product.objects.filter(category=self.category) class ProductDetailView(generic.DetailView): model = Product template_name = 'product_detail.html' product_list.html {% extends 'base.html' %} {% load static %} {% block title %} Welcome | Global Market {% endblock %} {% block content %} {% for product in product_list %} <a href="{% url 'shop:product-detail' product.pk %}"> <div class="card bg-light mb-3" style="max-width: 18rem;"> <div class="card-header">{{ product.title }}</div> <img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}"> <div class="card-body"> <p class="card-text">{{ product.description }}</p> </div> </div> </a> {% endfor %} {% endblock %} product_detail.html {% extends 'base.html' %} {% load static %} {% block title %} Welcome … -
Django - use middleware to block debug data on some cases
I'm using Django in debug mode in dev environment. When some views fail, it returns the debug page (not debug_toolbar, just the page with list of installed apps, environment variables, stack trace, ...) In my middleware, I have some cases (specific URLs, specific users, ...) where I want to remove this data and just return the raw response. How should I do that? currently my best idea is to just: response.data = {} return response But I'm not sure if it's the proper way to do that, whether it covers all cases and so on. I just want to use a middleware to control in some cases and avoid the DEBUG mode for them. -
Right Approach to Schedule a job in Django/Python
If you have built an application using Django 3 and MySQL 8. How would you schedule a job with "Right Approach" and why? I am guessing by using the inbuilt sched module. What are the merits and demerits of using sched, cron and APScheduler? -
Django Accessing Parent Data in templates from child data
So I've been search and trying to solve this question for hours and hours and I cant' seem to find an answer. I have 2 different models flights and Destinations. The Destination is the Parent model, A flight can only have one destination but the Destination can have many flights (one to many relationship). I would like to access this parent model on the details page of of the flight model. This details page is generated via the url routing and the slug of the flight. Here is what I have for the for the models, views and templates. models: class Flight(models.Model): title = models.CharField( null=True, max_length=60, blank=True) slug = models.SlugField(max_length=100, null=True, blank=True) flight_destination = models.ForeignKey(Destination, null=True, blank=True, on_delete=models.SET_NULL) class Destination(models.Model): title = models.CharField( null=True, max_length=60, blank=True) featuredimage = models.ImageField(null=True, blank=True, upload_to ='media/') slug = models.SlugField(max_length=100, null=True, blank=True) Each of these classes has an id for its primary key and I've connected all my flights to the correct destination. Here is what I have for my view. def flight_detail(request, slug): return render(request,"flight/detail.html",context= {'flight': Flight.objects.get(slug=slug), 'destination': Destination.objects.filter(id= Flight.objects.get(slug=slug).flight_destination_id)}) Here is the template but it which doesn't throw an error but it displays nothing <h3 class="pb-3"> {{ destination.title }} </h3> I feel … -
How do I properly use javascript axios .get() function to call get_queryset() function in Django viewset?
I followed a youtube guide to implement a React/Redux frontend that uses javascript axios to make requests to a Django REST framework backend. I've been adding a lot of my own work to it. Here is the original github repository if you think you need it to answer my question, although you shouldn't: Link To Github I have a new method I use to get what I call eventdefinitions. Sometimes I want all of the eventdefinitions that are in the database, but sometimes I only want some of them. In the original guide, the only way I was taught to get data, was to get all of the data, and so to get all eventdefinitions, I would do the following: In javascript, I use the following method which implements axios: // GET EVENT DEFINITIONS export const getEventDefinitions = () => (dispatch, getState) => { axios .get("/api/eventdefinitions/", tokenConfig(getState)) .then((res) => { dispatch({ type: GET_EVENTDEFINITIONS, payload: res.data, }); }) .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)) ); }; In my urls.py file I set up the url_patterns for the /api/eventdefinitions/ url: from rest_framework import routers from .api import ... EventDefinitionViewSet, ... router = routers.DefaultRouter() ... router.register('api/eventdefinitions', EventDefinitionViewSet, 'eventdefinitions') ... urlpatterns = router.urls The EventDefinitionViewSet in … -
Django add dataframe as Excel file inside model
Django I have multiple dataframes And I want to add download links in html to down load those dataframes as Excel files -
Cannot pass variables between javascript function and ajax in django project
This is a proper noob question it would seem, so apologies, but I can't seem to solve it so I'm reaching out for some assistance. I have a function in my .js file that interacts with the Google Places library to autocomplete a field in a form. I then have an ajax function that runs when you click the submit button which creates variables in the django session. The data of interest to me is lat and long. However, for some reason, I can't seem to get the data to pass from one to the other. I know the ajax function is working because if I type in fixed values they propagate through to django, but I can't seem to get it to update dynamically. const csrf = document.getElementsByName('csrfmiddlewaretoken'); var lat; var lng; function autocomplete_location() { let defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(49.6331, -11.7247), new google.maps.LatLng(59.4850, 1.5906)); let input = document.getElementById('id_your_location'); let options = { bounds: defaultBounds, types: ["address"], fields: ["name", "geometry"], }; let autocomplete = new google.maps.places.Autocomplete(input, options); autocomplete.addListener('place_changed', function() { // Get place info let place = autocomplete.getPlace(); // Do whatever with the value! lat = place.geometry.location.lat() lng = place.geometry.location.lng() console.log(lat) console.log(lng) }) } $(document).ready(function (){ $(".btn").click(function (){ … -
Django q update an already scheduled task
I am using Django-q to schedule a task at a specified date in an object (lets call this bell). I am successfully able to do so using schedule_obj = schedule(func_name, arg1, arg2, arg3, schedule_type=Schedule.ONCE, next_run=bell.date) when there is an update to the obj bell that holds the date, I want to modify this schedule obj with the updated date (bell.date). Is there a way to check if there is a schedule pending for this specific func_name with the args and then access it to modify it? -
How can I get userprofile randomly and add condition?
Here i am trying to get 3 random users and adding them in request user followers, But with the following code , That is getting three users useprofiles randomly including those who already following that profile, i just want to replace those users profiles with those users who don't following request.user so i can add them. #return the count of users who is not following request user all_profiles = UserProfile.objects.all() user_followers = request.user.is_following.all() pk_range = 0 for profile in all_profiles: if not profile in user_followers: pk_range +=1 print(pk_range,) if pk_range >= 3: k1, k2 ,k3 = sample(range(pk_range), 3) f1 = UserProfile.objects.all()[k1] f2 = UserProfile.objects.all()[k2] f3 = UserProfile.objects.all()[k3] userprofile = request.user.userprofile user= request.user user.is_following.add(f1, f2, f3) user.save() if more information or code is require than tell me in a comment session. I will update my question with that information. -
Why is my loop terminating before all items are looped through?
So I'm using Django and trying to dynamically add a users gists to the page using githubs embedded gists. this is the loop {% for i in snippets %} <div class="tile is-4"> <div style="height:25vh;"><script src="https://gist.github.com/{{i.owner.login}}/{{i.id}}.js"/></div> </div> {% endfor %} the list im looping through contains two items, however only the first is added. if I do something along these lines however it correctly displays the two different id's {% for i in snippets %} {{i.id}} {% endfor %} I read that the github script calls document.write(), I have a gut feeling this is where my issue lies. would document.write() break my loop? -
how can i fetch data without refresh page with javascript & django?
i am using django to make API and get data with javasctipt. first time i'm using javascript i don't have very good understanding with javasctipt. i want to get data without refreshing page i am using javacript to fetch data form API. my code is getting data from databse only when i refresh the page. is there way to get data without refreshing page? when anybody create new post then page automatically load the post in index page without refresh the page? index.html <script> async function getPosts() { const Url = 'http://localhost:8000/api/' const Story = document.getElementById('stories') await fetch(Url) .then((res) => res.json()) .then((data) => { data.map((post, index) => { document.getElementById('stories').innerHTML += ` <div class="card card-body mb-3"> <h3>${post.title}</h3> </div> `; }); }) .catch((err) => console.log(err)) } getPosts(); </script> -
AssertionError Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I want to create a comment api but I get this error: AssertionError at /comment/add/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> this is my view: @api_view() def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) return comment and this is url: path('comment/add/', views.AddComent, name='add_comment'), -
Passing varibles from API to template in Django
I am working on building a flight price search website as part of a project and have managed to get most of the functionality I require working. Here's what the front-end looks like so far: When users enter in the details, a POST request is sent to an API. API: https://developers.amadeus.com/self-service/category/air/api-doc/flight-offers-search API Python SDK: https://github.com/amadeus4dev/amadeus-python I'm receiving a response from the API; however, am struggling to understand what I should then do with the information received. The next step is to pass the information from the API into a search results template and split out all of the received flight information, similar to how it is displayed on Sky Scanner: Below is what I have in my views.py so far (currently passing in the whole response, in what I believe is JSON format?) Views.py: def flight_search(request): kwargs = {'originLocationCode': request.POST.get('Origincity'), 'destinationLocationCode': request.POST.get('Destinationcity'), 'departureDate': request.POST.get('Departuredate'), 'returnDate': request.POST.get('Returndate'), 'adults': '1'} try: response = amadeus.shopping.flight_offers_search.get( **kwargs) print(response.data) return render(request, "flightfinder/flight_search.html", { "response": response }) except ResponseError as error: raise error Here is an example response from the API: { "meta": { "count": 2 }, "data": [ { "type": "flight-offer", "id": "1", "source": "GDS", "instantTicketingRequired": false, "nonHomogeneous": false, "oneWay": false, "lastTicketingDate": "2020-11-20", "numberOfBookableSeats": 2, … -
Got AttributeError when attempting to get a value for field `phone` on serializer `UserSerializer`
im trying to create a view to update the extended profile data in one request, using the auth_rest library, but i got this error: Got AttributeError when attempting to get a value for field phone on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'userprofile'. This is my models (UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) phone_whatsapp = models.BooleanField(default=False) def __str__(self): return self.user.username This is the serializer: class UserSerializer(UserDetailsSerializer): phone = serializers.CharField(source="userprofile.phone") phone_whatsapp = serializers.BooleanField(source="userprofile.phone_whatsapp") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('phone','phone_whatsapp',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) phone = profile_data.get('phone') phone_whatsapp = profile_data.get('phone_whatsapp') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and phone and phone_whatsapp: profile.phone = phone profile.phone_whatsapp = phone_whatsapp profile.save() return instance i modified some things, but i dont be able to fix it. anyone can helpme? thanks in advance -
How can I update the email address using the confirmation code in Django?
I use all the functionalities of dj-rest-auth to register, log in, confirm the email address, change the password, reset the password and many more. Unfortunately, the library does not support changing the email address. I would like the authenticated user to first enter the account password and the new email address. After the successful process of authentication, I would like to send the user a specially generated confirmation code. Only when he enters it, the old email address will be changed to the new one. As far as I know, there is no such functionality in dj-rest-auth. Unfortunately, I also have not found any current solutions or libraries for this purpose anywhere. Has anyone had a similar problem and could share solution here? Thank you in advance. -
How to iterate through all foreign keys pointed at an object in Django without using _set notation?
I am fairly new to Django, but I am working on an application that will follow a CPQ flow or Configure, Price, Quote. The user should select the product they would like to configure as well as the options to go with it. Once selected, the program should query an external pricing database to calculate price. From there the program should output the pricing & text data onto a PDF quote. I was able to get the application working using the specific product inheriting from a base product class. The issue is now that I've created a second product child class, I cannot use a singular "related_name". I've omitted the lists associated with the drop down fields to help with readability, but I've posted my models.py file below. Is there a way I can iterate through Product objects that are pointing to a Quote object with a foreign key? A lot of answers I've found on SO relating to this were able to be solved either by specifying the "_set" or "related_name". I've seen other answers use the select_related() method, however, I can't seem to get the query right as the program won't know which set it needs to look … -
Web Client to Display and Read from SFTP Server in Django Admin
What am I trying to do? I want to allow the user to configure an SFTP server and select the folders that should be downloaded. Following is how I the admin form to look like: Allow the user to configure an SFTP server (host, port, user, pass) from the Django admin On the same page, provide a connect button, which when clicked would connect to the SFTP server using the configuration (Step 1) and open up the SFTP server (either as a modal popup or in a new browser tab/window) The user selects the folders that should be included for parsing and save the admin form. Step 1 is fairly straightforward. However, I am unable to figure out if there's a preexisting module that I use to accomplish step 2 and 3. Basically what I am looking for is a Web SFTP client that I can integrate into my Django admin. I am looking for some guidance in order to achieve this setup. -
Rendering MPTT structure with open/close possibility in django template
I need to render my MPTT model as tree with dropdown (open/close every node that contains children) possibility and buttons that will open/close all the nodes in that tree in 1 click. I tried to find some ready-to-use examples, but best that I found is this: <ul class="navbar-nav mr-auto"> {% recursetree thecategories %} {% if node.level == 0 %} {% if not node.is_leaf_node %} <!-- Let op: <li> tag wordt steeds onderaan aangevuld, ander werkt het niet...--> <li class="dropdown nav-item"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="mainBarItem">{{ node.ctg_Title }}<span class="caret"></span> </span></a> {% else %} <li><a href="#" class="mainBarItem">{{ node.ctg_Title }}</a> {% endif %} {% else %} {% if not node.is_leaf_node %} <li class="dropdown-submenu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="nav-label">{{ node.ctg_Title }}<span class="caret"></span></span></a> {% else %} <li><a href="#">{{ node.ctg_Title }}</a> {% endif %} {% endif %} {% if not node.is_leaf_node %} <ul class="children dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> with some CSS and JS, but it is not that I need. Actually I need to render just one tree at a time. I'm passing variable {{ product }} in my template that is just a root node. And for now … -
How to create json response from django orm annotate?
I want to create sales per month report and send it to the frontend. here is my serializers.py: from .models import Sale from rest_framework import serializers class SaleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sale fields = ['url', 'id', 'date', 'sku', 'product', 'quantity', 'price'] Here is the view from views.py: from django.db.models import Sum from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import SaleSerializer from .models import Sale @api_view() def monthly_sales(request): monthly_sales = Sale.objects.values( 'date__month').annotate(Sum('price')) serializer = SaleSerializer( monthly_sales, many=True, context={'request': request}) return Response(serializer.data) When I go to browser I get the Attribute error: 'dict' object has no attribute 'pk' What's the solution?