Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Django models from database using for loop in HTML table
In my views.py I add all transactions from the database to the request context. I want to display the data in a dashboard table. How do I do this using a for loop? I can use the following to print out all data, but it doesn't fit into the table. {% for transaction in transactions %} {{transaction.date}} {{transaction.event}} {{transaction.total}} {% endfor %} The HTML code <div class="sales-boxes"> <div class="recent-sales box"> <div class="title">Transaction history</div> <div class="sales-details"> <ul class="details"> <li class="topic">Date</li> <li><a href="#">Date 1</a></li> <li><a href="#">Date 2</a></li> </ul> <ul class="details"> <li class="topic">Event</li> <li><a href="#">Event 1</a></li> <li><a href="#">Event 2</a></li> </ul> <ul class="details"> <li class="topic">Total</li> <li><a href="#">$1</a></li> <li><a href="#">$2</a></li> </ul> </div> <div class="button"> <a href="#">See All</a> </div> </div> My views.py code used to render the page from .models import Transaction def earner_dashboard(request): transactions = Transaction.objects.all() return render(request, 'dashboard.html', context={"transactions":transactions}) -
Detect which url a request came from in Django
In my Django project I have 2 different views that render pageA.html and pageB.html. In both pages there is a Next button, which when clicked is sending a form to the backend for additional processing followed by a redirect view C that renders pageC.html. When the requests arrived to view C is it possible for me to detect path that the view had gone through? That is I will like a way to see if the reqeusts originally came from view A or viewB. -
JavaScript quantity function is not working
I am a person who is studying JavaScript. Django is trying to modify the quantity, but the quantity button is not working. But I don't know why. Also, I have implemented the option so that information about the option appears when it is selected, and I hope the quantity will also appear when it appears. If you could tell me how to modify it, I'd really appreciate it. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"> </div> </div> <body onload="init();"> <form name="form" method="get"> <input type=hidden name="sell_price" value="5500"> <input type="button" value=" - " onclick="del();"> <input type="text" name="amount" value="1" size="3" onchange="change();"> <input type="button" value=" + " onclick="add();"> <input type="text" name="sum" size="11" … -
How to get logged in user id for "default=" value in django?
How to get Logged In User id for model.py in Django? This is mymodel.py file: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) c_user =models.ForeignKey(User, on_delete=models.CASCADE, default= ) def __str__(self): return self.title class Meta: ordering = ['-date_added'] How to get logged in user id for default= value in c_user ? -
Manage free and busy appointment in django
I'm looking for an efficient way to create appointments between teachers and students. I want teacher to be able of make their students know their availabilities : For example, A Teacher writes on the application that he is free on Monday from 8am to 9am. The Student wants an appointment with his teacher. The Student checks free time slots of his teacher and choose the appointment on Monday from 8am to 8.30am. A second Student want an appointment and the application have to show him only the free time of the Teacher from 8.30am to 10am on Monday and not from 8am to 8.30 because now this time slot is busy with the first student appointment. There are a Teacher class and a Student class. I'm thinking about creating a class of dailySchedule for the teacher with time hour slot boolean fields in which 0 means free and 1 means busy. When a student choose an appointment from 8am to 8.30am, the field slot_8_8h_30 equals to 1. Then, in a AppointmentBook class, the appointment is added. If the row corresponding to the appointment is deleted, the field slot_8_8h_30 come backs to 0. This is what I've done in Django : … -
Remove id field from djongo model
I want to get rid of the id field from every djongo model that inherits the Django default model. For example, the documents for ./manage.py createsuperuser (auth_user) should only have _id, not id -
How to Pythonically test whether a function is called with a certain argument in Python?
I've got a Django codebase which contains an endpoint. The endpoint does many things, and I now want to check whether the endpoint calls the function do_metadata_request (pasted below) with a specific token. def do_metadata_request(url_info, token): metadata_url = f"{settings.META_SERVER_BASE_URL}/{url_info['dossier']}" headers = {} if token: headers['Authorization'] = token return requests.get(metadata_url, headers=headers) So after some fiddling around I made the setup below. It works, but it does the actual test in a mocked function which I define outside the test itself. It just doesn't feel elegant or Pythonic at all. I'd rather do the assert inside the test, or at least define the mock_do_metadata_request within the test. Does anybody know a way to do this more elegantly? class MockResponse: def __init__(self, status_code, json_content=None, content=None, headers=None): self.status_code = status_code self.json_content = json_content self.content = content self.headers = headers def json(self): return self.json_content MOCK_TOKEN = "Bearer " + create_test_token([settings.EXTENDED_SCOPE]) def mock_do_metadata_request(url_info, token): assert token == MOCK_TOKEN return MockResponse( 200, json_content={ 'access': settings.ACCESS_RESTRICTED, 'documents': [{'barcode': '123', 'access': settings.ACCESS_RESTRICTED}] } ) class TestFileRetrieval(TestCase): def setUp(self): self.c = Client() @patch('project.metadata.do_metadata_request', side_effect=mock_do_metadata_request) def test_token_is_passed_on_to_metadata_server(self, mock_do_metadata_request): header = {'HTTP_AUTHORIZATION': MOCK_TOKEN} response = self.c.get(IMG_URL, **header) -
What technologies are out there for creating Building Block applications
I want to build an app that is similar to Scratch and IRobot Education Code. It should that functions that are normally complicated to someone who has no programming knowledge and makes it an easy drag-and-drop experience for them. It should look somewhat modern and user-friendly. Right now I am planning this app and checking what technologies I will be using to know what I will have to learn. My requirements: python as backend - preferred modern GUI can be web-based expandable easy to learn not "re-inventing the wheel" support Windows 7/10 From my research, I was only able to find Google's "Blockly" library and I would like to know if there are any alternatives for it that would suit me better. From my understanding, If I want something that looks and feels good and modern I will have to make it web-based. I was thinking about Django. The question is if there are any libraries (like for example how bootstrap does with its elements) that implement this "building block" mechanism. -
What is difference between these two method of updating DB using form?
I'm trying update db using form. I want to select title in dropdown, and update 'opening_crawl' field to input from text area. models.py : class Movies(models.Model): episode_nb = models.IntegerField(primary_key=True) title = models.CharField(max_length=64, unique=True, null=False) opening_crawl = models.TextField(null=True) director = models.CharField(max_length=32) producer = models.CharField(max_length=128) release_date = models.DateField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, editable=True) forms.py: class TitleDropDownForm(forms.Form): title = forms.ModelChoiceField(queryset=Movies.objects.only('title'), empty_label=None) opening_crawl = forms.CharField(widget=forms.Textarea) views.py: def update(request): msg = '' if request.method == 'POST': form = TitleDropDownForm(request.POST) if form.is_valid(): #method 1 : it updates 'opening_crawl' properly, but not 'updated_time'. movie = form.cleaned_data['title'] movie.opening_crawl = form.cleaned_data['opening_crawl'] movie.save() #method 2 #h = Movies.objects.get(pk=1) #h.opening_crawl = 'HAND WRITTEN MESSAGE!' #h.save() return redirect(request.META.get('HTTP_REFERER')) else: form = TitleDropDownForm() if not form.fields['title'].queryset: msg = 'No data available.' return render(request, 'ex07/update.html', context={'form' : form, 'msg' : msg}) method 1 works with 'opening_crawl' field, but 'updated' datetime field was not changed. When I tried like method 2, it updates both fields properly. What is the difference between two method? Is there any misunderstanding? -
Django Date field, form, format mix up
I encounter an error while retrieving date input field data, after looking at numerous threads I still cannot find the answer. The error I receive is : ValueError at /datetime time data '2021-12-31' does not match format '%d/%m/%Y' Thanks Here is my config in details: forms.py class DateInput(forms.DateInput): input_type = "date" def __init__(self, **kwargs): kwargs["format"] = "%d-%m-%Y" super().__init__(**kwargs) class DateStartForm(forms.ModelForm): class Meta: model = DateStart fields = ["start"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["start"].widget = DateInput() ``` models.py ``` class DateStart(models.Model): start = models.DateField(_("Start")) def __str__(self): return f'{self.start}' ``` skimmed views.py ``` def bookingdef(request): if request.method == "POST": if form1.is_valid(): arrival_date = request.POST.get("start") date_obj = datetime.datetime.strptime( arrival_date, '%d/%m/%Y') arrival_date = DateStart.objects.get_or_create(start=arrival_date) form1 = DateStartForm() return render(request, "core/datetime.html", {"form1": form1}) ``` settings.py ``` DATE_FORMAT = ['%d-%m-%Y'] DATE_INPUT_FORMATS = ['%d-%m-%Y'] ``` -
Why do we need Virtual Environment in Django?
I'm new to Django and I wonder why it's recommended to set up a virtual environment. I asked google and found that Python provides a tool virtualenv to create an isolated Python environment. Still, I don't get what's meant by an Isolated environment. Well, briefly my problem is that I don't understand why we need a virtual environment in simple terms. -
How to make a return in the form of a whole message in the __str__ model function in Django?
I just would like getting a next str in my html: made by John Kennedy. But now I have the next str: made by ('John', 'Kennedy') There is the cod from model: class Teams(models.Model): first_name = models.CharField('First name', max_length=15, default='Name') second_name = models.CharField('Second name', max_length=30, default='Family' ) ---...---- def __str__(self): return f'{self.first_name, self.second_name}' class Portfolio (models.Model): ---...---- name = models.ForeignKey (Teams, related_name='maked', on_delete=models.PROTECT,blank=True) ---...---- So how can I fix this? -
DJANGO makemigrations keeps on making new migrations even if no models are changed
I'm confused on why this is happening, I search and found out maybe that the date_choices causes this. Anyway to fix this? I can't delete migration files because I already uploaded my project on github. models.py: class SchoolOfficeHours(models.Model): DAY_CHOICES = { ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday') } HOUR_CHOICES = { ('6AM','6AM'), ('7AM','7AM'), ('8AM','8AM'), ('9AM','9AM'), ('10AM','10AM'), ('11AM','11AM'), ('12NN','12NN'), ('1PM','1PM'), ('2PM','2PM'), ('3PM','3PM'), ('4PM','4PM'), ('5PM','5PM'), ('6PM','6PM'), ('7PM','7PM'), ('8PM','8PM'), ('9PM','9PM'), } starting_day = models.CharField( max_length= 12, choices = DAY_CHOICES, default = 'Monday', ) last_day = models.CharField( max_length= 12, choices = DAY_CHOICES, default = 'Friday' ) opening = models.CharField( max_length= 4, choices = HOUR_CHOICES, default = '8AM', ) closing = models.CharField( max_length= 4, choices = HOUR_CHOICES, default = '5PM' ) class Meta: verbose_name_plural = 'School Office Hours' def __str__(self): return f"School Office Hours: from {self.starting_day} to {self.last_day}, {self.opening} - {self.closing}" Should I just change the value of each tuple to integers? But I think, by doing so might be confusing in coding in the future. -
Django custom login form not displaying inputfields
I have a problem with my login template. I´m not sure, but I think I´m using a custom form since the path is templates/registration/login.html . So, I think it gets replaced to the usual django form. But the input fields of my form dont show up, so I only have the login button and some text underneath it. Similar questions I read couldn´t solve it, so I hope someone can me help here. If you need any code more, please let me know. Thanks in advance. views.py def login(response): if response.method == "POST": form = LoginForm(response.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) auth_login(response,user) return redirect("home") else: form = LoginForm() return render(response, "registration/login.html",{}) urls.py from register import views as v path("", v.login, name="login"), login.html {% block content %} <form method="POST"> {% csrf_token %} <div class="content"> <h3>{{form.username}}</h3> <h3>{{form.password}}</h3> <button type="submit">Login</button> </div> </form> <br> <p>Don´t have an account yet?</p> <p>Create one <a href="/signup">here</a></p> {% endblock %} -
Django: static files not connected
i cannot undestand why django can't load my static files. This is the structure: Here my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] Here my main.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'styles/main.css' %}" /> <script src="{% static 'js/script.js' %}"></script> And this is the result: Can someone help me found the mistake? Thanks a lot! -
Pass Javascript variable into Django tag
as the title says I'm trying to replace a value in my Django tag with a Javascript variable. I'm not sure if it's even possible but here is what I have (The tag is between ``): const myTemplate = (list) => html` <form method="post" class="notes-form"> {% csrf_token %} {{ user.profile|meet_notes:15 }} <div> <button type="submit">Send</button> </div> </form> ` I would like to replace the 15 by a variable like ${list.met_profile.id} for exemple (this tag will render an input with a value of this variable, here 15). Thank you! -
Django Authentication module for connecting with Directory Service
I am building an web application using Python Django REST framework.I am looking for authentication module in Django that can be bind with Active Directory. Any suggestions ? -
Django TypeError - TypeError: issubclass() arg 1 must be a class
I want to migrate my config in django application, but below console isn 't working. python3 manage.py migrate python3 manage.py makemigrations Traceback (most recent call last): File "/usr/src/frontend/manage.py", line 22, in <module> main() File "/usr/src/frontend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mungmung01/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/mungmung01/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class I don't know what was wrong. My config in django application is very shorts. Here is my urls.py from django.contrib import admin from django.urls import path from mungmung01.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', MainPage.as_view()) ] And here is my models.py from django.db import models from django.db.models.deletion import CASCADE # 전체 데이터모델은 이곳에 구현되어 있습니다. # PositiveInteger = unsigned int입니다. class MainPageVisitor(models.Model): VisitorNum = models.PositiveIntegerField(primary_key=True, null=False) # 방문객번호 NumVisit = models.PositiveSmallIntegerField(null=False) # 방문한 횟수 ipAddress = models.GenericIPAddressField() # ip주소 TimeVisited = models.DateTimeField(null=False) # 방문시간 TimeLeft = models.DateTimeField(null=False) # 떠난시간 Service = models.SmallIntegerField() # 이용한 서비스. 1=홀랜드 | 2=철학 | 3=엔지니어링 | 4=질의응답 Here is my views.py from django.http import request … -
I need JavaScript to calculate the quantity and total price
if you select the Django option, you can select the quantity, and we are writing a code that calculates the total price by adding the option price and the product price. How can I write JavaScript that calculates quantity and total price in my code? When you select an option, the information for the option appears, and then adjusting the quantity is also recommended. I'd appreciate your help. <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> /*value.extra_cost = Option Additional Price*/ /*happgae = value added to product and option price*/ <script> $().ready(function() { $("#optionSelect").change(function(){ var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price … -
How can I change django default logout success template?
enter image description here by default its showing admin logout page. I tried path('logout/',auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), this is not working -
reverse referencing in query lookups that span relationships
In Django official doc, there is an example as below, from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline In below lookup, >>> Blog.objects.filter(entry__headline__contains='Lennon') Q: Even though one foreign key defined in Entry class is pointing to Blog, but there is no entry field defined in Blog class, how can above lookup refer to Entry class from Blog in the form of entry__headline? I did not see anywhere in official doc authorize this kind of usage.. -
Pass django templatetag return value in if statement
I want to use the return value of my templatetag in if statement. This is the templatetag # validate_bookmark.py from django import template from user.models import Bookmark register = template.Library() @register.simple_tag def validate_bookmark(post, user): if Bookmark.objects.filter(user=user, post=post).first() != None: return True return False Template {% load validate_bookmark %} {% if (validate_bookmark post_obj request.user) == True %} <!-- Something like this --> <button data-postpk="{{i.pk}}" class="**fw-bold** bookmarkBtn mx-3 n-border-outline n-border-outline far fa-bookmark px-0 py-0" style="font-size: 1.1rem;"></button> {% else %} <button data-postpk="{{i.pk}}" class="bookmarkBtn mx-3 n-border-outline n-border-outline far fa-bookmark px-0 py-0" style="font-size: 1.1rem;"></button> Any help is appreciated Thank you -
How can I use a serializer to retrieve data from a django model in a nested way?
I have a django model with 3 fields: "product", "price_1" and "price_2". I would like to serialize this model in a way that the result would be: { "product": "some product", "price": { "price_1": 15.00, "price_2": 25.00 } } I was able to reach this result by creating a model for the price and connecting it to the product model with a foreign key. #Models class Product(models.Model): product = models.CharField() price = models.ForeignKey(Price) class Price(models.Model): price_1 = models.FloatField() price_2 = models.FloatField() #Serializers class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ['price_1', 'price_2'] class ScheduleSerializer(serializers.ModelSerializer): price = PriceSerializer() class Meta: model = Product fields = [ "product", "price", ] It worked, but it's very ineffective. Is there a way for me to achieve the same result, but having only one model such as: class Product(models.Model): product = models.CharField() price_1 = models.FloatField() price_2 = models.FloatField() And it would be even better if I could have only the numbers without the word "price": { "product": "some product", "price": { 1: 15.00, 2: 25.00 } } Although the second result is better, I'd already be very happy if I could achieve the first one using only one model. Thanks in advance! -
Restrict notifications to following users with Django-Channels
I'm working on a concept and try to analyse how to set it up. To make it easier let's imagine it's a social network. You can follow people and people can follow you. When you follow someone and this person do actions on the app, all the followers should receive a notification about it. The app will be developped with Django and Django-channels. My question is what is the best architecture to implement for these notifications. I was thinking about creating a group for each user on connection then select every follower connected and add them to this group, then select every following and add the user to the groups but that will make me a huge number of groups. I'm a bit scared that it could impact the performances. Would love to have your opinion :) -
Django CSRF Middleware: Why is my request CSRF token different to the one sent in the request header?
For initial background information, I have a similar setup to this post - please note this is NOT my issue. My configuration is working, the browser accepts the CSRF Set-Cookie from the response. CSRF cookie is http only. I have the appropriate CORS settings. I have a separately hosted SPA where I'm currently testing this flow: SPA pings the backend server for a CSRF token. Make a login post request. Login is denied by 403 on the server due to the CSRF token not matching. See my screenshots. The first part of the screenshot shows that Djangos CSRF middleware found a token in my request starting with 'q1jHW', the second part of the screenshots shows that the same middleware is expecting the request to have a token starting with 'Mrmh9'. The final part of my screenshot shows that the login request my browser made DOES have the 'Mrmh9' CSRF Token in it's headers. Why is my requests token being changed by the backend and not having the expected token being updated? I believe the issue may be with HOW I'm setting the initial token: I'm simply using the get_token function from django.middleware.csrf and doing something like: response["X-CSRFToken"] = get_token(request) I …