Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove HTML tags in Django messages
Basically I have a view with Django where I add some messages like this: from django.contrib import messages def myView(request): #some stuff messages.error(request, "My message here") return render(request, "myApp/myTemplate.html", context = data) And then I print them in the template like this: {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} But the problem is that the messages framework is adding HTML tags to the message and when the message is printed, the <ul> and <li> tags are added. So after the template is rendered it looks like this: <div><ul class="errorlist"><li>My message here</li></ul></div> I would like to know if there is a way to avoid the message getting these html tags added. Also, I would need it outside of the template too, so in the unit tests I can do something similar to: messages = list(response.context["messages"]) self.assertEquals(len(messages), 1) self.assertEquals(str(messages[0]), 'My message here') Is there any way to achieve this? Currently using Python3 and Django 4 Note that I would like to completely avoid the framework to add the tags, so I do not need to use striptags filter. -
Django Can't access URL Pk from FormView Class
I am putting together a simple medical-related project that includes allowing user to order lab tests on a patient. From the patient screen they select Order Tests. The UrlPattern, which includes the Patient pk, brings up the OrderTestsView which is a FormView. The kwargs in this view have no pk even though it is in the Url. I use a FormView because I need to access the list of tests selected in the Forms MultipleModelsChoice. But I need the patient information before the Order form is selected because I have to display who the patient is at the top of the order screen. Normally I would use get_context_data to do all of this, but the kwargs are blank. Not sure why FormView ignores the pk parameter, but how do I fix this? urls.py path('order-tests/<pk>/', OrderTestsView.as_view(), name='order-tests'), forms.py class TestOrderForm(forms.Form): choice = forms.ModelMultipleChoiceField(Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") view.py class OrderTestsView(FormView): model = Universal_Test_File form_class = TestOrderForm success_url = '/list_tests/' template_name = "lab/order_tests.html" patient = get_object_or_404(Patient, pk) ***## CANNOT ACCESS PK*** def form_valid(self, form): choice = form.cleaned_data.get("choice") if choice: for test in choice: print(test.service_id, test.test_name) -
MultiValueDictKeyError at /authors/postform/
i have bulit a books management app in django-rest framework with UI in html css and bootstrap. But when i'm trying to add new authors to the database doing a post request i'm getting this multivalue dict error even though i checked the name in the form. traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/authors/postform/ 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', 'genebox', 'rest_framework'] 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'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('Name'), another exception occurred: File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Online Test\GeneBOX full stack (27th)\myproject\genebox\views.py", line 58, in author_save name = request.POST['Name'] File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /authors/postform/ Exception Value: 'Name' ```urls.py``` urlpatterns = [ path('', views.home, name='home'), path('authors/', views.Author_list, name='all_author'), path('authors/postform/', views.author_save, name='authsave'), path('books/', views.Book_list, name='all_books'), path('authorcsv/', views.author_csv, name='author_csv'), path('bookcsv/', views.book_csv, name='book_csv') ] models.py class Authors(models.Model): Gender_choice = ( ('M', 'Male'), ('F', 'Female'), ('Other', 'Others'), ) Name = models.CharField(max_length=70) Age = models.IntegerField() Gender = models.CharField(max_length=20, choices=Gender_choice) Country … -
getting AttributeError 'str' object has no attribute 'data' when makinh request to Django-based Server from Flutter application
Hello fellow developers! I am trying to make a request to my Django-based server. lets first look at the endpoints that are causing trouble url.py path("getBookings/<str:Role>/<str:id>/", views.getBookings), path("archiveBooking/<str:Role>/<str:id>/", views.archiveBooking), these endpoints work fine when I make a request to them via localhost i.e. when I run the server with python manage.py runserver they also work fine when I try to make a request via my heroku-deployed application. But when I try to make a request via flutter, the following error shows up, I/flutter (10506): Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] I/flutter (10506): Server time: Sun, 27 Feb 2022 12:53:22 +0000 I/flutter (10506): Installed Applications: I/flutter (10506): ['django.contrib.admin', I/flutter (10506): 'django.contrib.auth', I/flutter (10506): 'django.contrib.contenttypes', I/flutter (10506): 'django.contrib.sessions', I/flutter (10506): 'django.contrib.messages', I/flutter (10506): 'django.contrib.staticfiles', I/flutter (10506): 'fyp_api.apps.FypApiConfig', I/flutter (10506): 'rest_framework'] I/flutter (10506): Installed Middleware: I/flutter (10506): ('whitenoise.middleware.WhiteNoiseMiddleware', I/flutter (10506): 'django.middleware.security.SecurityMiddleware', I/flutter (10506): 'django.contrib.sessions.middleware.SessionMiddleware', I/flutter (10506): 'django.middleware.common.CommonMiddleware', I/flutter (10506): ' here is my views.py code for the two concerned endpoints: @api_view(['GET']) def getBookings(request, Role, id): #Data = request.data #Role = Data['role'] #Role = request.META.get('HTTP_ROLE') BSerializer = '' if(Role == 'expert'): try: #eID = Data['eID'] eID = id #eID = request.META.get('HTTP_EID') expertExists = Experts.objects.filter(expertID = eID).exists() if(expertExists): exp = Experts.objects.get(expertID = eID) … -
SQL - How do I create a linkage table?
I'm building the following data model in Django / SQL Table 1 (Entity) - things that can do things Entity ID: Enum: (Person, or Business) Table 2 (Person) Entity ID: Person ID: Firstname Lastname Table 3 (Ltd Co.) Entity ID: Ltd Co. ID: Company Name Company No. I'm trying to link a Person, who has a Limited Co., with an Agent (who is also a Person) that also has a Limited Co. So 4 different entitites, two of which are type Person, and two of which are type Limited Co. Do I need another Linkage Table? E.g. Profile Person Profile Ltd Co Agent Person Agent Ltd Co Entity 1: Type Person Entity 3: Type Business Entity 2: Type Person Entity 4: Type Business Q. How do I create this Linkage Table in a Django Model / or SQL? Q. Is a Linkage Table the right approach? -
Django form buttons
I have an order form that should display product sizes as buttons, but the buttons do not register to be selected unless a user clicks exactly on the letter for the size ('S', 'M', etc.) in the exact center of the button. Clicking the space between the letter and the border of the button marks it as selected, but when you click Add to cart, it deselects itself. class OrderForm(forms.Form): def __init__(self, instance, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.instance = instance self.fields['size'] = forms.ModelChoiceField( queryset=self.instance.sizes.all(), widget=forms.RadioSelect()) The HTML is as follows: {% for choice in order_form.size %} <button type="button" class="size-btn">{{ choice }}</button> {% endfor %} Sizes is a simple model: class Size(models.Model): size = models.CharField(max_length=10) def __str__(self): return self.size This way the rendered HTML is a mess: <button type="button" class="size-btn"> <label for="id_size_0"> <input type="radio" name="size" value="2" id="id_size_0" required>S </label> </button> How do I fix the buttons so that they get selected even if clicked outside of the very center, in the size letter? Thanks. -
(mismatching_state) CSRF Warning! State not equal in request and response in django and google-api
I'm creating a web page in django which uses google api in order to send a pdf file to google drive. Everything was working perfectly on my local machine but as soon as i put it on production i got an error ((mismatching_state) CSRF Warning! State not equal in request and response.) as you can see down below. Here is the function which sends the request: def send_drive(file_name, file_path): CLIENT_SECRET_FILE = '/home/djuka/reusabletechnologies/project_app/reBankMini/reBankMiniApp/client_secret_156600557463-8e2qka5c4t646t7t4ksmbluo3aovv4q6.apps.googleusercontent.com.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # Upload a file file_metadata = { 'name': file_name, 'parents': ['1WpY7cw3S5RAPvCfFyPMDkw0I3vIZfQ_c'] } media_content = MediaFileUpload(file_path, mimetype='application/pdf') file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file) And Create_Service() function is in Google.py: import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google.auth.transport.requests import Request from datetime import datetime def Create_Service(client_secret_file, api_name, api_version, *scopes): print(client_secret_file, api_name, api_version, scopes, sep='-') CLIENT_SECRET_FILE = client_secret_file API_SERVICE_NAME = api_name API_VERSION = api_version SCOPES = [scope for scope in scopes[0]] print(SCOPES) cred = None pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle' # print(pickle_file) if os.path.exists(pickle_file): with open(pickle_file, 'rb') as token: cred = pickle.load(token) if not cred or not cred.valid: if cred and cred.expired and cred.refresh_token: cred.refresh(Request()) … -
How to get exact value of choice field in django
I have a choice field in Django model ) COMMITTEE_STATUS = ( ("p", "Pending"), ("a", "Active"), ("c", "Completed"), ) but the issue is when I am accessing these data in template I am getting p,a and c instead of actual peening, active and complete -
Finding api documentation flask
Have been given the task to ID all APIs in the source code since the previous dev was fired immediately..now i know that flask or django have certain templates to define API and specify parameters so i intend to write a script to simply look for such patterns , recursively across folders ..is the community aware of any tools / projects which do this across programming languages.. please nite, iam NOT speaking of swagger or api documentation..this tool NEEDs to be able to scan through code and generate necessary API docs -
Cannot assign "<User: Euler>": "Article.authorr" must be a "User" instance
I want to change the model field from the charfield to the user's forignkey And I do not want my information to be deleted First I added the fields, then I transferred the data, then I deleted the previous fields def change_names_of_field(apps, schema_editor): Article = apps.get_model('blog', 'Article') article = Article.objects.all() for s in article: **s.authorr = User.objects.get(username=s.author)** if Category.objects.filter(title=s.category).values_list("title", flat=True) == []: Category.objects.create(title=s.category) s.categoryy = Category.objects.filter(title=s.category) s.update = s.created s.published = s.created s.status = "p" s.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0002_alter_article_created'), ] operations = [ migrations.AddField( model_name='Article', name='authorr', field=models.ForeignKey(User,on_delete=models.CASCADE,null=True), preserve_default=False, ), ... ... ... migrations.RunPython( change_names_of_field, ), ... ... ... -
bad request in django when unity send it but its OK when is use postman
I develop a service for our online games. when I'm testing by Postman everything is OK but when I'm tried test by end-user application djago send Bad_request 400 40. what happened ?! -
How to create ManyToMany object in django view?
I am trying to create product api. Here I have delivery_option filed which has a manytomamy relation with my product. when I am trying to create product I am getting some error like TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use delivery_option.set() instead. How to create the many to many field in django? @api_view(['POST']) @permission_classes([IsVendor]) def vendorCreateProduct(request): data = request.data user = request.user.vendor print(data['deliveryOption']) product = Product.objects.create( user=user, name=data['name'], old_price = data['price'], discount = data['discount'], image = data['avatar'], countInStock = data['countInStock'], subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0], description=data['description'], delivery_option = data['deliveryOption'], ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) -
GKE Django MySQL is not accessible during rolling update
I have Django application deployed in GKE. (Done with this tutorial) My configuration file: myapp.yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp labels: app: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp-app image: gcr.io/myproject/myapp imagePullPolicy: IfNotPresent --------- - image: gcr.io/cloudsql-docker/gce-proxy:1.16 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=myproject:europe-north1:myapp=tcp:3306", "-credential_file=/secrets/cloudsql/credentials.json"] apiVersion: v1 kind: Service metadata: name: myapp labels: app: myapp spec: type: LoadBalancer ports: - port: 80 targetPort: 8080 selector: app: myapp settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DATABASE_NAME'], 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': '127.0.0.1', 'PORT': os.getenv('DATABASE_PORT', '3306'), } Now, when I do rolling update or via kubectl rollout restart deployment myapp or kubectl apply -f myapp.yaml kubectl get pods is in the following state: NAME READY STATUS RESTARTS AGE myapp-8477898cff-5wztr 2/2 Terminating 0 88s myapp-8477898cff-ndt5b 2/2 Terminating 0 85s myapp-8477898cff-qxzsh 2/2 Terminating 0 82s myapp-97d6ccfc4-4qmpj 2/2 Running 0 6s myapp-97d6ccfc4-vr6mb 2/2 Running 0 4s myapp-97d6ccfc4-xw294 2/2 Running 0 7s I am getting the following error for some amount of time during rolling out: OperationalError at / (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") Please advise how can I ajust settings to have rollout without a downtime/this error -
How to solve Django send_mail schedule problem?
I am using Pythonanywhere (PA) and like to use the PA's task scheduler to send scheduled emails. I made a ne file called: weeklyemailmm.py. The email settings in the setting.py works with other emailing stuff on my site. What am I doing wrong? I ty to use the code below: from django.core.mail import send_mail import datetime from django.conf import settings settings.configure(settings, DEBUG=True) today = datetime.date.today() weekday = today.weekday() subject = 'New weekly email' message = 'Hi there!' if (weekday == 2): try: send_mail( 'Subject here', 'Here is the message.', 'from@gmail.com', ['to@gmail.com'], fail_silently=False, ) print('It is Wednesday, email sent') except: print('It is not Wednesday') else: print('Email does not sent') On this way I always get It is not Wednesday. If I delete the try-except part and outdent it says: RecursionError: maximum recursion depth exceeded while calling a Python object If I delete the settings.configure(settings, DEBUG=True) that could be possibly wrong it say: django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
hi please help im trying to create a form view
hi everyone as i said im trying to create a Formview wait.. first at all where should i create the Meta class because i saw a page first where it create the Meta class inside the models but the i saw another page where it says that i should create in my forms so i did that also and then i say another page where it say that it must register the models in admin because i also hade that error where it show an error if i mis an s in Meta class models descibtion so heres my error: File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 23, in check_resolver return check_method() File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 625, in urlconf_module return import_module(self.urlconf_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>", … -
How to post PDF to an API in Django?
I create a project with Django. I need a PDF upload page for my project. I created a form for that. class PDFTestForm(forms.ModelForm): pdf = forms.FileField(label=_(u"Please Upload the PDF file"), required=False) class Meta: model = TestPDF fields = ('pdf',) But I need the post the PDF to a API. This API is not related to my project. def mytestview(request): form = PDFTestForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): pdf = form.save() r = "https://api.myaddress.com/pdf" else: messages.error(request, 'Please, upload a valid file.') context = { 'form': form } return render(request, 'testthat.html', context) How can I post my uploaded PDF to this API address? -
React Multiselect package is sending [object, Object] instead of key and value
I am trying to pass data in my django backend from react frontend. I am able to pass the data using some Multiselect from react. But the problem is I am sending label and value but when I try to print my data in frontend and check the data what it is passing I got the result like [object Object] instead of [mylabel MyValue] and I just want to pass the option value. I am new to react so don't know much about setState things. Can someone help me to do this? Or any other easy way to pass multiple data in my api it would be much appreciated like I select HD and SD then in my backend I should get both value. #This is my react code check the deliveryOption, setDeliveryOption import axios from "axios"; import React, { useState, useEffect } from 'react' import { LinkContainer } from 'react-router-bootstrap' import { Table, Button, Row, Col, Form } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import FormContainer from '../components/FormContainer' import { MultiSelect } from "react-multi-select-component"; import Select from 'react-select'; const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/create/products/"; const options = [ { label: "HD 🍇", … -
How to direct a user from a page in a Django app to a static web page found on the same server
Assume that I have my Django app running at '/var/project/my_django_project/' and I want to direct the user to '/var/project/static_website/index.html' when a button is clicked in a template located at '/var/project/my_django_project/templates/my_template.html'. How can I achieve this? -
login with phone number in django
I get this error when making changes self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' model from django.db import models from django.contrib.auth.models import AbstractUser class Userperson(AbstractUser): gender_choice = [ ('M', 'male'), ('F', "female") ] roles = [ ('seller', 'Seller'), ('shopper', 'Shopper'), ('serviceman', 'Serviceman') ] fullname = models.CharField(max_length=100, verbose_name="Fullname") phone = models.CharField(max_length=20,verbose_name="Phone",unique=True) image = models.ImageField(upload_to="userphoto/fullname", blank=True, null=True, verbose_name="userPhoto") phone_auth = models.BooleanField(default=False) gender = models.CharField(choices=gender_choice, blank=False, null=False, max_length=50) role = models.CharField(choices=roles, max_length=50) # ? USERNAME_FIELD = 'phone' #REQUIRED_FIELDS = ['fullname'] admin from django.contrib import admin from .models import Userperson @admin.register(Userperson) class personadmin(admin.ModelAdmin): list_display = ['fullname', 'phone', 'image', 'phone_auth'] What should I do to solve the problem? -
COMBINING DJANGO QUERYSETS WITH RELATED FOREIGN KEY FIELS
I have three models which are listed below. In a view called workstation view I need to show all products that match two criteria. I need to show all "Dispensings" where the status is "Pending" and the "Dispensing.product.form" equals the allocated workstation form. I am not sure of the quickest and best way to do this. The code is below app name = "prescriptions" class Dispensing(models.Model): class Status(models.TextChoices): RECEIVED = 'A', _('Order received') OWING = 'W', _('Owing') PAYMENT = 'C', _('Invoice sent') PENDING = 'D', _('In production') #CHECKED = 'C', _('Approved for release by pharmacist') DISPATCHED = 'E',_('Dispatched') script_status = models.CharField(max_length=2,choices=Status.choices,default=Status.RECEIVED,) product = models.ForeignKey(Product,related_name='product',on_delete=models.CASCADE) app_name = 'product class Product(models.Model): form = models.ForeignKey(Form, related_name='products', on_delete=models.CASCADE, blank=True,null=True) app name = "equipment" class Workstation(models.Model): created_on = models.DateField(default=((timezone.now())+(datetime.timedelta(hours=11))),blank=True,null=True) name = models.CharField(max_length=200, db_index=True, blank=True,null=True) asset_id = models.CharField(max_length=200, db_index=True, blank=True,null=True) product_types = models.ForeignKey(Form,related_name='forms',on_delete=models.CASCADE,blank=True,null=True) app name = "list" class Form(models.Model): description = models.CharField(max_length=255) I have removed the unnecessary fields. Both dispensing and Workstation are linked separately to Form. I need to query all dispensings where dispensing.product.form equals workstation.form. I just can't think of a simple query to do this. The view is below: class WorkstationDetailView(DetailView): model = Workstation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['workstations'] = Workstation.objects.all() … -
Can anyone please help me figure out what is causing this error
enter image description here My app shows error after build succeeded, and the log file shows an error from the procfile -
foreign key in django and postgresql ,
i am trying to export the model from the database which is postgresql to an Excel file and the issue here is the Foreign key fields exported as an ID integer , How can i change it to string for enter image description here -
Im trying using class modelForm in django
My models.py from django.db import models # Create your models here. class modelBlog(models.Model): title = models.CharField(max_length=200) description = models.TextField() body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) def __str__(self): return ('{}.{}').format(self.id, self.title) class comment(models.Model): blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE) name = models.CharField(max_length=200) komentar = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) My forms.py from .models import modelContact, comment from django import forms class CommentForm(forms.ModelForm): class meta: model = comment fields = [ 'name', 'komentar', ] widgets = { 'name': forms.TextInput(attrs={'class':'form-control'}), 'komentar': forms.Textarea(attrs={'class':'form-control'}), } AND views.py def detail(request, id): blog = modelBlog.objects.get(id=id) form = CommentForm() if request.method == 'POST': nama = request.POST['nama'] comment = request.POST['komentar'] new_comment = blog.comment_set.create(name=nama,komentar=comment) new_comment.save() messages.success(request, 'Komentar berhasil ditambahkan') return redirect('blog:detail', id) judul = blog.title context = { 'title':judul, 'blog':blog, 'form':form } return render(request, 'blog/detail.html', context) i got error ValueError at /blog/1/ ModelForm has no model class specified. Request Method: GET Request URL: http://localhost:8000/blog/1/ Django Version: 4.0.2 Exception Type: ValueError Exception Value: ModelForm has no model class specified. -
One test database is not created when two database are used
I have two databases to use in django project. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": "mydb", "USER": "root", "PASSWORD": config("DB_PASSWORD"), "HOST": "127.0.0.1" "PORT": 3306, 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'TEST': { 'NAME': 'test_{0}'.format(config("DB_NAME")), }, }, 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mydb_extern", 'USER': "root", 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': "127.0.0.1", 'PORT': 3306, } } I am using two datbases mydb and mydb_extern When I am testing with python manage.py test, it makes test_mydb However there comes error like django.db.utils.OperationalError: (1051, "Unknown table 'mydb.t_basic'") So problem is, t_basic is exist on in mydb_extern not in mydb testscript copy the mydb to test_mydb testscript try to search the t_basic from test_mydb Why does it happen? and why testscript doesn't make the second database? -
Error H12 "Request timeout" on heroku for django application
I am getting the H12 "Request timeout" error when I am working with large data in a CSV file and when the data in the CSV file is less the app is working fine. The logs that I am getting is : 2022-02-27T06:05:20.963369+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/" host=youtube-channel-list.herokuapp.com request_id=36c5fe9b-21c5-40de-8804-a75786dfd32e fwd="27.97.65.233" dyno=web.1 connect=0ms service=30699ms status=503 bytes=0 protocol=https I updated my Procfile also as: web: gunicorn channelList.wsgi --timeout 120 --keep-alive 5 --log-level debug --log-file - But still, the same error is coming. What exactly do I need to do? If you need more information, I am ready to provide it.