Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Feed User a Django Background Task Response
I created a web application using django that utilizes a FedEx API so that a user can create shipments through my website. The response of this FedEx API call is in xml format that contains a lot of data such as; was the request a success or failure, error messages, error codes, tracking number (if successful) etc. I am using django background tasks to make these API calls and once a process finishes I am unable to retrieve the response from the API call. I was thinking to maybe store the xml response in a file and feed it to the user but before I do that I wanted to find out if there is a better way. I also would like to know the best practice for API responses in general, like does the user need to see the entire response and if so how can I display it to them in the best way possible. -
Would Python and Django fit my needs for my first project?
This is my first post here. Been using this site for ages and you guys have always helped out! I'm sorry if I ask something that has been answered numerous times before but when I searched I couldn't find anything. THe thing is that I'm planning a personal project. I have 10 years of detailed personal financial data and want to build a app/web interface to view this data more visually. I'm also planning on uploading new data each month and would like to be able to analyze that data in an "Power BI"-manner. I'm doing this to develop my, currently basic, skills in the area. More or less as a hobby project. Was thinking that Python and Django would be a good fit for this project. Mostly since I have some (kinda little) experience using these. Can you guys advice me towards another language or am I able to pull this of using Python and Django? Feel free to comment anything I missed and need to edit. I'm still in the learning process :) Cheers! -
Proper way to write a python loop and if else
I have a check statement like - for k in data: for l in prevValues: if k['name'] == l: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) I know this is wrong, I want to first complete the check block then come out of it, and then, at last, execute the save statement. What may be the proper way of writing this? My code till if statement works fine. -
How to display images using their path in Django
I have created a image folder in static directory. It contain all images. The images path along with some other information is fetched from MYSQL database using python. Images folder with python function that will fetch data from database. Python fetches data from database and stores in dict. Here's example of data store in database Image path is stored in database as a string in charfield It gets passed to html which convert dict to javascript object. [The image contain 3 obj which stores data of products at 0,1 and 2 and it is added in a string literal stored in javascript variable][4] Error that is shown in console -
Cannot upload big image files to Django project
I'm a beginner trying to make my first Django project. I'm using ubuntu local server on Windows 10 (WSL), i set up basic web server Nginx -> Gunicorn -> Django. In my django app i have a custom user with profile photo: class MyUser(AbstractBaseUser, PermissionsMixin): .... profile_image = models.ImageField(upload_to='users/%Y/%m/%d/', null=True, blank=True) .... with project settings: MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Using django admin site i can upload image, image successfully stores in image folder and shows up on user page, but only if image size is less than 70-80kB. If image size is bigger than that, every time when I'm trying to upload image using Django Admin Site or user form, web page gets stuck on loading, and after a moment i get message "127.0.0.1 didn’t send any data. ERR_EMPTY_RESPONSE", with no error message from the server. What am i doing wrong? -
Accessing token from jQuery Ajax call securely for TokenAuthentication DRF
I have gone through every forum, and I am not able to find an answer to this. I did find great examples of getting Token using the command line, but not from the jQuery Ajax call. My application (multi-user docker hosted) extensively uses jQuery Ajax call from separate .js files. During the development: I stored the generated token in the session (at the login), Then access the token from the session in : def get_context_data(self, **kwargs): for each view, and then stored at the template using a variable. Then use it when I do API calls using Ajax in the separate js files (below). $.ajax({ url: '/work/api-stream-item-process-vote/' + contentid + '/', contentType: 'application/json', cache: false, processData: false, headers: {'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val(), "Authorization": "Token " + token}, type:"PATCH", data: JSON.stringify({ 'key':key, 'sel_image':contentid, }), success: function(data){ consolemsg("Successfully updated the vote information!") //stream_reload_vote_info(key,contentid,data['total_rating'],data['voted']) }, error:function(xhr, errmsg, err){ show_message("An error occured! Please contact administrator for help!!!",ERROR) } }); Question: How do I securely accomplish this? Is there a full implementation of this using Django + Ajax I can refer to? -
How to force django test to create sqlite database in file (not in memory)
I've tried changing test database name: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'mytestdatabase', }, } } I've also tried running test with: python manage.py test --keepdb Nothing works. It seems to keep working in memory. I need django to generate the sqlite file to search it using a DBMS like DBeaver and see what are my tests actually doing inside the DB. -
Django REST Framework: how to make a APIView/Serializer browserable?
Using serializers.HyperlinkedModelSerializer with viewsets.ModelViewSet works fine for CRUD, as described in the docs. Unfortunately this requires a Model which I don't have on the login endpoint. Relevant code snippets: # Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(min_length=8, max_length=50) # View class Login(APIView): permission_classes = [permissions.AllowAny] def post(self, request: Request, *args, **kwargs): # Some logic using LoginSerializer # urls.py urlpatterns = [ path('v1/login', Login.as_view()) ] Any idea? Thanks in advance! -
Using filter in list
I am building a Blog App and I am trying to access first posts of all the users in last 2 days, So i am using solution for accessing first posts. when i use filter of last 2 days then the first post method is not working. So i thought "I should use filter in another query" models.py class BlogPost(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') date = models.DateTimeField(auto_now_add=True) views.py def first_posts(request): time = timezone.now() - timedelta(days=2) posts = [user.blogpost_set.first() for user in User.objects.prefetch_related( 'blogpost_set')].filter(blogpost__date__gte=time) context = {'posts':posts} But it showed 'list' object has no attribute 'filter' I also tried using :- ALL_POSTS = [] for post in posts: ALL_POSTS.append(post).filter(post__date=time) But it showed 'NoneType' object has no attribute 'filter I will really appreciate your Help. Thank You -
Single table's column can point to multiple table in django
Let's say I have tables FormulaA, FormulaB...FormulaX, and productContent. Formula { characteristicsA, characteristicsB, ... } Now, each product will be based on only a single formula(A to X). I want to design my database in such a way, that table productContent will have two columns, productContent { product_id, -> foreign key to product table formula_id -> can point to either of table formulaA,..formulaX } Now, My concerns/requirements are: if I have product_id, how can I get it's formula detail? Can I use select_related query here? we can take help of polymorphism, like make a common table, Formula, and from there formulaA,..formulaX can inherit. and in ProductContent table, we can have a new column, formula which will point to base table. But here also, how can I achieve requirement 1? -
django-channels: page not found
I am trying to set up django-channels. I did everything according to the instructions, but when I try to connect, I get a 404 error - page not found. I make a request from the localhost to the dev server. config/base.py INSTALLED_APPS = [ "grappelli", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "adminsortable2", "channels", "corsheaders", "django_filters", "django_multilanguage_content", "django_otp", "django_otp.plugins.otp_totp", "drf_yasg", "notifications", "rest_framework", "rest_registration", "storages", "vv.announcements.apps.AnnouncementsConfig", "vv.core.apps.CoreConfig", "vv.discussions.apps.DiscussionsConfig", "vv.manage_categories.apps.ManageCategoriesConfig", "vv.messaging.apps.MessagingConfig", "vv.users.apps.UsersConfig", "vv.vital_notif.apps.VitalNotifConfig", ] ASGI_APPLICATION = "config.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(env("REDIS_HOST"), 6379)], }, }, } config/asgi.py import os import sys import django from django.core.asgi import get_asgi_application app_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, "vv")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.base") django.setup() django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from config.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": URLRouter(websocket_urlpatterns), }) routing.py from django.urls import path from vv.messaging.consumers import MarkAsReadConsumer websocket_urlpatterns = ( path("ws/mark/", MarkAsReadConsumer.as_asgi()), ) runner.sh #!/bin/sh daphne -b 0.0.0.0 -p 8000 config.asgi:application -v2 python manage.py runworker -v2 client.js let socket = new WebSocket("ws://<ip>/ws/mark/"); docker-compose.yml version: "3.7" x-env_file: &env_file env_file: - ./.env services: nginx: build: ./nginx container_name: vv-fix-nginx ports: - "5555:80" depends_on: - backend networks: - vv-fix-network redis-vv: image: redis:alpine container_name: vv-fix-redis volumes: - vv_fix_redis_volume:/var/lib/redis/data/ ports: - … -
django sign up form not storing the username
I have a sign up form that does not store the username properly, other fields are stored successfully. Shouldn't it save the username because it is in the fields ? I saw that I cannot login and this is because the row in the table does not have the username. views.py class SignUpFormView(FormView): form_class = SignUpForm template_name = 'users/authentication/login/signup.html' def post(self, request): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) # some logic here user.save() messages.success( request, "Great! You are able to login now.") return redirect('login') else: messages.error(request, form.errors) return redirect('login') forms.py class CustomUserCreationForm(UserCreationForm): def clean_username(self): username = self.cleaned_data["username"] try: TbUser.objects.get(username=username) except TbUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class Meta(UserCreationForm.Meta): model = TbUser class SignUpForm(CustomUserCreationForm): email = forms.EmailField() customer_id = forms.CharField(label="Customer ID") def clean_username(self): data = self.cleaned_data['username'] if TbUser.objects.filter(username=data).exists(): raise forms.ValidationError( "Username already exists. Pick another one") def clean(self): cd = self.cleaned_data password1 = cd.get("password1") password2 = cd.get("password2") if password1 != password2: raise ValidationError("Passwords did not match") return cd class Meta: model = TbUser fields = ['username', 'email', 'real_name', 'customer_id', 'password1', 'password2'] -
Create a dropdown select based on a first selected dropdown in DJango/Ajax
I'd like to create a dropdown select based in a first selected dropdown using Ajax/JQuery with Django I alread make a couple of tests, but without success for now: Models: class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id views: from django.shortcuts import render from maintenance.models import MaintenanceEquipment def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): if request.method == 'GET': line = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line) context = {'equipment': equipment} return render(request, 'maintenance/maintenanceIssue.html', context) maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="equip_sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="equip_sequence" name="equip_sequence"> {% for instance in equipment %} <option id="{{ instance.equip_id }}" value="{{ instance.sequence }}">{{ instance.sequence }}</option> {% endfor %} </select> </div> </div> </div> </form> <script> $("#line_nm").change(function () { var url = $("#maintenanceForm").attr("data-equipment-url"); var lineID = $(this).val(); $.ajax({ url: url, … -
Sending data to sqlite3 with django
I want to send data to Sqlite3 with Django. What do you need to learn for this? And how can I do? Can you explain simply? My goal: to make a registration system. It can be used on multiple computers. Likewise, the registration process will be via CMD. Sending the information will be through the Django framework. -
Django/Celery 'Received unregistered task of type'
I have hit a brick wall for quite some time with my simple task that I need to run asynchronously from a Django server. I have a form on a page that when I submit a value my views.py executes a simple multiplication function from the tasks2.py file which also has my Celery stuff. With Celery running by this command from my terminal: celery -A tasks2 worker -l info -P eventlet And submitting a number "2 in this case" through my form I get the following error Received unregistered task of type 'app_scrape.tasks2.my_multiply'. The message has been ignored and discarded. Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[["2"], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (80b) Traceback (most recent call last): null}]' (80b) File "c:\users\likea\.virtualenvs\django-j1eue__k\lib\site-packages\celery\worker\consumer\consumer.py", line 581, in on_task_received ry\worker\consumer\consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'app_scrape.tasks2.my_multiply' Project structure: - src-estategy - manage.py - app_scrape - views.py - tasks2.py - models.py - .... - proj_estategy - __init__.py - settings.py - urls.py - .... tasks2.py from celery import Celery app = Celery('tasks2', broker='amqps://mcbojxac:6sC7n38IdqmNoNgUjmjBkHum6RxRnaqt@clam.rmq.cloudamqp.com/mcbojxac', backend='db+postgresql://kbsrjinigbkzqu:ed0aab74c997b56aa756d510439e28404cf1e87de629a7af66bd49ae29961bbb@ec2-44-195-201-3.compute-1.amazonaws.com/d85tdjbd3am2sc') @app.task def my_multiply(x): print(x) return x ``` **views.py** ``` #Django … -
How to pass a nested foreignkey object to a another model?
I've been stumped for days; hoping one of you wizards can get me out of this pickle.. I have a model called ExtraSlot class ExtraSlot(models.Model): ....... employee = models.ForeignKey(Employee, on_delete = models.CASCADE, related_name="employee") this is the serializer class ExtraSlotSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True) <-- If I add this it tries to iterate through and errors out class Meta: model = WorkingSlot fields = (..... 'employee') fields = ('__all__') <- also used this to no avail depth = 3 I'm trying to add an Employee to the model; in the admin panel it is fine. The employee object can be selected. The DRF api doesn't show anything; I've read HTML list input isn't supported which is fine but the employee field as an input (even in raw format) doesn't show at all. Employee extends User (AbstractBaseUser) - here is the list error if I try many=true and passing the entire serializer. TypeError: 'Employee' object is not iterable (if I try pass EmployeeSerializer with many=True; which makes sense.) employee = EmployeeSerialzer() - passes the entire object as if I want to create a new one?! I want to allow a user to sign employee to the extraslot. Please help! -
DateField's DateInput widget with 'format="%B"' is not localized/translated
I'm trying to display a form-field with full month + Year representation (like 'December 2021') but I cannot localize it to German. In forms.py I'm using format("%B %Y") in the widget to achieve that representation, like so: date = DateField(widget=DateInput(attrs={"autocomplete": "off"}, format="%B %Y")) I'm using this form in an UpdateView, nothing fancy... <div class="form-row"> ... some fields <div class="form-group flatpickrdatetimeinput col-md-6 mb-0"> {{ form.date|as_crispy_field }} </div> </div> The date representation works in terms of Month + Year, but I need to localize the month name (December -> Dezember). I cannot find the error, I tried changing the field attribute (localize=True) and also I have played around with the settings (i18n, l10n, etc) with no success. In fact, the settings have worked out so far. In the same template I am using the 'date' template filter and it translates the month just fine <h2>{{campaign.date | date:'F Y' }}</h2> -
First posts of all the users
I am building a BlogApp and I am trying to implement a feature , So, I am trying to access first post of all the users. models.py class BlogPost(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') views.py def first_posts(request): user = User.objects.all() posts = BlogPost.objects.filter(user=user).first() context = {'posts':posts} return render(request, 'first_posts.html', context) But it is showing The QuerySet value for an exact lookup must be limited to one result using slicing. When i try to use User.objects.all().first() then it is only showing first post in all posts. I have tried many times But it is still not working. Any help would be much Appreciated. Thank You -
How do I write a view function for exporting a filtered data to an excel file in Django?
I have a model which has five ForeignKey fields, which basically works a master data comprising of almost all the models. class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE) receivables=models.ForeignKey(Receivables, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) @property def track_id(self): ...... Its view is like: def ipd_report_view(request): report=IpdReport.objects.all() print(report[0].patient.name) total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2} return render(request, 'account/ipdreport.html', context) Its Template: <body> <table class="design"> <h3>Track Report</h3> <th class="design">ID</th> <th class="design">Name</th> <th class="design">Patient Number</th> <th class="design">MR/UID</th> <th class="design">Diagnosis</th> <th class="design">Treatment Type</th> <th class="design">Type of Patient</th> <th class="design">Date of Admission</th> <th class="design">Max Fractions</th> <th class="design">Total Package</th> <th class="design">RT Number</th> <th class="design">Discount</th> <th class="design">Approved Package</th> <th class="design">Proposed Fractions</th> <th class="design">Done Fractions</th> <th class="design">Base Value</th> <th class="design">Expected Value</th> <th class="design">Date of Discharge</th> <th class="design">Mould Charges</th> <th class="design">CT Charges</th> <th class="design">Amount Received</th> <th class="design">Billing Month</th> <th class="design">Deficit or Surplus Amount</th> <th class="design">Deficit Percentage</th> <th class="design">Surplus Percentage</th> <th class="design">Action</th> {% for rp in report %} <tr class="design"> <td class="design">{{rp.track_id}}</td> <td class="design">{{rp.patient.title.title}}{{rp.patient.name}}</td> <td class="design">{{rp.patient.patient_number}}</td> <td class="design">{{rp.patient.mr_uid}}</td> <td class="design">{{rp.package.diagnosis}}</td> <td class="design">{{rp.package.treatment}}</td> <td class="design">{{rp.package.patient_type}}</td> <td class="design">{{rp.package.date_of_admission}}</td> <td class="design">{{rp.package.max_fractions}}</td> <td class="design">{{rp.package.total_package}}</td> <td class="design">{{rp.receivables.rt_number}}</td> <td class="design">{{rp.receivables.discount}}</td> <td class="design">{{rp.receivables.approved_package}}</td> <td class="design">{{rp.receivables.proposed_fractions}}</td> <td class="design">{{rp.receivables.done_fractions}}</td> <td class="design">{{rp.receivables.base_value}}</td> <td class="design">{{rp.receivables.expected_value}}</td> <td class="design">{{rp.discharge.date_of_discharge}}</td> <td class="design">{{rp.discharge.mould_charges}}</td> <td class="design">{{rp.discharge.ct_charges}}</td> <td class="design">{{rp.realization.amount_received}}</td> <td class="design">{{rp.realization.billing_month}}</td> <td class="design">{{rp.realization.deficit_or_surplus_amount}}</td> <td … -
Why css don't loaded in django?
I encountered a problem. Just my .html, the css files not loaded,even I write the absolute path which can be visited from the browser as follows: <link ref="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> <link ref="stylesheet" type="text/css" href="http://127.0.0.1:8000/static/css/bootstrap.min.css" /> Could anyone please help me? My PyCharm project location: E:\workspaces\workspace-py\python-test django project relative lication: \django\djangotest \template\base.html: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title></title> <link ref="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> <link ref="stylesheet" type="text/css" href="{% static 'css/index.css' %}"/> \static\css\bootstrap.min.css \djangotest\settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) -
How to trigger a function at regular times?
I have a DashboardData model. I get some info from this form and according to the given answers, I run a function by using form answers as parameters. This is my form model: class DashboardData(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user n_username = models.CharField(max_length=250) n_password = models.CharField(max_length=250) n_url = models.CharField(max_length=250) n_port = models.IntegerField() period = models.CharField(max_length=250) db_password = models.CharField(max_length=250, null=True) And this is my function: class myFunction(): def __init__(self, n_user, n_password, n_url, n_port, db_password): self.zaman = datetime.now().strftime("%Y-%m-%d") self.location = a_url self.static_fields = {} self.index_name = "vulns-" + self.zaman self.download_all(n_user, n_password, n_url, n_port, db_password) self.send_it() I want to run this function like functions.myFunction(n_user, n_password, n_url, n_port, db_password) with user's DashboardData values every 15 minutes. How can I do it? I tried to use apscheduler app but I cannot run it. -
Question regarding a Django web app with firebase storage and heroku for deployment
I've made a wallpaper generator website that also lets users share wallpapers, memes nd stuff, im using my sqlite db to store credentials of created users and then use firebase storage to upload their images (using pyrebase4) , while the image url gets retrieved and is stored in the sqlite3 db. I just have two questions. Question 1: my first question is when i will launch the website using heroku, do i need to set some enviroment variable or something for it to work? like i know we have to do something like that for aws, and your secret key etc.. do i need to do some extra stuff so that it can work?? Question 2 : So while the user is logged in my website, he already is authenticated by django...so when he uploads an image he/she doesnt know what's going behind the scenes...but im uploading their image to firebase...so currently in test mode im doing this without authenticating anyone...but in production how im going to do that? do i have to authenticate them with fireabse as well? can i just let anyone upload a file their as long as they are logged in my website?? which will obv … -
When using Django's Default Storage should/can you close() an opened file?
When using Django's DefaultStorage it's possible to open and read a file something like this: from django.core.files.storage import default_storage file = default_storage.open("dir/file.txt", mode="rb") data = file.read() When using python's own open() method, it's best to close() the file afterwards, or use a with open("dir/file.txt") as file: construction. But reading the docs for Django's Storage classes, and browsing the source, I don't see a close() equivalent. So my questions are: Should a file opened with Django's Default Storage be closed? If so, how? If not, why isn't it necessary? -
formset django, problems saving a lot of data added to the click
Hi everyone I have a problem with django formset.I can create through js adding objects but at the moment of creation I only save the first object I created and not the others. I beg you for months that I have been on this thing without finding a real solution. below I put my code, I hope you are reading that you can help me, I will be grateful. HTML <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">TEST FORMSET</h1> <a href="{% url 'lista' %}" class="btn btn-outline-dark">LISTA</a> </div> <hr> <form method="post"> {% csrf_token %} {{ formset.management_form }} <div class="list-form"> {% for form in formset %} <div class="esercizio-box"> {{ form.as_p }} </div> {% endfor %} </div> <div id="form-vuoto" class="hidden"> <div class="esercizio-box"> {{ formset.empty_form.as_p }} </div> </div> <div class="text-end mt-2 mb-5"> <button id="add" type="button" class="btn btn-success">AGGIUNGI</button> </div> <input type="submit" class="btn btn-primary" style="width:100%;" value="crea"> </form> </section> SCRIPT <script> $('#add').click(function(){ var form_idx = $('#id_form-TOTAL_FORMS').val(); $('.list-form').append($('#form-vuoto').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> VIEWS.PY from django.forms import formset_factory def testViews(request): testFormSet = formset_factory(testForm, extra=0) if request.method == "POST": formset = testFormSet(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('/lista/') else: formset = testFormSet() context = {'formset': formset} return render(request, "tests.html", context) -
Error __str__ returned non-string (type NoneType)
I know that this error is classic. But I'm facing a harder problem : This is my model. I've check all the topics about this common problem, try to resolve it but I don't achieved. I cannot add stafftimeslot in the admin panel. Can you help me ? Here is my models.py : from django.db import models from django.utils import timezone from staffs.models import Staff from students.models import Student TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '09:30 – 10:00'), (2, '10:00 – 10:30'), (3, '10:30 – 11:00'), ... ) class StaffTimeSlots(models.Model): staff = models.ForeignKey(Staff, null=True, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) time_slot = models.CharField(max_length=2, choices=TIMESLOT_LIST) def get_absolute_url(self): return reverse('stafftimeslot_detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.date) EDIT : When I delete ForeignKey, it works but when I reuse it, it does not work anymore. So I tried to replace with OnetoOneField and ManytoManyField and I have faced with the same problem. It seems that the model does not accept model relations. How can I do to relate this model with the Staff model with a foreign key ?