Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I pass an emoji as POST request to Django and store it in MySQL database
I am developing a chat application in Django. I am using MySQL database to store data. I want to store emojis also in the database. Can someone help, please? -
Django logging maxbytes
I am using the following snippet in django settings.py for logging. As you can see, currently there is a maxbytes variable under handlers. Is it possible to keep no limit at all for the log file ? If i remove maxbytes line, will django automatically set no limit for log file? because size of log will increase at a huge rate for my app on a daily basis. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s|%(name)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'applogfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/home/sai_avinash/Documents/refactor/unityapp/unity/media/myproject.log', 'maxBytes': 1024*1024*15, # 15MB 'backupCount': 10, 'formatter': 'simple', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { djanngo': { 'handlers': ['applogfile', 'console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), } } } -
"Error during WebSocket handshake" when hosted on Heroku
I'm making a chat server on Django and atm trying to implement websockets. It works fine locally but whenever I launch it on Heroku, websocket is unreachable. Here's my client script: var loc = window.location var ws_start = 'ws://' if (loc.protocol == 'https:'){ ws_start = 'wss://' } var endpoint = ws_start + loc.host + loc.pathname var socket = new WebSocket(endpoint) Full error code: WebSocket connection to 'wss://my-app.herokuapp.com/chat' failed: Error during WebSocket handshake: Unexpected response code: 500 I've seen a variety of similar questions already, and they are either left unanswered or delve into dealing with SSL certificate. There's one answer that would potentially save me (and other folks) alot of frustration if anyone was to confirm it's true. It's quite old and there's no feedback after it was posted: https://stackoverflow.com/a/45173822/7446564. I will gladly provide any of my code if necessary but the real problem (based on other SO questions) is understanding the source of this error. Is this an error in my code, some SSL-shenanigans or simply a matter of switching to paid dynos? -
Redirect Django not working and not redirecting
views.py: def showLoginPage(request): if request.method == "POST": try: body_unicode = request.body.decode('utf-8') if 'csrfmiddlewaretoken' not in body_unicode: body = json.loads(body_unicode) user_obj = AuthenticateUser() user_obj.validate_user(body) c={} c.update(csrf(request)) return redirect('http://abchostname/mainPage/') # return redirect('/mainPage') This is another url which i want to redirect after # successful login except Exception as exe: print("Inside Exception : ",exe) raise else: print("Inside else {}".format(request.method)) return render(request, 'login.html') @login_required(login_url="/login/") def showMainPage(request): return render(request, 'mainPage.html') I want to redirect after a successful login, I see the login is getting successful and it is hitting by backend correctly as well. [07/Jul/2020:06:59:29 +0000] "GET /login/ HTTP/1.1" 200 2082 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362" [07/Jul/2020:06:59:36 +0000] "POST /login/ HTTP/1.1" 200 2081 "http://abchostname/login/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362" [07/Jul/2020:06:59:36 +0000] "POST /login/ HTTP/1.1" 302 306 "http://abchostname/login/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362" In the third option 302 status code is shown which means it is redirecting. I need some help on this. -
Django, Bootstrap toast appears whenever I refresh the page instead of when needed
I want to make a toast appear only when a file has been processed. Currently I check from the model.py whether another file exists or not. If it does, the file has been processed. Else not if not. def status(self): if os.path.exists(...)): return "processed" else: return "unprocessed" I'm not sure if it's right to check from model.py. As for my HTML file, I have set the following. {% for td in user.userlist.all %} {% if td.status == 'processed' %} <div class="toast" drole="alert" data-autohide="false" ... > <div class="toast-header"> <strong class="mr-auto">{{ td.status }}</strong> <small class="text-muted">just now</small> <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="toast-body"> The file was {{ td.status }} </div> </div> {% endif %} {% endfor %} This works fine whenever it detects the word 'process', but the toast appears everytime I refresh since it detects 'process' repeatedly. I want the toast appear only once when the file has actually processed instead of looking for the word 'process'. Any suggestions are highly appreciated. -
Get list value by comparing values
I have a list like this: data.append( { "type": type, "description": description, "amount": 1, } ) Every time there is a new object I want to check if there already is an entry in the list with the same description. If there is, I need to add 1 to the amount. How can I do this the most efficient? Is the only way going through all the entries? -
Python/Django recursive model into tree structrue dict
I have a Django model class Category(models.Model): parent = models.ForeignKey('Category', null=False, blank=False) category_name = models.CharField(max_length=55,null=False, blank=False) status = model.BooleanField(default=True) I want to create recursive which return tree structure dict. e.g [ { 'category_name': 'vehical', 'id': 1, 'children' : [ { 'category_name': 'cars', 'id': 11, 'children': [ { 'category_name': 'sport cars', 'id': 20 } ] } ] } ] >>> category = Category.objects.all() >>> get_tree(category) -
Can i deploy my django app to godaddy.com
just started coding at 39yrs( i've always dreamt about it) Being overwhelemed with all the online tutorials im trying to make progress every day( 1 week now) I have a simple hosting on godaddy and would like to deploy my practise apps there so my friends can critisize my work( i have some dev buddies) But for the life of me i cannot get that to work. I cant find the "terminal" like in the tutorials. Edit: I am trying to learn Python django if thats the correct way to say it. I'm using vscode to code -
Django allauth url fetch from react calls signup view form. How can I just send the data to the API endpoint?
I am using React as a standalone SPA connecting to a Django backend with allauth to manage authentication. If I type in the allauth UR on my local browser (192.168.86.28:8000/accounts/signup/ or 127.0.0.1:8000/accounts/signup/), it brings me to a form I can populate with my custom fields. I can enter in the information and it completes the signup correctly in my database. The form looks ugly, however, so I would like to implement my own frontend form using react. A fetch call with the data should simply post it to the database, but instead the fetch call to that URL brings up the form! How can I change this so the URL will instead send the data to my database? mysite/urls.py from django.contrib import admin from django.urls import path from django.urls import include from django.conf.urls import url from allauth.account.views import confirm_email from allauth.account.views import SignupView urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), path('accounts/signup/', SignupView.as_view(), name="account_signup"), path('accounts/', include('allauth.urls')), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), ] mysite/settings.py # rest_framework authentications and permissions REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSS': [ 'rest_framework.authentication.TokenAuthentication' ] } # cors CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://192.168.86.28:3000', 'http://192.168.86.33:3000', ) CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '[::1]', "192.168.86.33", "192.168.86.28", ] # … -
Page not found 404 - Django
I'm a newbie to Django and I know this probably has been asked alot of times. So basically what's happening is when I try to create a new project and whenever I'm trying to run my server, by default it's opening http://127.0.0.1:8000/catalog/ and not http://127.0.0.1:8000/. Even if I run the server with my other projects, I'm facing the same error. I followed this django basics tutorial on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website Idk but somehow I think it's default address is set to http://127.0.0.1:8000/catalog/. Is there any way I can change it? Regards -
Django NoReverseMatch when using django NamespaceVersioning
I'm trying to implement versioning in django. My project urls.py looks like: from backend.st_site import urls as site_urls router = routers.DefaultRouter() urlpatterns = [ url(r"^v1/sites/", include((site_urls, "sites"), namespace="v1")), url(r"^v2/sites/", include((site_urls, "sites"), namespace="v2")), ] In st_site/urls I got following url: site_list = SiteView.as_view({"get": "list", "post": "post"}) url(r"^$", site_list, name="site-list"), in my settings/base.py I added: REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", "DEFAULT_VERSION": "v1", } This works for the default version (v1). If I run a test class, it works. But when I try to test a v2 version test like: def test_get_all_sites_admin_version_2(self): self.client.force_login(self.admin_user) url = reverse("v2:admin-site-list") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) I got following error: django.urls.exceptions.NoReverseMatch: Reverse for 'admin-site-list' not found. 'admin-site-list' is not a valid view function or pattern name. Do I need to configure something else? This for example does work: self.client.force_login(self.admin_user) url = reverse("admin-site-list") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) -
Django sitemap, google seo couldn't fetch
I would like to ask some advice for my website. I've made a sitemap with django(sitemap) But when i go to the seo and register the sitemap they told me that they couldn't fetch it. I've tried to wait few days as some site suggest but it do not change anything. Does anyone have a possible solution to my problem ? Thanks you in advance. -
The value of 'list_display[5]' must not be a ManyToManyField
I am trying to create manytomany fields in one of the class, I am getting an error "The value of 'list_display[5]' must not be a ManyToManyField" Need Help, Thanks in advance :) class ShiftConfig(models.Model): description = models.CharField(max_length=30) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.id) + ' : ' + str(self.start_time) class FaultConfig(models.Model): description = models.CharField(max_length=30) message = models.ForeignKey(Message, null=True, on_delete=models.SET_NULL) recipients = models.ForeignKey(UserGroup, null=True, on_delete=models.SET_NULL) alert_time = models.DurationField(default=timedelta(0.0001)) repeat = models.PositiveSmallIntegerField() escalated_fault = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, blank=True) def __str__(self): return str(self.id) + ' : ' + str(self.description) Here is the concerned class. class WorkStation(models.Model): name = models.CharField(max_length=30) location = models.CharField(max_length=30) department= models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) current_user=models.ForeignKey(User, null=True, on_delete=models.SET_NULL) allowed_fault_configs = models.ManyToManyField(FaultConfig, through='WFMembership', through_fields=('workstation', 'fault_config')) allowed_shift_configs = models.ManyToManyField(ShiftConfig, through='WSMembership', through_fields=('workstation', 'shift_config')) def __str__(self): return str(self.id) + ' : ' + str(self.name) class WFMembership(models.Model): workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE) fault_config = models.ForeignKey(FaultConfig, on_delete=models.CASCADE) class WSMembership(models.Model): workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE) shift_config = models.ForeignKey(ShiftConfig, on_delete=models.CASCADE) -
Strange behaviour while using Field lookup in Django
I noticed a strange behavior in in Field lookup while trying up challenge yourself section of MDN Django Tutorial. I wanted to modify view.py to generate counts for genres and books that contain a particular word (case insensitive), and pass the results to context. I tried to achieve this by following code: # Filtering the word 'comedy' from 'genre' attribute(ManytoManyField) present in 'Book' class num_word_in_geners = Book.objects.filter(genre__in='comdey').count() Surprisingly, this throws a ValueError invalid literal for int() with base 10: 'c' So, I did a workaround by replacing 'comedy' with inner_qs: inner_qs = Genre.objects.filter(name__icontains='comedy') num_word_in_geners = Book.objects.filter(genre__in=inner_qs).count() Now more surprisingly, this works! But why? I suspect there is something I don't understand behind these words in Django docs: In a given iterable; often a list, tuple, or queryset. It’s not a common use case, but strings (being iterables) are accepted. Help me clear this query. -
Can't connect to WebSocket Nginx in my django app chat on deployment I'm use to Nginx and Supervisor
Hi everyone,I need help with this issue as soon as possible. I'm trying to use WebSocket for my django project. I have an app chat in django but i cant get it to connect in deployment, these are my config files and the error . I'm using nginx and supervisor erro in browser settings.py from InclusionEducativa.settings import * import os import dj_database_url from django.urls import reverse_lazy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '0r9u3z=w6j2mq$vbus@(ppx5%f+c63pgmsnum10=!_jvl7i@2h' DEBUG = True ALLOWED_HOSTS = ['*'] ADMINS = [('Jafet', 'jafetandres@hotmail.com')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'InclusionEducativa.Apps.GestionSistema', 'InclusionEducativa.Apps.AppDocente', 'InclusionEducativa.Apps.AppRepresentante', 'InclusionEducativa.Apps.AppExperto', 'InclusionEducativa.Apps.automata', 'django_chatter', 'channels', 'notifications', 'InclusionEducativa.Apps.chat' ] 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 = 'InclusionEducativa.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'InclusionEducativa/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'InclusionEducativa.wsgi.application' ASGI_APPLICATION = 'InclusionEducativa.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('127.0.0.1', 6379)], }, }, } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'InclusionEducativa.db', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = "es-es" TIME_ZONE = 'America/Guayaquil' USE_I18N = True USE_L10N … -
I use meta for displaying keywords in meta tag but it shows empty on inspecting base.html but in meta.html it shows keyword
//models.py ''' from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.template.defaultfilters import slugify from django.contrib.contenttypes.fields import GenericRelation from meta.models import ModelMeta class Post(ModelMeta,models.Model): title = models.CharField(max_length=100) h_overview = models.CharField(max_length=300) content = RichTextField(blank=True,null=True) publish=models.BooleanField(default=False,blank=True) slug=models.SlugField(max_length=200,unique=True,null=True,blank=True) class Meta: ordering=['-rate'] def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) _metadata={ 'keyword':'keyword', } ''' //views.py ''' def article_detail_view(request): obj = get_object_or_404(Post) template_name = ['appnews/base.html'] context = {} context['object'] = obj context['meta'] = obj.as_meta() return render(request, template_name, context) ''' //meta.html ''' {% block meta_extend %} <meta name="description" content="{{meta.keyword}}"> {% endblock %} ''' // base.html ''' <html> <head> {% include 'meta.html' %} </head> <body> </body> </html> ''' -
Django Apache2 error - Truncated or oversized response headers received from daemon process [raspberry pi]
I have a django app I have created that runs fine with manage.py runserver and it was working fine before I started working with opencv and imported numpy. I can still use runserver, but I can no longer use localhost in the browser. When I look at the log (/var/log/apache2/error.log), I see the following error: Truncated or oversized response headers received from daemon process 'myproject' : [path_to_my_project]/wsgi.py. When I type in localhost into the browser I get the following: I have searched for answers but they haven't helped: I've tried added WSGIApplicationGroup ${GLOBAL} to /etc/apache2/sites-available/000-default.conf NOTE: I placed it below the WSGIAlias line but not within the <Directory></Directory> tags. 2. I've tried adjusting the timeout in /etc/apache2/apache2.conf (I believe the default was 400) 3. I've seen a lot of suggestions say it's because of numpy and similar python C extension modules, and some suggest alternates that include a binary. However I don't see an option like that for numpy. Is there something I'm doing wrong? None of the common fixes seem to be working for me. Note: I have restarted the pi and the apache2 service for each attempt, but still no luck. -
How to handle database connection pooling in django with postgresql
I have a django application every api hit in django creating one db connection to handle that request and basically this is an overhead as this is creating several connections if there are multiple requests to handle so I want to have db connection pooling or persistent connection for efficient handling. I have gone through the django doc for this as there is CONN_MAX_AGE parameter but what should be the best way to manage open db connections. -
django create a coupon
I'm trying to create a function where when the user clicks submit, a random 6 digit character code is generated and stored in the database and at the same time code with the same code id in the database is created in stripe. So far I'm able to generate random codes in the database. But for stripe I have no idea what value should I give to the id field in stripe create coupon. views.py def create_coupon(request,pk): code=Code.objects.get(id=pk) form = Coupon_Code(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() coupon = stripe.Coupon.create( duration='forever', id=code, percent_off=20, max_redemptions=100, ) context = { 'form':form } return render(request, "coupon.html", context) forms.py from django.forms import ModelForm from django.contrib.auth.models import User from django import forms from .models import Code class Coupon_Code(ModelForm): class Meta: model = Code fields = '__all__' models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from .utils import code_generator from datetime import datetime, timedelta def compute_default_to(): return datetime.now() + timedelta(days=20) class Code(models.Model): code = models.CharField(max_length=10, unique=True, blank=True) valid_from = models.DateTimeField(default=datetime.now, blank=True) valid_to = models.DateTimeField(default=compute_default_to) discount = models.IntegerField(default=15, validators=[MinValueValidator(0),MaxValueValidator(100)]) active = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.code is None or self.code == "": self.code = code_generator() super(Code, self).save(*args, … -
About Django and static files in deployment from pythonanywhere
what can I do if I want to collectstatic again in pythonanywhere? I did it because I remove oneline in my remote repository and when I collectstatic it didn't work (new styles don't apply) so what can I do? I'm not an speaker of English. -
"GET /blog/ HTTP1.1" 200 1111
I am running a simple Django blog it is running i can see the list.html but when I click on a specific post it wont show the detail.html render. Where could the error be. IN the HTML files ? in the URL or Views files. I am using these files https://github.com/PacktPublishing/Django-3-by-Example/blob/master/Chapter01/mysite/ It is supposed to allow me to click on a post and see the detailed "view" I checked all my files syntax looks ok. -
the {% for item in items %} part of page doesnot work
while running the server the {% for item in items %} part in cart.html is not displayed model.py * *from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = … -
How can I make this "class-based view" work?
I have been learning Django and now working on the class based view. I typed exactly as both official documentation and the book for beginner mentioned, but the code didn't work as they explained. Please teach me why this doesn't work. The command prompt says "File "C:\Users\yuto1\Desktop\book_study\Tabelog\urls.py", line 9, in path("list/", ReviewList.as_view(), name="ReviewList"), AttributeError: 'function' object has no attribute 'as_view'" urls.py from django.urls import path,include from Tabelog import views from Tabelog.views import ReviewList app_name = "Tabelog" urlpatterns = [ path("lp/", views.lp,name="lp"), path("list/", ReviewList.as_view(), name="ReviewList"), path("detail/<str:store_name>",views.detail,name="detail"), path("form/",views.form,name="form"), path("form/fix/<str:pk>",views.form_fix,name="form_fix") ] views.py from django.shortcuts import render,redirect,get_object_or_404 from Tabelog.models import Tabelog from Tabelog.forms import CreateTabelogForm from django.views.generic import ListView # Create your views here. def lp(request): return render(request,"Tabelog/lp.html") def ReviewList(ListView): model = Tabelog def detail(request,store_name): detail = Tabelog.objects.get(store_name = store_name) context = { "detail":detail, } return render(request,"Tabelog/detail.html",context) def form(request): if request.method == "GET": form = CreateTabelogForm() context = { "form":form } return render(request,"Tabelog/form.html",context) else: form = CreateTabelogForm(request.POST or None) if request.method == "POST" and form.is_valid(): form = CreateTabelogForm(request.POST) form.save(commit=True) return redirect("Tabelog:list") else: form = CreateTabelogForm() context = { "form":form } return render(request,"Tabelog/form.html",context) def form_fix(request,pk): review = get_object_or_404(Tabelog,pk=pk) print("success one") form = CreateTabelogForm(request.POST or None,instance=review) print("success two") if request.method == "GET": form = CreateTabelogForm(instance=review) context … -
How to make Django search contains work with uppercase and lowercase?
I have problem with Django Example.objects.filter(text__contains='text here') that only match with same input. I want the search contains feature also works in uppercase and lowercase. I have tried to use Example.objects.filter(text__contains__iexact='text here') and Example.objects.filter(text__iexact__contains='text here') but it's not work. I found another way to search data in database form https://docs.djangoproject.com/en/3.0/topics/db/search/ but it's just for PostgreSQL user. Is there any solution to search for data from the database without using Django 'raw' MySQL query? -
How to request Uptade an item on Django Rest Framework from React-Redux
How can I send an update request to Django Rest API from React-Redux. Which method I have to use? I'm developing this application; https://github.com/bradtraversy/lead_manager_react_django I added a check button to leads. So when a lead completed, I want to set is_completed: true & send an update request to django rest API. There is how I send add leads post request; handleSubmit= e=>{ e.preventDefault(); const { task, tag1, tag2, tag3,is_completed } = this.state; const newTask = {task,tag1, tag2, tag3,is_completed} this.props.addTask(newTask) } addTask action export const addTask = (task) => (dispatch,getState) => { axios.post('/api/tasks/',task,tokenConfig(getState)) .then(res=>{ dispatch({ type : "ADD_TASK", payload : res.data, }); }) .catch(err=>console.log(err)) } //takenConfig function from another js file const tokenConfig = getState=>{ // Get token from redux state const token = getState().auth.token; // Set Headers const config = { headers: { 'Content-Type':'application/json' } } // Add headers config if there is token if (token) { config.headers['Authorization'] = `Token ${token}`; } return config; } my reducer else if (action.type ==='ADD_TASK') { return { ...state, tasks:[...state.tasks, action.payload] } } And its perfectly working. But I couldn't send an update request. I tried axios.post & axios.put methods, always got 400 Bad Request error. I even try override with id parameter in …