Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send selected radio button id from Datatable to Django URL
I'm looking for a solution to get the value from my radio button and send it to my django url. When I get selected radio button in the first page of DataTables, it's working properly, However when select radio button from other page (not first page), I can't get the radio button value HTML <a href="{% url 'update_maintenance_issue' %}" id="edit"> <img src="{% static 'images/icons/edit3.png' %}"> </a> <table id="mytable1"> <thead align="center"> <tr align="center" style="font-weight:bold"> <th style="cursor:pointer" align="center">No</th> <th style="cursor:pointer" align="center">ID</th> <th style="cursor:pointer" align="center">Type</th> <th style="cursor:pointer" align="center">Line</th> <th style="cursor:pointer" align="center">Sequence</th> <th style="cursor:pointer" align="center">Module</th> <th style="cursor:pointer" align="center">Item</th> <th style="cursor:pointer" align="center">Sympton</th> <th style="cursor:pointer" align="center">status</th> <th style="cursor:pointer" align="center">Register</th> <th style="cursor:pointer" align="center">Assigned</th> <th style="cursor:pointer" align="center">Register dt</th> </tr> </thead> <tbody> {% for list in issue_list %} <tr> <td> <input name="radio_id" type="radio" id="radio_id" value="{{list.id}}"> </td> <td align="center">{{ list.id }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.sequence}} </td> <td align="center">{{ list.division }} </td> <td align="center">{{ list.module }} </td> <td align="left">{{ list.sympton }}</td> <td align="left">{{ list.status }}</td> <td align="center">{{ list.register }}</td> <td align="center">{{ list.assigned }}</td> <td align="center">{{ list.register_dt|date:'d/m/Y H:i' }}</td> </tr> {% endfor %} </tbody> </table> <!--DataTables--> <script type="text/javascript"> $(document).ready( function (){ $('#mytable1').DataTable(); }); </script> <!--Get ID from selected radio button and insert … -
Mysqlclient Installation error in python Django
I try to build a sample project in Pycharm. But In the step migrate classes i face an error. I am using the code python manage.py makemigrations Then terminal shows install mysqlclient. I am using pip install mysqlclient Then shows a error below sreeju@Sreeju:~/PycharmProjects/pythonProject21/SampleProject123$ python manage.py makemigrations Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 22, in <module> main() File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/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, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line … -
Create a modules with models in python
I have a rather strange problem, I wanted to make a whole module of models but django does not recognize that module with models For example: I created this module in which I made a folder models I also made an init py in which I import the model but nothing happens to me How should I proceed in this situation? -
How to combine two queryset by a commin field
I have these two below querysets. They have a common road_type_id edges = Edge.objects.values("road_type_id", "edge_id", "name", "length", "speed", "lanes").filter(network=roadnetwork) roadtypes = RoadType.objects.values("road_type_id", "default_speed", "default_lanes" ).filter(network=roadnetwork) I would like to replace in edges : all lanes with None as value by roadtypes.default_lanes all speed with None as value by roadtypes.default_speed How can I do that please? -
How to save some data in user model and some data save in extended user model from a html form
model.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.db.models.fields import CharField, DateField Create your models here. class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) phone=models.CharField(max_length=20) DateOfBirth=DateField(max_length=50) profession=CharField(max_length=50) bloodGroup=CharField(max_length=20) gender=CharField(max_length=20) city=CharField(max_length=30) thana=CharField(max_length=30) union=CharField(max_length=30) postCode=CharField(max_length=20) otp=models.CharField(max_length=30) def __str__(self) -> str: return self.user.username views.py def registrations(request): if request.method == 'POST': fname = request.POST.get('fname') lname = request.POST.get('lname') username = request.POST.get('username') phone = request.POST.get('phone') email = request.POST.get('email') Password = request.POST.get('password') Password2 = request.POST.get('password2') DateOfBirth = request.POST.get('DateOfBirth') profession = request.POST.get('profession') bloodGroup = request.POST.get('bloodGroup') gender = request.POST.get('gender') city = request.POST.get('city') thana = request.POST.get('thana') union = request.POST.get('union') postCode = request.POST.get('postCode') check_user = User.objects.filter(email=email).first() check_profile = UserProfile.objects.filter(phone=phone).first() if Password != Password2: context1 = {"message1": "Password mismatch", "class1": "danger"} return render(request, 'UserProfile/registration.html', context1) if check_user or check_profile: context = {"message": "User already exist", "class": "danger"} return render(request, 'UserProfile/registration.html', context) user = User.objects.create_user( first_name=fname, last_name=lname, username=username, email=email, password=Password) user.save() profile= UserProfile(user=user, phone=phone, DateOfBirth=DateOfBirth, profession=profession, bloodGroup=bloodGroup, gender=gender, city=city, thana=thana, union=union, postCode=postCode, ) profile.save() context = {"message": "Successfully registrations Complate", "class2":"alert1 success ", } return render(request, 'UserProfile/login.html', context) return render(request, 'UserProfile/registration.html') enter image description here I want to save the user name, email, password in the user model and others field wants to save in the UserProfile … -
Display Django Admin group selection while creation User
I'm trying to simplify User creation, showing User Model fields, 1 field from an extended Model and the group selection from Django Admin. It's working fine, but I can't get the same selection as Update User page. I'm trying to make this: [Group selection from User Update][1] But I can only get to this: [Default Django Multiple Choices][2] Here is my admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User, Group from django.contrib.auth.forms import UserCreationForm from django import forms # Register your models here. from .models import * class UserCreateForm(UserCreationForm): group = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ('username', 'first_name' , 'last_name', 'group', ) class UserBoolInline(admin.StackedInline): model = UserBool fk_name = 'user' can_delete = False verbose_name_plural = 'UserBool' class UserAdmin(BaseUserAdmin): add_form = UserCreateForm inlines = (UserBoolInline,) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('first_name', 'last_name', 'username', 'password1', 'password2', 'group' ), }), ) admin.site.unregister(User) admin.site.register(User, UserAdmin)``` [1]: https://i.stack.imgur.com/N1LcX.png [2]: https://i.stack.imgur.com/7EApY.png -
Serializers django rest framework
I am new to Django rest framework, I am working on a small project and I am facing a truoble with serializsers what I need is one URL request with a list of all the name of school, and another URL request that has all the information about the school(name, city, street, student). The probleem is that in both URLs I get the same information which is (name, city, street, student). Can someone help me with that? serializers.py class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] class SchoolNameSerializer(serializers.ModelSerializer): class Meta: model = School fields = ['name'] views.py class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() class SchoolNameViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolNameSerializer queryset = School.objects.all() urls.py router.register(r'schoolname', SchoolNameViewSet) router.register(r'school', SchoolViewSet) -
RuntimeError at /signup
I am begginer in django. I am getting this error. "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings." Can anyone help to solve this error? urls of my app: from django.contrib import admin from django.urls import path, include from home import views urlpatterns = [ path('',views.home, name='home'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('search/', views.search, name='search'), path('signup/', views.handleSignUp, name="handleSignUp"), ] views.py: def contact(request): messages.success(request, 'Welcome to contact') if request.method=="POST": name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] content = request.POST['content'] # print(name, email, phone, content) if len(name)<2 or len(email)<3 or len(phone)<10 or len(content)<4: messages.error(request, "Please fill the form correctly") else: contact = Contact(name=name, email=email, phone=phone, content=content) contact.save() messages.success(request, "Your message has been successfully sent") return render(request, "home/contact.html") models.py: from django.db import models class Contact(models.Model): sno= models.AutoField(primary_key=True) name= models.CharField(max_length=255) phone= models.CharField(max_length=13) email= models.CharField(max_length=100) content= models.TextField() timeStamp = models.DateTimeField(auto_now_add=True,blank=True) def __str__(self): return "Message from " + self.name + ' - ' + self.email admin.py: from django.contrib import admin from .models import … -
Why I am getting "Not Implemented Error: Database objects do not implement truth value testing or bool()." while running makemigration cmd in django
I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error Not Implemented Error: Database objects do not implement truth value testing or bool(). when I am running makemigration command. Please can anybody explain why I am getting this error and how to resolve it? I have include settings.py file, error log and mongodb compass setup image. settings.py """ Django settings for Chatify project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-1k4mo05el_0112guspx^004n-i&3h#u4gyev#27u)tkb8t82_%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Chatify.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, … -
RuntimeWarning: DateTimeField Model.date received a naive datetime while time zone support is active
I am trying to filter a query set to obtain this year's all posts. def thisYearQuerySet(objects): start_day = datetime.date(datetime.date.today().year, 1, 1) end_day = datetime.date(datetime.date.today().year, 12, 31) return objects.filter(date__range=[start_day, end_day]) django moans about start_day and end_day declaration may conflicts django.utils.timezone, I think it is not a big deal. But the warning is annoying, any suggestion on dismissing it (not disable django warning) will be appreciated. something like, how to get first day of the year and the last from django.utils full warning RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active. RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-12-31 00:00:00) while time zone support is active. -
Django heatmap d3.js passing returned data from search
am creating a searchable repository that displays heatmap after the search is completed in django (windows) and postgresql. my code for the search is not used to HTML. views.py def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = Bindll.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched)[:10] return render(request, 'Search/search_result.html', {'ChemSearched':ChemSearched,'tarname':tarname}) else: return render(request, 'Search/search_result.html',{}) Searchresults.html ... <br/><br/><br/><br/> <strong><h1>{% if ChemSearched %} <script> var margin = {top: 30, right: 30, bottom: 30, left: 30}, width = 450 - margin.left - margin.right, height = 450 - margin.top - margin.bottom; var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); {% for Bindll in tarname %} var myGroups = [ "{{ Bindll }}" ] var myVars = [ "{{ Bindll.ki_nm }}" ] {% endfor %} var x = d3.scaleBand() .range([ 0, width ]) .domain(myGroups) .padding(0.01); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) var y = d3.scaleBand() .range([ height, 0 ]) .domain(myVars) .padding(0.01); svg.append("g") .call(d3.axisLeft(y)); var myColor = d3.scaleLinear() .range(["white", "#69b3a2"]) .domain([1,100]) d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) { svg.selectAll() .data(data, function(d) {return d.group+':'+d.variable;}) .enter() .append("rect") .attr("x", function(d) { return x(d.group) }) .attr("y", function(d) { return y(d.variable) }) .attr("width", x.bandwidth() ) .attr("height", y.bandwidth() ) … -
django rest framework model habit tracker
I'm trying to do an habit tracker using django rest framework as backend and react-native as frontend. I have same issue with the model of data in django. I want create one Daily instance for each date between start_date and end_date when a Tracker is created. Could you give me some help on how I can do it? Thank you in advance. models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class Habit(models.Model): title = models.CharField(max_length=32) description = models.TextField(max_length=360) class Tracker(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() published = models.BooleanField(default=True) def is_active(self): today = datetime.now().date() return (today >= self.start_date) and (today <= self.end_date) class Daily(models.Model): STATUS = [('DONE', 'DONE'), ('TODO', 'TODO'), ('NOTDONE', 'NOTDONE'),] date = models.DateField() status = models.CharField(choices=STATUS, max_length=10) tracker = models.ForeignKey(Tracker, on_delete=models.CASCADE) serializers.py from rest_framework import serializers from .models import Habit, Tracker, Daily from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class HabitSerializer(serializers.ModelSerializer): class Meta: model = Habit fields = ['id', 'title', 'description'] class TrackerSerializer(serializers.ModelSerializer): class Meta: model … -
How can I get related objects for related objects of an object in Django in a single query when all linked using Generic Foreign Key
Assuming I have the following models and knowing that each Message can have multiple Records and each Record can have multiple Notes, how can I get a queryset of related Notes from a Message in a single query? class Note: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Record: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey() notes = GenericRelation(Note, related_query_name='records') class Message: records = GenericRelation(Record, related_query_name='messages') I know how to achieve this by using list comprehensions like shown below, however it is a bad approach since this will do multiple queries. if records := message.records.all(): notes = list(chain.from_iterable([record.notes.all() for record in records])) -
How to handle POST request from react to django?
How to handle a post request? I don't have any spec about that request. How do I can handle it proper that request and write in to my model? -
Django/AWS - An error occurred (403) when calling the HeadObject operation: Forbidden
I'm trying to set up my Django project to host static images on AWS S3 buckets, but when I try to upload an image via the Django admin panel I get the following error These are my settings in Django AWS_ACCESS_KEY_ID = 'some_key' AWS_SECRET_ACCESS_KEY = 'some_key_aswell' AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'us-east-2' Cors policy setup for the bucket [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] -
after deleting a superuser, all its entries are deleted django
there are also recent actions in the admin panel, for example, after creating an article, an inscription appears there, saying that this user created such an article, but after deleting this user, this last action is also deleted and I wish this last action was not deleted from the log how should i implement this? -
How to add images to python docxtpl from url
I have a docxtpl document, but I need to add images to the InlineImage from a url, not local disk. I'm using Django So this works (document is a DocxTemplate): InlineImage(document,'C:/Users/sande/Pictures/myimage.png') But how do i do this?: InlineImage(document,'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png') the image_descriptior doesn't accept a url.: Exception has occurred: OSError [Errno 22] Invalid argument:'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png' -
Use parameters in subfields with graphene-django without relay for pagination purpose
I'm using graphene with django and I'm struggling to do something that in my head should be very simple, but I don't find it documented anywhere in graphene docs or github nor did I see similar question here. The closest to it I found was: https://www.howtographql.com/graphql-python/8-pagination/ but as you can see I'd have to declare the parameters in the parent resolver which I don't want to. I have a query like this getUser(id: $userIdTarget) { id username trainings{ id name sessions{ id name } } } } I would like to implement a pagination in the sessions subfield. So this is what I would like: getUser(id: $userIdTarget) { id username trainings{ id name sessions(first:10){ id name } } } } and in the resolver I'd implement something like this: def resolve_sessions(root, info, first=None, skip=None): if skip: return gql_optimizer.query(Session.objects.all().order_by('-id')[skip:], info) elif first: return gql_optimizer.query(Session.objects.all().order_by('-id')[:first], info) else: return gql_optimizer.query(Session.objects.all().order_by('-id'), info) (gql_optimizer is just an optimization wrapper library I use) However this doesn't work as the field sessions correspond to a list of a model Session that is a fk to Training according to my django models, so this is automatically resolved by graphene because these types are DjangoObjectType , so I'm not … -
Django append products in categories with same names
and im tying to append products to categories with same name For example this is my models. models.py class Category(models.Model): headline = models.CharField(max_length=150) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True, blank=True) class Product(models.Model): headline = models.CharField(max_length=150) category = models.ManyToManyField(Category, related_name = 'products') views.py #For Example I have Main Category Technic. that has 2 child categories (Mobile Phones and SmartPhones) and both have category Phone with same name See the Tree: #Technic -> Mobile Phones -> Phone AND Technic -> SmartPhones -> Phone Technic -> Mobile Phones -> Phone - Contains 4 products Technic -> SmartPhones -> Phone - Contains 0 products All im trying to do is to check if smallest(childest) category has same name take its produts and fetch to another Phone Category in this position #Desired Result -> Technic -> Mobile Phones -> Phone - Contains 4 products ( same products ) Technic -> SmartPhones -> Phone - Contains 4 products ( same products ) Because both last child cat names are the same. -
Migrating back from DateTimeField to DateField in Django
I have a Django Model with two DateTimeFields: class FacilityTender(models.Model): """ Class to store Facility Tender """ publisher = models.ForeignKey('company.Company', on_delete=models.CASCADE) publish_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() ... I now have to change the DateTimeFields to DateFields. Doing so, the app can't be deployed since when quering the objects created before the migration don't fit to the new DateField. There is no error coming up when running the migration itself. It returns: invalid literal for int() with base 10: b'31 11:41:29' for this qs: running_tenders = FacilityTender.objects.filter(publisher__cashpool__name=user_cashpool.name) Full Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/facilities Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'applications.bank', 'applications.cashpool', 'applications.company', 'applications.core', 'applications.dashboard', 'applications.universe', 'applications.user'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /Users/jonas/PycharmProjects/Finchin/applications/dashboard/templates/dashboard/dashboard_frame.html, error at line 0 invalid literal for int() with base 10: b'31 11:41:29' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : {% load static %} 4 : 5 : <head> 6 : 7 : <!-- Meta --> 8 : <meta charset="UTF-8"> 9 : <meta name="viewport" content="width=device-width, initial-scale=1"> 10 : Traceback (most recent call last): File "/Users/jonas/PycharmProjects/Finchin/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) … -
How to dynamically remove forms from an unbound formset without JavaScript in Django
I have a solution, but it contains one problem. I know where the problem is happening in the code, but I can't solve it. Maybe someone has a better solution that doesn't contain any problems. Description of the problem: After deleting any form, the fields in the remaining forms are not pre-filled if the data is not valid. Procedure: The browser displays 5 forms. The first field of the first form contains invalid data. I activate the delete check-box in the last form and click on the "delete" button. The last form is deleted and the first field of the first form is not pre-filled. Cause Invalid data does not end up in cleaned_data after the is_valid () method, which is called in the not_deleted_forms () method of the TestFormSet class Code: app_formset.forms.forms from django import forms class TestForm(forms.Form): title = forms.CharField(label='Title', min_length=5) description = forms.CharField(label='Description', max_length=10) app_formset.forms.formsets from django.forms.formsets import BaseFormSet class TestFormSet(BaseFormSet): @property def not_deleted_forms(self): """Return a list of forms that have not been marked for deletion.""" self.is_valid() if not hasattr(self, '_not_deleted_form_indexes'): self._not_deleted_form_indexes = [] for i, form in enumerate(self.forms): if i >= self.initial_form_count() and not form.has_changed(): self._not_deleted_form_indexes.append(i) elif self._should_delete_form(form): continue else: self._not_deleted_form_indexes.append(i) return [self.forms[i] for i in … -
How can I use 'pdfkit' in djngo?
I want to generate pdf in my django project. I use pdfkit module to convert html page as a pdf file. I use this function but it has errors, like: OSError Exception Value: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(Person, pk=pk) enrolment = get_object_or_404(Enrollment,pk=pk) template_path = 'test.html' context = {'customer': customer, 'enrolment':enrolment} template = get_template(template_path) html = template.render(context) pdf = pdfkit.from_string(html, False) response = HttpResponse(pdf, content_type='application/pdf' ) response['Content-Disposition'] = 'filename= "report.pdf"' return response -
Connect Angular Frontend to Django View
I have a basic django app that simply uploads an excel file onto an oracle database. I created a python class (uploader) to carry out some the sanity checks on the file and upload to the database. I have managed to successfully create a UI using HTML in Django templates which works fine. However, I wanted to migrate the front end to an Angular front end. I have created the angular app but I am currently struggling to understand how to connect the front end to django. Having researched online, they advise using models, serializers but because I carry out the upload through a standalone python class, I am not sure how to connect the two using this method. I assume I have to use a HttpClient to somehow connect to this view? Any help will be greatly appreciated. Thanks upload/views.py def clickToUpload(request): if request.method == 'POST': if 'form' in request.POST: try: upload_instance = uploader(request.FILES['file'], request.POST['date']) _ = upload_instance.run_process('File', update_log=True) message= "Success" except Exception as e: upload_message = 'Error: ' + str(e) return render(request, 'Upload/upload.html', {'upload_message':upload_message}) -
ModelForm doesnt render input fields properly
I have the following ModelForm: class RaiseTender(forms.Form): """ A form to raise a new tender for new facilities """ country = forms.ModelChoiceField(queryset=OperatingCountries.objects.all(), required=True) publisher = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all')) class Meta: model = FacilityTender fields = ['publisher', 'amount', 'currency', 'country', 'start_date', 'end_date'] # Model class FacilityTender(models.Model): """ Class to store Facility Tender """ publisher = models.ForeignKey('company.Company', on_delete=models.CASCADE) publish_date = models.DateTimeField(auto_now_add=True) amount = models.FloatField() currency = models.CharField(max_length=3) country = models.CharField(max_length=50) start_date = models.DateTimeField() end_date = models.DateTimeField() submissions = models.IntegerField() is_active = models.BooleanField(default=True) is_closed = models.BooleanField(default=False) is_successful = models.BooleanField(default=False) # Checks how long is left for the tender period, # Assumes a 7 day tender duration @property def time_remaining(self): return self.publish_date + timedelta(days=7) def __str__(self): return F"{self.publisher} tendered {self.amount} {self.currency}" Now in my my view I do the following: def raise_tender(request): if request.method == 'GET': # Get the user instance user = User.objects.get(username=request.user.username) # Query companies associated to the cash pool of the requesting user companies = Company.objects.filter(cashpool__company=user.company) # Override the RaiseTenderForm company field RaiseTender.base_fields['publisher'] = forms.ModelChoiceField( queryset=companies) # Return the form form = RaiseTender() # Process inputs on POST request else: .... But for whatever reason the form only renders the fields where I provide a queryset to pre-populate. It's not the case with … -
Get the instance of related model and save
I need to create and save with the related model. My model looks like Class Abs(models.Model): detail = models.ForeignKey(Detail, ........) class Detail(models.Model): user = models.ForeignKey(get_user_model(), ...) detail_parts = models.ForeignKey(Abs,....) What I want to achieve is to create a new A and retrieve its instance and create a new Detail with user and detail_parts (related to model Abs) inside view class AView(viewsets.ModelViewSet): def create(self, request, *args, ** kwargs): detail = request.data.get(detail) // a = A.objects.filter(detail=detail) // here it return integer(example 20) Detail.objects.create(user=user,detail_parts=a) // returns Detail.detail_parts must be a "Abs" instance Any ideas ?