Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make this serializer (python django) to convert comments under a post to Json data
from .models import User, Post, Project, Comment, Version, Tag from rest_framework import serializers import bcrypt from .models import Stock class PostSerializer(serializers.ModelSerializer) class Meta: model = posts fields = 'all' def create(self, validated_data): I cant figure out how to make it convert the data -
Django CSRF Token not validated despite inheriting Generic View and CSRF middleware
I have a POST request on a DRF view that inherits generics.CreateAPIView and CSRF enabled in middleware, but despite that it doesn't validate my CSRF token, I am not sure why not ? Here's my View: class SchemeView(generics.CreateAPIView): queryset = SchemeModel.objects.get_queryset() serializer_class = SchemeModelGraphSerializer def post(self, request, *args, **kwargs): try: ----Business Logic Code ----- return Response(result, status=status.HTTP_200_OK) except Exception as e: return Response("Error: %s" % (e), status=status.HTTP_400_BAD_REQUEST) Middleware: MIDDLEWARE = { 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', 'RMS.middleware.AuthTokenMiddleware' } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'RMS.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } CSRF Settings: CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = True Using React for FE, Django for BE, CSRF Cookies does get sent along with request to Django server. I tried changing CSRF cookie value, but Django silently ignores it. Note: Some had suggested that along with Token auth, CSRF isn't needed. But I don't understand the reason why ? Also, not using CSRF with Token Auth, doesn't provide a solution to Django ignoring CSRF validation. I am more curious as why doesn't it get validated ? -
How to fetch a query/mutation to graphene-django API from JavaScript?
I am trying to make a mutation when the user submits a form, but I always get a 400 err. The weird thing is that I used the GraphiQL interface to check how do they do the fetch function, and in the end, they use the exact same headers, method, body, and credentials. So I really don't know how to do it. This is the mutation: const mutation = ` mutation { createCompetitors(comp1: ${comp_1}, comp2: ${comp_2}) { comp1 { id name } comp2 { id name } } } `; fetch('/graphql/#', { method: 'POST', headers: { "Accept": 'application/json', "Content-Type": 'application/json', "X-CSRFToken": getCookie('csrftoken') }, body: JSON.stringify({ query: mutation }), credentials: 'include', }) .then(response => { if (!response.ok) { throw Error(`${response.statusText} - ${response.url}`); } return response.json(); }) .then(result => { console.log(result) }) .catch(err => { if (err.stack === 'TypeError: Failed to fetch') { err = 'Hubo un error en el proceso, intenta más tarde.' } useModal('Error', err); }) I get a 400 error that just says: Failed to load resource: the server responded with a status of 400 (Bad Request), and the Django output says: Bad Request: /graphql/ [07/Feb/2021 12:51:44] "POST /graphql/ HTTP/1.1" 400 294 But that is not it. After this, … -
Django: How to create a abstract field?
I would like to start using an abstract model for my application (based on a django-accounting app). How should I create my field on the views.py. I guess I will also need to change my view file when creating a new field...Can I still create the same way I used to if it was not an abstract model? views.py @login_required(login_url="/login/") def create_bill(request): form = BillForm(request.POST or None, request.FILES or None) if form.is_valid(): bill = form.save(commit=False) bill.save() return render(request, 'accounting/bills/detail.html', {'bill': bill}) context = { "form": form, } return render(request, 'accounting/bills/create_bill.html', context) @login_required(login_url="/login/") def detail_bill(request, bill_id): user = request.user bill = get_object_or_404(Bill, pk=bill_id) return render(request, 'accounting/bills/detail.html', {'bill': bill, 'user': user}) @login_required(login_url="/login/") def bill_update(request, bill_id): bill = get_object_or_404(Bill, pk=bill_id) form = BillForm(request.POST or None, instance=bill) if form.is_valid(): form.save() return render(request, 'accounting/bills/index_table.html', {'bill': bill}) else: form = BillForm(instance=bill) return render(request, 'accounting/bills/edit.html', {'form': form}) models.py class AbstractSale(CheckingModelMixin, models.Model): number = models.IntegerField(default=1,db_index=True) # Total price needs to be stored with and wihtout taxes # because the tax percentage can vary depending on the associated lines total_incl_tax = models.DecimalField("Total (inc. tax)",decimal_places=2,max_digits=12,default=D('0')) total_excl_tax = models.DecimalField("Total (excl. tax)",decimal_places=2,max_digits=12,default=D('0')) # tracking date_issued = models.DateField(default=date.today) date_dued = models.DateField("Due date",blank=True, null=True,help_text="The date when the total amount ""should have been collected") date_paid … -
Django Ajax Like Section not working in Docker
I am trying to create dynamic like functionality in Django. But it shows following error: Not Found: /blogs/why-do-we-use-it/{% url "like_post" %} Here is my urls.py: urlpatterns = [ path('', PostListView.as_view(), name='post-list'), path('like/', like_post, name='like_post'), path('<slug:slug>/', post_detail, name='post-detail'), ] models.py: likes = models.ManyToManyField(get_user_model(), blank=True, related_name='likes') views.py: def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('blogs/like_section.html', context, request=request) return JsonResponse({'form': html}) post_detail.html: <div id="like-section"> {% include 'blogs/like_section.html' %} </div> like_section.html: {{ total_likes }} Like{{ total_likes|pluralize }} {% if request.user.is_authenticated %} <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> {% endif %} In console logs: The current path, <code>blogs/why-do-we-use-it/{% url &quot;like_post&quot; %}</code>, didn't match any of these. I couldn't find a way how it done. Thanks in advance. -
Background workers and overriding save method on Django models
I have a long-running process that depends on model fields. Let's say I have a model that looks like this class Client(models.Model): input_data = models.CharField(max_length=100) # The field that will be computed in the background task computed_data = models.CharField(max_length=100, null=True, blank=True) I want to trigger a background task every time this model is updated, but the problem is I also need to call the save method after the background task updates the instance. It's roughly looking something like this. def a_long_running_background_task(instance): input_data = instance.input_data # Reading the model input data # Updating the output_data field using the input data from the model instance instance.output_data = input_data.title() # To make sure the changes apply to the database we need to call the save method instance.save() The problem with this code is that it would cause an infinite loop, because I'm calling the background task on the save method, and I'm calling the save method in the background task. And I kept getting this error RecursionError: maximum recursion depth exceeded while calling a Python object After I researched this problem, I found a solution which suggests using the post_save signal, with the created attribute, and then would check if the instance is … -
How to raise error for email field if user is trying to pass just few letters
How can I rise the error and information, if user is puting only "dummy date" without "@"? Email model is email = models.EmailField(max_length=254) but is only preventing passsing empty field, and nothing else. Can someone advice ? def addContact(request): form = ContactForm if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('/contact') context = {'form': form} return render(request, 'contact/new.html', context) -
Django how to control format of input html content
When I copy some content for example a news, from other website into my django website.I copy the whole html which contains the content into my django admin,not only the text content. And in my template I use: {% autoescape off %} {{news.content}} {% endautoescape %} So that it will display text and image content not html code in the final template. But I find some of the content is too wide, makes a scroll bar in the bottom of my django page. I tried to use css like: overflow: hidden !important; But it is still not work.So I need go to admin to use ckeditor to manually editor the format of the article.For example ,add a line break if the line is too long. My question is ,is that any way that django can automatically editor the format of input content?So that I don't need to edit each article's format manually. Best! -
Insert JS value to Django template
As I am exploring Web Development, I require small assistance here. In my case, I have a folder with static images. To display an image I need to get data from API, let's say, some pointer on which particular image should be displayed. <img class="some_img" src="{% static 'image_PIONTER.png' %}"> I'm getting that pointer using JS in a separate file script.js. To achieve what I want I need to replace POINTER in the src attribute of html with some actual word (lets say 'Captain') to get an image 'image_Captain.png' from static files. How could I get this POINTER from a JS to django template? As I already know, Django renders its templates before any client side (JS code) executed. So I cant just pass this attribute or even a part of html as $().html or $().append. It won't work. Picture should be displayed on a button click, preferably without refreshing the whole page. Thanks in advance -
The current path, {% didn't match any of these django responsive images
I keep getting this error when the browser width size is below 640px and above 990px. I am trying to display different resolution images depending on the browser width size. The current path, about/{%, didn't match any of these. In other words the only image that displays properly is footer-city-medium.jpg {% extends "base.html" %} {% block content %} {% load static %} <picture> <source media="(min-width:990px)" srcset={% static '/images/footer-city-large.jpg' %}> <source media="(min-width:640px)" srcset={% static '/images/footer-city-medium.jpg' %}> <img src={% static '/images/footer-city-small.jpg' %}> </picture> {% endblock %} The page renders properly except for the image. Only the footer-city-medium.jpg renders in properly. Does the source attribute not work with django? -
Django Selenium test onclik not calling function
In a Selenium test of my homepage I ran into the following problem: I have a number of buttons on the page. When clicking one of them a selections list is populated with a number of options via a javascript function. After clicking one of the buttons the selection list can look like this: <select id="selectionList" name="List1" size="10" style="width:100%;"> <option style="color:#0275d8">Item Type 1</option> <option onclick="onSelection()" id="Item_1">Item 1</option> <option onclick="onSelection()" id="Item_2">Item 2</option> <option onclick="onSelection()" id="Item_3">Item 3</option> <option onclick="onSelection()" id="Item_4">Item 4</option> <option onclick="onSelection()" id="Item_5">Item 5</option> <option onclick="onSelection()" id="Item_6">Item 6</option> <option style="color:#0275d8">Item Type 2</option> <option onclick="onSelection()" id="Item_7">Item 7</option> <option onclick="onSelection()" id="Item_8">Item 8</option> <option onclick="onSelection()" id="Item_9">Item 9</option> <option onclick="onSelection()" id="Item_10">Item 10</option> </select> In my test I used the following to click on one of the items. WebDriverWait(self.browser, 60).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='Item_1']"))).click() I do see that item 1 gets highlighted but the onSelection() function is not called. I also tried this time.sleep(10) self.browser.find_element_by_id("Item_1").click() Again item 1 gets highlighted but the function onSelection() is not called. Any idea of how to solved this issue? -
How to make time slots(for a particular date and time) not appear after a person has booked it in Django?
I am creating a website in which there is a form where you can book appointments(for doctors)..The issue I am facing is that, if a particular timeslot(for the particular date and time) has been selected it should not appear anymore on the form, but I have no clue on how to do it The form looks like this(This is returned from the index function in views.py) <section id="appointment" data-stellar-background-ratio="3"> <div class="container"> <div class="row"> <div class="col-md-6 col-sm-6"> <img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt=""> </div> <div class="col-md-6 col-sm-6"> <!-- CONTACT FORM HERE --> <form id="appointment-form" role="form" method="post" action="{% url 'test' %}"> {% csrf_token %} <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Make an appointment</h2> </div> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Full Name"> </div> <div class="col-md-6 col-sm-6"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Your Email"> </div> <div class="col-md-6 col-sm-6"> <label for="date">Select Date</label> <input type="date" name="date" value="" class="form-control"> </div> <div class="col-md-6 col-sm-6"> <label for="select">Select Department</label> <select class="form-control" name="drop"> {% for entry in items %} <option>{{ entry.category }}</option> {% endfor %} </select> </div> <div class="col-md-6 col-sm-6"> <label for="select">Select Time</label> <select class="form-control" name="drop1"> {% for entry in times %} <option>{{ entry.time }}</option> {% … -
Django wait for session variable to be written
is it actually possible to wait for a session variable to be written in a django view befor I return the actual response? For example: views: def post_detail(request, pk): .... if post.file: if 'download' in request.session: del request.session['download'] request.session['download'] = post.file.url else: request.session['download'] = post.file.url I just want to wait until the variable has been written sucsessfully to the db/cache. Can smb help? Thanks in advance -
Django GraphQL UI - not working in Heroku
I am trying to deploy a Django-graphql api server to Heroku. The app is successfully deployed to Heroku. However, when I try to launch https://jeba-blogapi.herokuapp.com/graphql/, I am facing the issue The graphql.js is not found, but I have it in my settings.py files STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') I am also facing same error when I try to launch admin page(css is not getting loaded) -
Integrating Collapse functionality of Bootstrap with Django Backend. How to use for loops?
I'm struggling with a task in Django. I have my database up and running with information on resellers. (name, address, region etc...) and I want to implement Bootstrap collapse functionality where each card is a region. I was able to do that hardcoding the handling of the region. So in my base.html file I have: <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Region1 </button> </h2> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> {% block content_Region1 %} {% endblock %} </div> </div> </div> and in the block content of Region1 I use the home.html template as follow: {% extends "base.html" %} {% load static %} {% block content_Veneto %} <div class = "container"> {% for reseller in resellers %} {% if reseller.region == "Veneto" %} <div class="reseller_name"> <a href="{% url 'reseller_detail' reseller.id %}"> <p>{{reseller.name}} - {{reseller.cityname}}</p> </a> </div> {% endif %} {% endfor %} </div> What I would like to have is a list containing all the regions that are present in by database and then, in the base.html file I would like to do something like: {% for region in list_regions %} <div class="card"> <div class="card-header" id="headingOne"> <h2 … -
Returning user's name instead of it's ID in a many-to-one relationship in Django Rest Framework
I'm returning all the "posts" in response of a get request like this # views.py class PostView(APIView): def get(self, request): serializer = PostsSerializer(Post.objects.all(), many=True) return Response(serializer.data) And here's the serializer # serializers.py class PostsSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['description', 'files', 'created_at', 'author'] And here's the model # models.py class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) files = models.FileField(upload_to=upload_path) created_at = models.DateTimeField(auto_now_add=True) description = models.TextField(default="No Description Has Been Added") def __str__(self): return self.description So as you can see in the models, I have a field called author which has a many-to-one relationship with the user who created the post. Now here's the problem: In the response of that get request, I get authors IDs instead of their names. Each author has a displayname field and that's the field that I want. I thought of iterating each Post and replacing each author's value with it's name by querying the model that contains them (Account). Like this # views.py class PostView(APIView): def get(self, request): serializer = PostsSerializer(Post.objects.all(), many=True) dataList = serializer.data for index in range(len(dataList)): for key in dataList[index]: if key == 'author': dataList[index][key] = Account.objects.get(id=dataList[index][key]) return Response(dataList) But this throws back Object of type Account is not JSON serializable … -
Search outlooks in django
How can I make the search word look like this. I want it to be tabbed, no need for the user to click on the word. -
Django does not respect environment variables set in venv activate script
I have perused the similar questions available, but don't see any that explicitly match the behavior I am seeing in my project. Like many other folks, I am trying to move my sensitive key information out of my settings.py file. To do this, I have added multiple export statements to the end of the activate script for my local venv environment, like ###env/bin/activate export AWS_ACCESS_KEY_ID="**********" export AWS_SECRET_ACCESS_KEY="************" From there, I can reload the environment and confirm that they key value pairs are available by running python manage.py shell >> import os >> os.environ Which shows the correct values for the keys. Additionally, I can launch the development server with python manage runserver 0:8080 And am able to post files to the AWS S3 bucket as desired. However, once I reboot the server to restart the uWSGI process and access the site from its domain, I am unable to post files to S3. Instead I get a NoCredentials error, despite the fact that I can see the relevant AWS key information in the settings information available when the debug setting is set to TRUE. Why are the variables exported in the activate script available when launching the development server but not … -
Constraint of a single True value in many-to-many through table BooleanField
I want to achieve the following: Listings can be tagged under multiple categories A listing can have at most one main category. This is the category that best describes it, of all the categories it is tagged with. Admins should not be able to mark multiple main categories for a single listing. In my models.py I have: from django.db import models from django.db.models import UniqueConstraint, CheckConstraint class Listing(models.Model): title = models.CharField(max_length=50), content = models.TextField(), categories = models.ManyToManyField( 'Category', through='CategoryMembership', related_name='listings' ) class Category(models.Model): title = models.CharField(max_length=50), class CategoryMembership(models.Model): listing = models.ForeignKey( Listing, on_delete=models.CASCADE ) category = models.ForeignKey( Category, on_delete=models.CASCADE ) main_category = models.BooleanField(default=False) class Meta: constraints = [ UniqueConstraint( name='unique_listing_category_membership', fields=['listing', 'category'] )] To achieve 2 and 3 I thought I could add another constraint to CategoryMembership's Meta class. But I am not sure how to proceed as I do not want to prevent listings having multiple categories where main_category == False in the through table. Is such a constraint possible? Or is there a smarter way to structure the models to achieve this? -
Django Serializer's Source argument is not working
My two models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=200) customer_code = models.CharField(max_length=300, blank=True, null=True, default=None) class Bill(models.Model): customer = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True, related_name="customer_bill" ) payable_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) View: class BillView(APIView): def get(self, request, format=None): q = Bill.objects.all().select_related('customer') s = BillSerializer(q, many=True) return JsonResponse({ "bill": s.data }) Serializer: class BillSerializer(serializers.ModelSerializer): customer_code = serializers.CharField(source='user.customer_code', read_only=True) class Meta: model = Bill fields = ('id','payable_amount','customer_code') # binding customer_code here Current Output: "bill": [ { "id": 1, "payable_amount": "1000.00" }, { "id": 2, "payable_amount": "2000.00" } ] Expected Result: "bill": [ { "id": 1, "payable_amount": "1000.00", "customer_code": "CUS10001" # want this to be attached }, { "id": 2, "payable_amount": "2000.00", "customer_code": "CUS10002" # want this to be attached } ] I am trying to get all the bills and their customer-related details (i.e. 'customer_code', 'email' etc.) with it. However, "source='user.customer_code" does not seem to have any effect at all. What am I missing? Please suggest me. I have been following along this: this stackoverflow post with no luck. -
If statement on Django template based on model data
I have an if statement on my django template on what to display. but It wont change, it stays at *No warning*, whats wrong in my code? Thanks! condition: if my app detects 15 entries of extreme it will display Warning else if it detects more than 15 entries of extreme it will display Critical. models.py class Data(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def update_level(self): if 0.1 <= self.amount < 2.5: return 'Low' elif 2.5 <= self.amount < 7.5: return 'Medium' elif 7.5 < self.amount < 15: return 'High' elif 15 <= self.amount < 30: return 'Very High' elif 30 <= self.amount < 200: return 'Extreme' views.py def index(request): num = Data.objects.all() context = {'num': num} return render(request, 'analytics.html', context) html <h3>{{ num.level }}</h3> {% if num.level < 15 %} <h3 style="color:red;">Critical</h3> {% elif num.level == 15 %} <h3 style="color:yellow;">Warning</h3> {% else %} <h3>No Warning</h3> {% endif %} -
How to use multiple database in Django
I have to use two databases, one is a third party db(MySql) for which I only have read access. Another db is my Django application's db(Postgres). I need to access the third party's sql db , to run some calculations and use my Django applications db(Postgres) to store those calculated values. I am very new to Django, I understand the concept of Models , but my knowledge is very limited to adding users logging them in etc. Can anybody point me in the right direction or let me know about some best practices to be followed in order to achieve this ? To stream line my question, after adding both db details in settings.py what will happen when I run migrate command ? Especially the third party db ? -
How to add items in a dictionary?
Here I have two different types of data lists. I want to add value list inside property list. How can I do this ? "property": [ { "proeprty1": "name1" }, { "property2": "name2" }, { "property3":"name3" } ], "value": [ 1700, 1500, 1000 ], The desired output I want is: "property": [ { "proeprty1": "name1", "value": 1700 }, { "property2": "name2", "value": 1500 }, { "property3":"name3", "value": 1000 } ], -
Can I have a folder instead file for a Django custom command?
The only way I know to create a custom Django command is by putting the file in the project/app/management/commands folder like this project/app/management/commands/my_custom_command.py But I would like to know if there is a way to make a directory (like a python package) instead of a single file. It should be something like this: project ├── app | ├── management | | └── commands | | ├── my_custom_command | | | ├── __init__.py | | | └── ... (other stuff like settings and output files) | | └── ... | └── ... ├── manage.py └── ... There is a way to do something like that? I think it is possible to use a whole app folder to do something similar saving the command stuff in the app folder, but I don't like that solution. -
Why does Django ORM not find related object in post_delete signal?
When I delete a PumpLog I delete the related Invoice via on_delete = models.CASCADE. Invoices have a post_delete signal that queries on that relationship (see the line with #ERROR). So it goes: user deletes PumpLog -> which triggers delete Invoice -> which triggers Invoice post_delete signal models.py class PumpLog(BasicModelFields): gallons = models.PositiveIntegerField(blank=True, null=True, editable=False) class Invoice(models.Model): pump_log = models.ForeignKey('PumpLog', on_delete = models.CASCADE) def post_invoice_delete(sender, instance, **kwargs): instance.pump_log #ERROR # or print(instance.pump_log_id) #displays the correct id. But the below query fails. PumpLog.objects.filter(index = instance.pump_log_id) #ERROR The error: records.models.PumpLog.DoesNotExist: PumpLog matching query does not exist. I understand to some degree that the PumpLog could be deleted according to the docs: Note that the object will no longer be in the database, so be very careful what you do with this instance. Technically this warning refers to the Invoice in this case NOT the PumpLog. Plus in PGAdmin I can query the database directly and see the PumpLog and Invoice are still there. So why is the ORM having trouble finding the PumpLog? Is the PumpLog artificially removed from the scope of the ORM even though it hasn't been removed from the database yet? Or am I not understanding this correctly?