Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-ckeditor modal form does not change data on POST
I have a django project using django-ckeditor. I use HTMX to create a bootstrap modal to show my edit form. It renders correctly (I did add the ckeditor.js files at the end of the body in base.html). If I call my form by going to localhost/1/update, change the RTF value, and click save, it works fine. But rendering it in the modal form and clicking save, the form.has_changed() returns false. If I edit another field and it saves, the value of RTF does NOT change. It seems like the POST does not include the changed value for the CKEditor field. I've tried to reduce the code below to make it as short as possible. My model: class MyModel(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150) comment = RichTextField(blank=True, null=True) def __str__(self): return f'{self.name} - {self.description}' My form: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ( 'name', 'description', 'comment', ) My View def update_data(request, pk): model = MyModel.objects.get(id=pk) form = MyForm(request.POST or None, instance=model) if request.method == "POST": if form.is_valid(): print(form.has_changed()) form.save() return redirect("detail-form", pk=model.id) My HTML#1 - I click on the update button to open the modal {% extends "layouts/base.html" %} {% load static %} {% block content %} … -
Customizing model primary keys
I have model Mail which saves a mail object. Mail model also has a OneToMany relationship field, that is related to User(User can have many mails, but a mail can have only one owner(User object)). I need to implement its own primary keys reference system for each Mail object, because each mail is supposed to be related to an only one user to display urls the right way. For example if User-1 sends his first two mails in the whole app, they are saved with 1 and 2 id in the database, that's default django primary keys saving system. Then if User-2 sends his first mail, this mail is supposed to be saved with id 1, because it's first User-2 mail, but it's gonna be saved with id 3, because by default primary key reference system, the ids 1 and 2 are already taken. And this is the problem, because the url of first mail for User-2 will be displayed as /sent-mail/3, when it must be /sent-mail/1 So how to customize Mail model and implement it's own primary key references for each user. Here is the model: class Mail(models.Model): url_id = None title = models.CharField(max_length=64) body = models.CharField(max_length=1000) unvisited = … -
DJANGO REST FRAMEWORK - AssertionError
I am getting this error AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> I don't really understand what's wrong views.py class Links(viewsets.ViewSet): def create(self, request): serializer = LinkSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) # return Response({"error": "something went wrong"}) serializers.py class LinkSerializer(serializers.ModelSerializer): class Meta: model = Links fields = ( "title", "niche", "url", "owner", "date", ) valid = {'required': True} extra_kwargs = { 'title': valid, 'niche': valid, 'url': { 'required': True, 'validators': [UniqueValidator(Links, "Link has been posted already"),] } } def create(self, validated_data): newLink = Links.objects.create( title=validated_data['title'], niche=validated_data['niche'], url=validated_data['url'], owner=validated_data.get['owner'] ) newLink.save() return newLink You can check if out on github here -
How to override the default authentication form in django
I've been trying to override the authentication form, i ve inherited from the authenticationform class how do i make the loginview to use my custom form -
Django and Javascript How to Upload Multiple Images with Progress Bar
Good day, I am trying to upload multiple images in django with a progress bar. Currently, I have a working solution for only one image but now I want to add more fields and I need to show progress bar for all the images I am uploading. Below is my working code and the commented out code in the forms.py are the new fields I want to add. models.py class ProductImage(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True) main_image = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_one = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_two = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_three = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_four = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_five = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) forms.py class StoreDashboardProductUpdateForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "main_image", # "img_one", # "img_two", # "img_three", # "img_four", # "img_five" ] views.py def store_dashboard_product_update_view(request, slug, product_slug, pk): product = get_object_or_404(Product, pk=pk) form = StoreDashboardProductUpdateForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.instance.product = product form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, "object": product } return render(request, 'store/dashboard/product_update.html', context) {% extends 'store/dashboard/base/products-second.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <style> .not-visible { display: none; } … -
Django. How to make ModelChoiceField work with SingleObjectMixin, FormView, and inlineformset_factory?
So, I have been trying to make it function as planned, but there might be a tweak away from my knowledge. The objective is to show only related options in a form with a choice field. Model CONTRATO register all contracts Model FATURA register all invoices and it has a ForeignKey with CONTRATO in a relation one-to-many (so one contract has many invoices) Model LANCAMENTO register records from contracts that will be later assigned to an invoice in FATURA. So LANCAMETNO has a ForeingKey with CONTRATO in a relation on-to-many (so one contract has many recors in LANCAMENTO). And LANCAMENTO also has a ForeignKey with FATURA, that is null by default, so later it will be assigned a FATURA to that record in LANCAEMTNO. The goal is to have this logic in a form. So when user goes to LANCAMETNO to assign a FATURA, it can choose only FATURA with the same contract_id as LANCAMETNO. I got here resarching a lot, but this is as far I can go. I'm stuck. Here's the code, in case someone could point me in the right direction. Here is my code for Models: from django.db import models from django.urls import reverse, reverse_lazy # … -
get next page number instead of next page link django rest framework
I'm working with django rest framework but I face this problem with the pagination the output Show in next and previous the page link but I want the page number only my pagination.py from rest_framework.pagination import PageNumberPagination class MycustomPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 10 page_query_param = 'page' my views.py from .paginations import MMycustomPagination class AllSerialed(ListAPIView): pagination_class = MycustomPagination queryset = MyModel.objects.filter(blacklist=False).order_by("-date") serializer_class = MyModelSerial simple output { "count": 20, "next": "http://127.0.0.1:7000/data/?page=3", "previous": "http://127.0.0.1:7000/data/?page=1", "results": [ ] } -
How to setup Vue.js SPA when starting it in HTML
I have a django application where I have an area that is made in Vue.js. I would like to know if it is possible to set parameters at the time of initialization of the Vue.js app in HTML. For example a token where the VueApp can use to authenticate and fetch some apis in django. Today it is being done like this: <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> <script> window.config = {{vue_config | safe}}; </script> <script type="text/javascript" src="{% static 'js/app.js' %}"></script> </body> And inside the VueApp I get the configs from window.config Is there a better way to do this? -
Is there a way in Django to order a model using a "custom filter logic"?
I'm currently having a problem in a personal project which involves ordering by 2 custom fields (limit_date and priority). Let's suppose a model like: PRIORITY_CHOICES = [ ("red", "Red"), ("yellow", "Yellow"), ("green", "Green") ] class Todo(models.Model): limit_date = models.DateField() priority = models.CharField(choices=PRIORITY_CHOICES, max_length=15, blank=False, null=True) Let's suppose i want to order them following the following logic: if <current_todo>.priority == 'red': priority_scale = 3 elif <current_todo>.priority == 'yellow': priority_scale = 2 else: priority_scale = 1 priority_scale_with_date = <current_todo>.limit_date - datetime.today() * (<current_todo>.priority_scale) I know i can do some things with "conditional expressions" to get priorities as values, like: Todo.objects.annotate( priority_scale=Case( When(priority='red', then=Value(3)), When(priority='yellow', then=Value(2)), When(priority='green', then=Value(1)), default=Value(0), output_field=models.IntegerField())).order_by('-priority_scale', 'limit_date') But i don't know how can i put them all "together". Let's suppose a object with priority 'red' (value 3), with two days left to be done and another one with priority 'green' (value 1) with one day to be done. Their priorities will be something like: first_obj = 1 * 3 = 3 (days untill limit_date and 'priority_scale') second_obj = 2 * 1 = 2 (days untill limit_date and 'priority_scale') What i want, is to order them with a "junction" of 'priority_scale' and 'limit_date'. I am very confused here and sorry … -
Name error when trying to import API key from .env
I am trying to store my API Keys in a .env file I created the file as a File containing settings for editor file type. Stored my APIKeys TWILIO_ACCOUNT_SID=*** TWILIO_AUTH_TOKEN=*** TWIML_APPLICATION_SID=*** TWILIO_API_KEY=*** TWILIO_API_SECRET=*** Installed decouple, imported and used config to retrieve my API tokens in my settings.py file from decouple import config ... TWILIO_ACCOUNT_SID = config(TWILIO_ACCOUNT_SID) TWILIO_AUTH_TOKEN = config(TWILIO_AUTH_TOKEN) TWIML_APPLICATION_SID = config(TWIML_APPLICATION_SID) TWILIO_API_KEY = config(TWILIO_API_KEY) TWILIO_API_SECRET = config(TWILIO_API_SECRET) I am however getting the error message: TWILIO_ACCOUNT_SID = config(TWILIO_ACCOUNT_SID) NameError: name 'TWILIO_ACCOUNT_SID' is not defined -
Loading Screen for a Form
I am trying to make a loading screen when submitting a form. When I submit a form the page starts to load until the backend responds by downloading an excel file. The idea is to have the effect of "load screen" only until the file manages to download. html: <form action="{% url 'downloadStatusPickingCustomerByCollection' %}" method="POST">{% csrf_token %} <div class="pnl-collection"> <div> <div class="tituloPnl"> <h3>Estado Ordenes de Venta por Colección</h3> </div> <div class="btnExport"> <button onclick="loadDisplay()" class="btn btn-light" type="submit">Exportar</button> </div> </div> <div class="filtro"> <div> <div class="title-select"><span>Colección</span></div> </div> <div> <select class="form-select form-select-sm form-down-report" name="collection-StatusCustomer-name" id="" required> <option value="">- SELECCIONE COLECCIÓN -</option> {% if collections %} {% for collection in collections%} <option value="{{collection.Name}}">{{collection.Name}}</option> {% endfor %} {% endif %} </select> </div> </div> </div> </form> javascript: function loadDisplay() { if (document.querySelector(".form-down-report").value != "") { document.getElementById("preloader-camion").style.display = 'block'; jquery(window).load( function () { document.getElementById("preloader-camion").style.display = 'none'; }); } } I have the bakcend developed in django so in the form route you can see a django "url tag". -
Bootstrap cdn working on Django but doesn't look quite right
I am trying trying to integrate bootstrap into my django site but it doesn't look quite write. I was looking for css clashes but the only stuff i could find is in the static folder and it just has admin related css. All my pages work its just the css that looks a bit off, any help is great, thanks. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> {% block nav %} <ul id="nav"> <li>{% block nav-home %}<a href="{% url 'home' %}">Home</a>{% endblock %}</li> </ul> {% endblock %} <div id='content' class='main'> {% block content %} {% endblock %} </div> {% block scripts %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> {% endblock %} </body> </html> <!-- templates/registration/login.html --> {% extends "base.html" %} {% block title %}Log in{% endblock %} {% block content %} <section class="vh-100" style="background-color: #508bfc;"> <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-12 col-md-8 col-lg-6 col-xl-5"> <div class="card shadow-2-strong" style="border-radius: 1rem;"> <div class="card-body p-5 text-center"> <h3 class="mb-5">Sign in</h3> <div class="form-outline mb-4"> <input type="email" id="typeEmailX-2" class="form-control form-control-lg" /> <label class="form-label" for="typeEmailX-2">Email</label> </div> <div class="form-outline mb-4"> <input type="password" id="typePasswordX-2" class="form-control form-control-lg" /> <label class="form-label" for="typePasswordX-2">Password</label> </div> … -
GUI Python Simple Calculator Using Django
I'm trying to make a simple calculator with graphical user interface using Django ,I'm having trouble in calculating any of arithmetic operation(+,-,*,/) that what logic I have to apply in views.py files. Could someone help me out with this? I'm beginner in Django... views.py def view_calc(request): a=int(request.POST.get('t1',0)) b=int(request.POST.get('t2',0)) if request.method=='GET': resp=render(request,'calc.html') return resp elif request.method=='POST': if 'btn1' in request.POST: c=a+b elif 'btnsub' in request.POST: c=a-b elif 'btnmult' in request.POST: c=a*b elif 'btndiv' in request.POST: c=a/b d={'a':a,'b':b,'c':c} resp=render(request,'calc.html',context=d) return resp -
Why does SSE work locally, but not when hosted on IIS?
I'm using Django eventstream for SSE and Channels (I'm not able to use Memurai or Redis). When I run the local server, everything works great. The user can submit a file, that information is ran against the external 3rd party API it calls, and real time information is displayed back to the browser from the /events/ URL API. When configuring through IIS, everything works great EXCEPT the /events/ URL is unreachable (404), so the SSE connection doesn't get initiated which halts everything in it's tracks and I'm looking at a blank template that should be getting populated in real time. WebApp is hosted for local network only. I've attempted to use Daphne with various errors: daphne mysite.asgi:application: Traceback (most recent call last): File "C:\Python\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python\Scripts\daphne.exe\__main__.py", line 7, in <module> File "C:\Python\lib\site-packages\daphne\cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "C:\Python\lib\site-packages\daphne\cli.py", line 232, in run application = import_by_path(args.application) File "C:\Python\lib\site-packages\daphne\utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "C:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, … -
streamBuilder flutter doesnt display data
im using streamBuilder to rebuild my screen depend on the project_id selected by taping on the project widget i send project_id to the next screen with constructer the streamBuilder read that constructor well but doesnt display that fetched from the http response from django endpoint here the model and api // To parse this JSON data, do // // final task = taskFromJson(jsonString); import 'dart:collection'; import 'dart:core'; import 'package:flutter/foundation.dart'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:project/model/project_model.dart'; import 'package:project/tasksById.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; //List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x))); //String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Task { String? url; int? id; String? owner; String? project; String? title; DateTime? start; DateTime? end; String? desc; int? project_id; Task( {this.url, this.id, this.owner, this.project, this.title, this.start, this.end, this.desc, this.project_id}); factory Task.fromJson(Map<String, dynamic> json) => Task( url :json["url"], id: json["id"], owner: json["owner"], project: json["project"], title: json["title"], start: DateTime.parse(json["start"]), end: DateTime.parse(json["end"]), desc: json["desc"], project_id: json["project_id"], ); Map<String, dynamic> toJson() => { "url": url, "id": id, "owner": owner, "project": project, "title": title, "start": start?.toIso8601String(), "end": end?.toIso8601String(), "desc": desc, "project_id": project_id, }; } class SharedProojectId { Future<Future<bool>> setid(int? newId) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); return prefs.setInt("project_id", newId!); } Future<int> getid() … -
image in django won't upload via form
I already found many answers to that question but most of them refer to adding request.FILES wchich doesn't work for me. I can upload an image via admin page, but when it comes to form i am getting an error that image is not loaded (while it is) Here is my model class Player(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) position = models.ForeignKey(Position,on_delete=models.CASCADE) shirt_number = models.IntegerField() team = models.ForeignKey(Team,null=True,on_delete=models.SET_NULL) image = models.ImageField(upload_to='images/players/') Here is my form class PlayerForm(forms.ModelForm): class Meta: model = Player exclude = ('team',) Here is views.py def team_detail(request,slug): team = get_object_or_404(Team, slug=slug) players = Player.objects.filter(team_id=team.id) if request.method == "POST": form = PlayerForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('') else: form = PlayerForm() return render(request,'team_detail.html',{'team':team,'players':players,'form':form}) And here is template file <form method = "POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SUBMIT"> </form> Before submitting After pressing submit button -
How to use prefetch_related in many to many relation django rest framework
I have some models (models.py): class User(models.Model): username = models.CharField(max_length=250) fullname = models.CharField(max_length=250) class Permission(models.Model): name = models.CharField(max_length=250) class User_Permission(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) permission = models.ForeignKey(Permission, on_delete=models.CASCADE) views.py class User_View(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = User_Serializer I want to optimize api. How can I use prefetch_related there? I set related name to UserPermission model and User.objects.prefetch_related('related_name'). But queries are not optimized -
Django get data from ForeignKey models
I have a simple models with a ForeignKey models, I am trying to get data from the ForeignKey models and display them on a HTML file. I tried this but it give me an error 'QuerySet' object has no attribute 'AccountHistory' #Get AccountHistory ForeigKey Models data = Account.objects.all() test_trade = data.AccountHistory.all(pk=account_id) models.py class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) accountid = models.CharField(max_length=100) def __str__(self): return self.accountid class AccountHistory(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) tradeid = models.CharField(max_length=100) profit = models.FloatField() def __str__(self): return self.tradeid views.py def metrix(requets, account_id): if requets.user.id: # Get Account models data item = Account.objects.get(pk=account_id) #Get AccountHistory ForeigKey Models data = Account.objects.all() test_trade = data.AccountHistory.all(pk=account_id) context = { "test_trade": test_trade, "item": item, } return render(requets, "main/metrix.html", context) return render(requets, "main/testpage2.html") metrix.html <div class="container"> {% for tradeinfo in test_trade %} <div class="TradeHistoryTable"> <table class="table table-dark"> <thead> <tr> <th scope="col">TradeID</th> <th scope="col">OpenDate</th> </tr> </thead> <tbody> <tr> <td>{{tradeinfo.tradeid}}</td> <td>{{tradeinfo.opendate}}</td> <td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> -
How can I break up a Django request into multiple requests?
I wanna do the following inside a Django REST ModelViewSet: receive data from an HTTP POST request break the data into several pieces pass the pieces to different ViewSets that should handle authentication, etc. based on the original request Background is the following: I have a working REST implementation with normal ModelViewSets for all endpoints and now I'm implementing a syncing protocol for a Progressive Web App that should work completely offline. The idea is that the normal ViewSets keep working and I implement the custom logic only once in the ViewSets. But I want to be able to collect request data offline and send all at once (also to guarantee order). Then the "sync" endpoint breaks the data apart and passes it to the respective views. I'm only missing a copy of the request object with adjusted data... What I tried to far: deepcopy of the request object does not work I have a hard time figuring out how to construct a request from scratch that mimics the original -
problem when try to make ajax request with django
i have a problem when make ajax request to the server to add product to the card using django and jquery, this the URLs here: path('add_to_cart/', cartView.add_to_cart, name="add_to_cart") here the jquery code: $(document).ready(function () { $('.addToCartBtn').click(function (e) { console.log("jjjj") e.preventDefault(); var product_id = $(this).closest('.product_data').find('.prod_id').val() var product_qty = $(this).closest('.product_data').find('.qty-input').val() var token = $('input[name=csrfmiddlewaretoken]').val() console.log(token) console.log(product_id) console.log(product_qty) $.ajax({ method: 'POST', url: 'add_to_cart', data: { 'product_id' : product_id, 'product_qty' : product_qty, csrfmiddlewaretoken: token }, success: function(res) { console.log(res.status) alertify.success(res.status) } }) }) }); and here is the view django code: from django.http.response import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from store.models import Product, Cart def add_to_cart(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = request.POST.get('product_id') product_check = Product.objects.get(id=prod_id) if product_check: if Cart.objects.filter(user=request.user.id, product_id=prod_id): return JsonResponse({'status': 'Product Already in the Cart'}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create(user=request.user, product_id=prod_id, product_quantity=prod_qty) return JsonResponse({'status': 'Product Added Successfully'}) else: return JsonResponse({'status': "only" + str(product_check.quantity) + "is Available"}) else: return JsonResponse({'status': 'No Such Product Found'}) else: return JsonResponse({'status': 'Login To Continue'}) return redirect('/') and here is the view.html when add to card button exist: <section style="background-color: #eee;"> {% csrf_token %} <div class="container py-5 product_data"> <div class="row justify-content-center mb-3"> <div class="col-md-12 col-xl-10"> <div … -
How to auto update a models attribute on creation of another model
I have been learning django and django rest from several different courses and have started my own project which will be a forum type web application. I 4 model classes Category, SubCategory, Thread, and Post. What I want to be able to do is have an attribute for subcategory called num_threads that can be updated when ever a thread is made for the subcategory it is related to. Similarly I will want a thread to have attributes num_posts and num_views. I have been using foreign keys to relate the models. Now I am not sure that I am doing that part correctly. Here is my model.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): """ Category Class: Main Categories for GRDG Forum Creation and Deletion will be restricted to site admin """ # Attributes name = models.CharField(max_length=32, unique=True, blank=False) description = models.TextField(max_length=150, blank=True) def __str__(self): return self.name class SubCategory(models.Model): """ SubCategory Class: SubCategories will be one to many relation with category ie: Multiple subcategories related to one category Creation and Deletion will be restricted to site admin GET methods restriction will vary by subcategory """ # References category = models.ForeignKey(Category, on_delete=models.CASCADE) # Attributes name = models.CharField(max_length=32, unique=True, blank=False) … -
Django and Python logging what is the full dictionary for the formatter?
Apologies if the title is vague. Feel free to edit to include the correct terminology. In settings.py, I have the LOGGING dictionary with this formatter: 'formatters': { 'standard': { 'format': '{asctime} {message}', 'style' : '{', } I understand that asctime is the time that the log message was generated, and message is the message itself. But I don't know what other options are available. Is the message itself a Python dictionary, and the curly-braced items are keys in the dict? How can I view all keys in that dictionary? I assume {severity} is in there somewhere. What else can I enter? Also, what are the various options under 'style'? -
Input object to django database without user input
So i want to input objects in my django database based on a list of objects. How would i move forward with this? Doing it with user input works. A workaround could maybe be to set the user input fields based on a list of objects and then POST that form but it seems dirty. Any thoughts? :) -
Exception Value: Field 'id' expected a number but got ''. (Django)
I was trying to code an add photo page on Django but got an error. I was watching this video on youtube to write my own project. I already wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately, it did not work. Here is the "view.py" file: def addPhoto(request): categories = Category.objects.all() if request.method == 'POST': data = request.POST image = request.FILES.get('image') if data['category'] != 'none': category = Category.objects.get(id = data['category']) else: category = None photo = Photo.objects.create( title=Title, category=category, description=data['description'], image=image, ) return redirect('index') context = {'categories':categories} return render(request, 'auctions/newlisting.html', context) Here is the "urls.py" file: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newlisting", views.addPhoto, name="create_listing"), path('photo/<str:pk>/', views.viewPhoto, name='photo'), ] Here is the "models.py" file: class Category(models.Model): category = models.CharField(max_length = 30) def __str__(self): return f'{self.category}' class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' title = models.CharField(max_length = 60,) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField() def __str__(self): return self.description Here is the "newlisting.html" file: {% extends "auctions/layout.html" %} {% block body %} <div class="m-5"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6"> <h2>Create Listing</h2> … -
Any beginner friendly tutorial to integrate D3js with django?
I am looking for a tutorial (beginner friendly) to integrate D3js with Django. My objective is to display graphs on my django website using sqlite database. I found very few tutorial on this topic but they are beyond my level. Thanks.