Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django malformed views.py or urls.py (redactor app)
I’m trying to write a web app which accepts a website visitor’s input which is a 12 digit “Chuckee Cheese” membership card number and then redacts the first 8 digits and presents the redacted number. I’ve got my template written and the basic logic inside my app’s views.py. The problem now is that after the user enters his or her card number, Django is not processing the user input properly. Like, the redacted number is not being presented and served in the template as intended. Here is a pic on imgur showing my website running on my dev server now. As you can see in that pic, in the web address bar Django receives the ‘ccEntry’ GET Request with ‘123456789102’ as user input. So I guess that kind of works. But below the two lime green h1 tags, Django should show the card number ‘123456789102’ as well as the redacted card number ‘xxxx xxxx 9102’ but instead it’s blank. What is wrong here? As far as I can tell, I believe the problem involves either first two functions inside my redactors views.py or the way my app’s urls.py is arranged. Here is my views.py : from django.shortcuts import render # … -
An issue with posting a reply in the Django website
I am following the tutorial on [Protecting Views][1] and I have trouble understanding the tutorial. When I click the the Reply Button, it does not take me to the link to reply to the topic, and displayed a # in the URL instead. I had to type in the URL to get to that point. And when I posted something, it didn't redirect, and the new topic that I replied to wasn't there. I don't know why this is happening. Here's my forms.py file from django import forms from .models import Topic, Post class NewTopicForm(forms.ModelForm): message = forms.CharField( widget=forms.Textarea(), max_length=4000, help_text='The max length of this field is 4000.' ) class Meta: model = Topic fields = ['subject', 'message'] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['message', ] and here's my urls.py file from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views from accounts import views as accounts_views from boards import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^signup/$', accounts_views.signup, name='signup'), url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^reset/$', auth_views.PasswordResetView.as_view( template_name='password_reset.html', email_template_name='password_reset_email.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), url(r'^reset/done/$', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name='password_reset_confirm'), url(r'^reset/complete/$', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), url(r'^settings/password/$', auth_views.PasswordChangeView.as_view(template_name='password_change.html'), name='password_change'), url(r'^settings/password/done/$', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'), name='password_change_done'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^boards/(?P<pk>\d+)/new/$', views.new_topic, … -
Google Cloud Run not setting X-Forwarded-Proto header correctly on https requests
I have a django application running in Google cloud run, via Docker. By default cloud run accepts connections on both http and https. I would like to redirect the user to the https version but cloud run does not seen to be setting the headers correctly. I have a handler that returns the headers via: json.dumps(request.headers.__dict__['_store']) And the relevant headers returned are: "x-forwarded-proto": ["X-Forwarded-Proto", "http"] But the value http never changes even when I visit the https version of the site. How should django correctly detect http requests on cloud run? I am unable to use SECURE_PROXY_SSL_HEADER to detect and redirect http requests to https as they all appear to be http requests, so you end up in a redirect loop. -
how to declare multiple kwargs in python 3.4?
hi guys I mention like this in Django views.py In my machine python 3.8 and Django 3.0.8 is running serializer = {**nameserializer,**nameserializer,**nameserializer} deployment machine is running in python 3.4 and django 2.0 so please help me to solve this error serializer = {**nameserializer,**nameserializer,**nameserializer} ^ SyntaxError: invalid syntax help me to fix this.. -
Send an email after some time (24hours) in django using django_rq
I have a website where user profile has multiple steps of registry. I would like to send the user an email if the user has completed step 1 but not step 2, 24 hours later than completing step 1. So, after the completion of step 1 I would like to set a task which runs after 24 hours and checks if User.profile_status == completed_step_2, and if this is not the case, send him/her an email asking to complete step 2 of their profile. How can I do that? Thanks in advance. -
Protecting User data and privacy in Django or webapps in general
I am new to web dev. So the scenario is I have a web app where I have user accounts and all login system etc. Now let's say to manipulate the data I have to log in and update, which all happens through views in Django. But ultimately what I have done is provided a single DB account credential. But the problem is with that DB password, all the accounts and data is compromised. So how can this situation be avoided? Like what are the proposed concepts or solutions to safeguard user data from backend? In other words , if for some reason, the person with superuser access to DB can read and manipulate all the user data from the backend. How can this be avoided, as such user data is only private to users alone? As an analogy consider Gmail, where only you can read your mail and anybody with databases access to google simply can't read and manipulate your mails! So what mechanism or concept is used to handle this situation? Such that single DB admin/developer cant blow up/modify all user private data? Thanx in advance for any suggestion or knowledge base! -
Having trouble integrating payment gateway in my django website
I have tried to see this tutorial to make a django E Commerce website.https://www.youtube.com/watch?v=33pnWTslX2E. In this the maker has added PayPal but I want to add Paytm Gateway. My problem is that in the video there is a submitformdata() function which on payment approval saves the form data but I cant do it in paytm integration as It does not give me and javascript code so that I can check the payment status in javascript and then call the submitformdata() accordingly. Please help me in suggesting how to check if the payment is successful in Javascript and the save the form data -
Django reuse class views
i hope this hasn't been asked, but i didn't found a suitable answer for what i was looking for. in my Django Database Model i have a few similar Tables class Manufacturer(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True) deleted_at = models.DateTimeField(null=True) class Elimination(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True) deleted_at = models.DateTimeField(null=True) class Inventory_location(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True) deleted_at = models.DateTimeField(null=True) is there a way to define a general view that creates\updates\list\delete these? maybe with an URL pattern that takes a string of the model as an argument and passes it to the "generalized" view(s). -
Calling a function in the views located in settings.py
Is this possible to call a function located in settings.py? def myfn(): return "hello world" view: from django.conf import settings def my_view(request) print(settings.MYFN()) -
I am trying to save the order but after payment process get success what should I do?
Views.py order = Orders(items_json=items_json, product_name=product_name , name=name, email=email, address=address, city=city, state=state, zip_code=zip_code, phone=phone, amount=amount) order.save(), update = OrderUpdate(order_id=order.order_id, update_desc="The order has been placed") update.save() thank = True id = order.order_id # Request paytm to transfer the amount to your account after payment by user param_dict = { 'MID': 'My Paytm mid', 'ORDER_ID': str(order.order_id), 'TXN_AMOUNT': str(amount), 'CUST_ID': email, 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL':'http://127.0.0.1:8000/shop/handlerequest/', } param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) return render(request, 'shop/paytm.html', {'param_dict': param_dict}) return render(request, 'shop/checkout.html') @csrf_exempt def handlerequest(request): # paytm will send you post request here form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful'), else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'shop/paymentstatus.html', {'response': response_dict}) Models.py class Orders(models.Model): order_id = models.AutoField(primary_key=True) items_json = models.CharField(max_length=5000) product_name = models.CharField(max_length=5000, default="") amount = models.CharField(max_length=90) name = models.CharField(max_length=90) email = models.CharField(max_length=111) address = models.CharField(max_length=111) city = models.CharField(max_length=30) state = models.CharField(max_length=30) zip_code = models.CharField(max_length=6) phone = models.CharField(max_length=10, default="") class OrderUpdate(models.Model): update_id = models.AutoField(primary_key=True) order_id = models.IntegerField(default="") update_desc = models.CharField(max_length=5000) timestamp = models.DateField(auto_now_add=True) def __str__(self): return self.update_desc[0:7] + "..." here are my models and views .py files … -
How i can solve error null value in column "user_id" violates not-null constraint?
I cannot add a new item to the database. An error appears that the user field is not added. I get error null value in column "user_id" violates not-null constraint What is mean? How could I solve this problem? models.py class Company(models.Model): name = models.CharField(max_length=40, blank=True) user = models.ForeignKey(User, verbose_name='User', on_delete=models.CASCADE) #models.IntegerField(blank=True) ... serializers.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=False) class Meta: model=Account fields='__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def create(self, validated_data): # address_data = validated_data.pop('address') # address = Address.objects.create(**address_data) # validated_data['address'] = address user = User.objects.create(**validated_data) class CompanySerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: if self.context['request'].method in ['GET']: self.fields['members'] = serializers.SerializerMethodField() except KeyError: pass class Meta: model = Company fields = '__all__' #('id', 'name', 'description', 'date_created', 'user', 'status', 'theme', 'members') def get_members(self, obj): accounts = Account.objects.filter(id__in=obj.members) return AccountSerializer(accounts, many=True).data class CompanyListSerializer(serializers.ModelSerializer): # memb = serializers.ReadOnlyField(source='members.user') class Meta: model = Company fields = '__all__' -
get_absolute_url id and slug in Django
Hello, I want my URL be like this: site.com/books/details/[id]/[slug] for example: site.com/books/details/3/blind_owl When I click on Book's Name Load Me Nothing. Even Doesn't Show An Error. I Want To Show Me Description Thank you in Advance Model: class Book(TimeStampMixin): id = models.AutoField(primary_key=True) author = models.ForeignKey(to=Author, on_delete=models.PROTECT) book_name = models.TextField() def __str__(self): return '{}'.format(self.book_name) class Details(TimeStampMixin): book = models.ForeignKey(to=Book, on_delete=models.PROTECT) description = models.TextField() slug = models.SlugField(max_length=100, null=True, blank=True) def get_absolute_url(self): return reverse('blog:book_details', args=[self.pk, self.slug]) def __str__(self): return '{}'.format(self.book) URL: urlpatterns = [ path('authors/', views.authors, name='authors'), path('books/', views.books, name='books'), path('books/details/<int:pk>/<slug:slug>/', views.book_details, name='book_details') View: def books(request): book = Book.objects.all() context = {'books': book} return render(request, 'Blog/books.html', context=context) def book_details(request, pk, slug): details = Details.objects.filter(pk=pk, slug=slug) context = {'details': details} return render(request, 'Blog/book_details.html', context=context) Book Template: {% for each in books %} <a href="{{ each.get_absolute_url }}"> Book's Name: {{ each.book_name }} {% endfor %} Book Details Template: {% for each in details %} Description: {{ each.description }} {% endfor %} -
Django: Check if an instance exists before creating
I have two models Purchaser and paymentInvoice, I want to make sure i don't create a duplicate Purchaser object when i'm creating a new paymentInvoice for the same Purchaser individual/instance. Basically i have a Purchaser by the name Becky, so when i want to create an invoice for Becky 1st i want to make sure if the name Becky exists in Purchaser if it does, create paymentInvoice object with Becky taking the field invoiceOwner. If Becky doesn't exist in Purchaser, create an instance of that purchaser in Purchaser then use that instance name to create paymentInvoice object. Models file class Purchaser(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=20) email = models.EmailField(max_length=255, blank=True, null=True) image = models.ImageField(default='default.png', upload_to='customer_photos/%Y/%m/%d/') data_added = models.DateField(default=datetime.date.today) def __str__(self): return self.name class paymentInvoice(models.Model): invoiceNo = models.CharField(max_length=50, unique=True, default=increment_invoice_number) invoiceOwner = models.ForeignKey(Purchaser, on_delete=models.CASCADE, related_name="invoice_detail") product = models.CharField(max_length=50, blank=True) date = models.DateField(default=datetime.date.today) quantity = models.PositiveSmallIntegerField(blank=True, default=1) payment_made = models.IntegerField(default=0) def __str__(self): return self.invoiceOwner.name Serializers file class paymentInvoiceSerializer(serializers.ModelSerializer): invoiceOwner = purchaserSerializer(many=False) invoiceOwner = serializers.CharField(source='invoiceOwner.name') class Meta: model = paymentInvoice fields = '__all__' def create(self, validated_data): purchaser_data = validated_data.pop("invoiceOwner") purchaser, _ = Purchaser.objects.get_or_create(**purchaser_data).first() validated_data.update({"invoiceOwner": purchaser}) return paymentInvoice.objects.create(**validated_data) POST request in Postman for the model paymentInvoice { "invoiceOwner":"Becky", "product": "Lix", "quantity": 1, "payment_made": … -
SyntaxError when launching a newly created Django application
I just created a project with Django, let me show you how I did it (with the voice of Wix ads ;)): django-admin startproject portfolio But when I launch my application I get a SyntaxError. So I don't remember doing anything with the code: (dja_env) C:\Users\antoi\Documents\Programming\Django\portfolio>py manage.py File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax Here's the guilty script: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "portfolio.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) I thought the cause was the python version but it seems that the problem is also with python3: (dja_env) C:\Users\antoi\Documents\Programming\Django\portfolio>py -V Python 3.8.5 (dja_env) C:\Users\antoi\Documents\Programming\Django\portfolio>py manage.py File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax -
Django REST API endpoint for specific url
Im trying to create an endpoint for a post and its comments in the following format: /posts (view all posts) /posts/{id} (view post by id) /posts/{id}/comments (view comments for a post) The first 2 work, but for the last one I have /comments rather than the url i would like and I am not sure how to go about that, I think I need to change my models for it. My current models (its using default Django User): class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class PostComment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.post.title And urls: router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'posts', views.PostViewSet) router.register(r'comments', views.PostCommentViewSet) -
Calling django ajax gives me a 405(Method Not Allowed:) error
I have a question Calling django ajax gives me a 405(Method Not Allowed:) error The error message doesn't tell me why. The request itself seems to be the cause of the problem. if you know what's the problem for this problem thanks for let me know~! ajax $('body').on('click', '.skill_search_button', function (e) { e.preventDefault(); window.history.pushState("", "", '/wm/myshortcut/') const search_word = $(".skill_input_box").val(); console.log("search_word : " + search_word); $("input:radio.search").each(function () { if (jQuery(this).is(":checked")) { search_option = this.id; } else { // alert("check") } }); $.ajax({ type: "POST", url: 'search_by_id_and_word/', data: { 'search_word': search_word, 'search_option': search_option, 'page_user': "{{page_user}}", csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (result) { window.history.pushState("", "", '/wm/myshortcut/') $("#wm_list_area_for_popup").html("") $("#wm_list_area_for_popup").append(result) } }); }); url path('myshortcut/search_by_id_and_word/' , views.searchSkilNoteViewByIdAndWord.as_view(), name="search_by_id_and_word"), view class searchSkilNoteViewByIdAndWord(ListView): model = MyShortCut paginate_by = 10 template_name = 'wm/MyShortCut_list_for_search.html' def get_queryset(self): if request.method == "POST" and request.is_ajax(): search_user_id = request.user search_word = request.POST['search_word'] search_option = request.POST['search_option'] print("search_user_id : ", search_user_id) print("search_word : ", search_word) print("search_option : ", search_option) user = User.objects.get(username=search_user_id) qs = MyShortCut.objects.filter(Q(author = user)).filter(Q(title__icontains=search_word) | Q(content1__icontains=search_word) | Q(content2__icontains=search_word)).order_by('-category') return qs else: qs = MyShortCut.objects.filter(Q(author = user)).filter(Q(title__icontains=search_word) | Q(content1__icontains=search_word) | Q(content2__icontains=search_word)).order_by('-category') return qs -
Django Social Widgets doesn't work django==3.0.8
Hi Today I was trying to add some Social Widget on my page and I took this error "@register.assignment_tag AttributeError: 'Library' object has no attribute 'assignment_tag'" I searched on net and I found that "https://github.com/mgaitan/waliki/issues/156" How can I handle this problem thank you for your time -
heroku django tunnel shocket error at the time of creating app or login
When I login heroku or create heroku app in my project folder then heroku generate error. but when i create app in my home directory this works fine. I installed heroku on my ubuntu 18.04 and I trying to deploy my django project and usind postgres database. Please help me to solve this error. (DjangoEnv) kamran@kamran-HP-245-G5-Notebook-PC:~/Desktop/Django/professional/blog$ heroku create blog Creating ⬢ blog... ! ▸ ERR_SOCKET_BAD_PORT: Port should be >= 0 and < 65536. Received null. (DjangoEnv) kamran@kamran-HP-245-G5-Notebook-PC:~/Desktop/Django/professional/blog$ heroku login heroku: Press any key to open up the browser to login or q to exit: Error: tunneling socket could not be established, cause=connect ECONNREFUSED 91.213.23.110:8080 Code: ECONNRESET Error: tunneling socket could not be established, cause=connect ECONNREFUSED 91.213.23.110:8080 (DjangoEnv) kamran@kamran-HP-245-G5-Notebook-PC:~/Desktop/Django/professional/blog$ (DjangoEnv) kamran@kamran-HP-245-G5-Notebook-PC:~/Desktop/Django/professional/blog$ heroku create blog Creating ⬢ blog... ! ▸ ERR_SOCKET_BAD_PORT: Port should be >= 0 and < 65536. Received null. (DjangoEnv) kamran@kamran-HP-245-G5-Notebook-PC:~/Desktop/Django/professional/blog$ -
Deploying DjangoREST+React project on a single google cloud app engine instance. Is it possible?
I have a Django backend that communicates with the React.js based frontend using REST APIs (made using DjangoREST Framework). Up until now all the similar projects that I have deployed on gcloud use two different gcloud projects/app engine instances, one for django and the other for react. This time I'm constrained to use a single app engine instance. Is it possible to deploy both the react and django components together? I am aware we can serve react as static files using django, but then would there be a performance decrease? And I still need to be able to access django admin. -
Overwriting AbstractClass fields with mypy and Django
In our project we subclass the AbstractUser model from Django: class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=50) last_name_prefix = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50) registered_on = models.DateTimeField(default=now, editable=False) organizations = models.ManyToManyField( "Organization", through="UserOrganization" ) USERNAME_FIELD = "email" REQUIRED_FIELDS: List[str] = [] def __str__(self): if not self.last_name_prefix: return f"{self.first_name} {self.last_name}" return f"{self.first_name} {self.last_name_prefix} {self.last_name}" We want to remove the username field and as specified in the Django docs you do this by setting the field to None. However, we also use mypy, and it complains that the None type is not compatible with the values it expects for a charfield: error: Incompatible types in assignment (expression has type "None", base class "AbstractUser" defined the type as "CharField[Union[str, int, Combinable], str]") I also tried removing the field with delattr which worked, but wasn't picked up by Django migrations. I know it's possible to use '# type: ignore' but is there any proper way to fix this (other than rewriting the AbstractUser class and removing it there)? -
Django Channels 'coroutine' object is not subscriptable
I have a WebSocket with Django Channels that I'm trying to send data to the consumer once they connect. consumers.py: class CameraOnlineConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() logger.info(f"Added {self.channel_name} channel to workflow") query_set = await self.get_events() print(query_set) minute_delta = timedelta(seconds=60) difference = query_set[0].time_stamp - query_set[1].time_stamp if difference <= minute_delta: return self.send(text_data=CameraOnline.status_code) else: return self.send(text_data=CameraOffline.status_code) @database_sync_to_async async def get_events(self): return PastureEvent.objects.filter(result=7).order_by('-time_stamp')[:2] When starting the client WebSocket: ws = new WebSocket("ws://127.0.0.1:8000/ws/camera_online/connect/") I get this error printed out in the terminal: difference = query_set[0].time_stamp - query_set[1].time_stamp TypeError: 'coroutine' object is not subscriptable WebSocket DISCONNECT /ws/camera_online/connect/ [127.0.0.1:43014] -
why django model can't save my new object when i click create button in 'create.html'
I'm beginning to use Django, and I have some problems. I want to create new post such as blog. So I use views.py with model.py and forms.py. but when I enter the create.html, I was writing what i want to post, and then click 'create' button. but it wasn't save in django object. I check in admin site, but there is no object. I think it means save object is failed. but I don't know where is the problem. plz help me T.T in views.py def create(request): if request.method =="POST": filled_form = ObForm(request.POST) if filled_form.is_valid(): filled_form.save() return redirect('index') Ob_form = ObForm() return render(request, 'create.html', {'Ob_form':Ob_form}) in create.html <body> <!-- form.py 모델 생성 --> <form method="POST" action=""> {% csrf_token %}} {{Ob_form.as_p}} <input type="submit" value="확인" /> </form> </body> in models.py from django.db import models class Ob(models.Model): title = models.CharField(max_length=50) image = models.ImageField(null=True) content = models.TextField(null=True) update_at = models.DateTimeField(auto_now=True) in forms.py from django import forms from .models import Ob # 모델폼을 상속받아서 모델폼이 되었음 class ObForm(forms.ModelForm): # 어떤 모델과 대응되는지 말해줌 class Meta: model = Ob fields = ( "title", "image", "content") # 모델 폼 커스텀 # init - 내장함수 - (해당 클레스에 들어오는 여러가지 인자를 받을 수 있는 파라미터) def __init__(self, *args, … -
Django website saying "Page not found (404)"
I just deployed a django website that I made. This is my first time of doing something like this.. still a newbie. The problem is that whenever I try to upload something to the website, I get the following error while DEBUG is True Page not found (404) Request Method: POST Request URL: https://majestylink.com/admin/music/music/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in majestylink.urls, Django tried these URL patterns, in this order: [name='index'] advertise/ [name='advertise'] about-us/ [name='about-us'] promote/ [name='promote'] privacy-policy/ [name='privacy-policy'] s/ [name='search'] admin/ poem/ video/ music/ [name='index'] music/ <slug:slug>/ [name='detail'] ckeditor/ ^media\/(?P<path>.*)$ The current path, music/music/add/, didn't match any of these. Everything works fine on local server. I made a slight change while deploying the website which is changing the database from the default sqlite3 to MySQL, will this be the cause?. All migrations were run successfully -
Why this code always return error "Tensor Tensor is not an element of this graph."?
With this code: def get(self,request): while True: if request.method == 'GET': chat = request.GET.get('chat') if chat.lower() != 'bye': predict_pattern = call_model.bag_of_words(chat, ChatbotapiConfig.words) print(ChatbotapiConfig.model.predict(predict_pattern)) print(predict_pattern.shape) x = json.dumps(predict_pattern.tolist()) response = {'BOT': x} else: response = {'BOT': 'Bye'} return JsonResponse(response) Got error like this: Tensor Tensor("dense_4/BiasAdd:0", shape=(?, 44), dtype=float32) is not an element of this graph. -
MultiValueDictKeyError at /savepost/
I know this has been asked before but I'm facing this MultiValueDictKeyError. Basically I'm trying to take an input from the user, the input tag has this name="usercaption" attribute. While I click on submit it pops up the MultiValueDictKeyError. Here's my HTML form: <div class="post"> <form action="/savepost/" method="GET"> <input type="text" name="usercaption" placeholder="Write Something..."> <div class="attach"> <button class="upload-image"><i class="fal fa-image"></i> Image</button> <button><i class="fal fa-video"></i> Video</button> <button><i class="fal fa-smile-beam"></i> Mood</button> <button type="submit">Upload</button> </div> </form> </div> Here's my view function: def savepost(request): caption = request.GET["usercaption"] Post = post(caption=caption) Post.save() return redirect('usersfeed') The error is on this line caption = request.GET["usercaption"]