Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AssertionError at /wiki/Facebook
def markdown_to_html(markdown_string): if '\r' in markdown_string: markdown_string = markdown_string.replace('\r\n', '\n') assert('\r' not in markdown_string) unique_marker = 'PROTECTED_CHARS_fwargnmejlgnsjglsibgtnovdrsfeaijler' heading_matcher = re.compile(r'^(?P<hash_tags>#{1,6})\s*(?P<heading_title>.*)$', re.MULTILINE) heading_substituted = heading_matcher.sub( lambda m: rf"{unique_marker}<h{len(m.group('hash_tags'))}>{m.group('heading_title')}{unique_marker}" + rf"</h{len(m.group('hash_tags'))}>", markdown_string) bold_matcher = re.compile(r"(\*\*|__)(?P<bolded_content>.+?)\1") bold_substituted = bold_matcher.sub(r"<b>\g<bolded_content></b>", heading_substituted) list_outside_matcher = re.compile(r"^([-*])\s+.*?(?=\n\n|\n((?!\1)[-*])\s|\Z)", re.MULTILINE | re.DOTALL) list_inside_matcher = re.compile(r"^([-*])\s+(?P<list_item>.*?)(?=\n[-*]\s+|\Z)", re.MULTILINE | re.DOTALL) list_substituted = list_outside_matcher.sub(lambda m: unique_marker + '<ul>\n' + list_inside_matcher.sub(unique_marker + r"<li>\g<list_item>" + unique_marker + "</li>", m.group()) + '\n' + unique_marker + '</ul>', bold_substituted) link_matcher = re.compile(r"\[(?P<text>((?!\n\n).)*?)\]\((?P<link>((?!\n\n).)*?)\)", re.DOTALL) link_substituted = link_matcher.sub(rf'<a href="\g<link>">\g<text></a>', list_substituted) paragraph_matcher = re.compile(rf"^(?!{unique_marker}|\n|\Z)(?P<paragraph_text>.*?)(?=(\n\n)|{unique_marker}|\Z)", re.MULTILINE | re.DOTALL) paragraph_substituted = paragraph_matcher.sub(r"<p>\g<paragraph_text></p>", link_substituted) html_string = paragraph_substituted.replace(unique_marker, '') return html_string -
How to add item to wishlist with only specific variant object(s) in django rest framework?
Before my product model doesnt include variants. Now I have added variants which is ManytoMany relationships with Product model. Variants model consists of fields like color,size,price etc. I had already created api endpoints for adding items to wishlist. Now, if I had added with same api, it will includes all the variants. But,in frontend, user has the flexibility of choosing only a single varaint. How to change this? My models: class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) price = models.DecimalField(decimal_places=2, max_digits=20,blank=True,null=True) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product vairant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" class Product(models.Model): AVAILABILITY = ( ('in_stock', 'In Stock',), ('not_available', 'Not Available',), ) WARRANTY = ( ('no_warranty', 'No Warranty',), ('local_seller_warranty', 'Local Seller Warranty',), ('brand_warranty', 'Brand Warranty',), ) SERVICES = ( ('cash_on_delivery', 'Cash On Delivery',), ('free_shipping', 'Free Shipping',), ) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) tags = TaggableManager(blank=True) # tags mechanism … -
Why is This Simple BeautifulSoup and Django Webscrapping Code Not Working
from bs4 import BeautifulSoup from django.core.management.base import BaseCommand from urllib.request import urlopen from bs4 import BeautifulSoup import json import html5lib from blog.models import Post, Category import csv class Command(BaseCommand): help = "collect news" # define logic of command def handle(self, *args, **options): # collect html html = requests.get('https://bbc.com') # convert to soup soup = BeautifulSoup(html.content, 'html5lib') # grab all postings postings = soup.find_all("div", class_="posting") for p in postings: url = p.find('a', class_='posting-btn-submit')['href'] title = p.find('h3' class_="media__title").text category = p.find('b').text images = soup.find_all('img') content_1 = soup.find_all('blockquote').text # check if url in db try: # save in db Post.objects.create( title=title, category=category, content_1=content_1, image=images ) print('%s added' % (title,)) except: print('%s already exists' % (title,)) self.stdout.write( 'News Added succesfully' ) This is supposed to scrap bbc website when i run python manage.py scrapper. can anybody shows me a way out or simply show me a way to scrap that website quickly. am desperately waiting for solutions -
Ajax call towards django views
Good morning. I made an ajax call on a button that goes to the Django views. I don't find any issues with it but it doesn't work at all, I can't even get a console response from it. I can get the response I want (redirection) without issues if not using AJAX. I am working with Django on localhost. I did not forget to put the JQuery script. Can anyone help, please? Button HTML <a href="{% url 'Like' post.id %}"> <button id="like-button" class="btn btn-outline-dark btn-lg w-100">Like</button> </a> AJAX $('.like-button').click(function(e){ console.log('TEST1') ---#Nothing shows on console e.preventDefault(); console.log('TEST2') ---#Nothing shows on console $.ajax({ type: "POST", url: $(this).attr('href'), data: {'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { console.log(response) ---#Nothing shows on console selector = document.getElementsByName(response.content_id); if(response.liked==true){ $(selector).css("color","blue"); } else if(response.liked==false){ $(selector).css("color","black"); } } }); }) -
Updating values in django
I am trying to update the profile value of a particular user. If the user has logged in for the first he needs to go to Edit Profile and then enter the details which are getting stored in the database. When I am trying to update the values of a User Profile. It is not getting updated in the database. I know the code is not that perfect but I am just trying to do it through normal logic. You can also find the comment in the code which represent what the code of block is doing. Code # edit user profile def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) except UserProfile.DoesNotExist: name = UserProfile.objects.all() response_data = {} # when the submit button is pressed if request.POST.get('action') == 'post': name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = college_name response_data['branch'] = branch try: # checking if the user exist # if the user exist update the values user_data = UserProfile.objects.get(emailID = request.user.email) if(user_data.emailID == request.user.email): UserProfile.objects.filter(emailID = request.user.email).update( name … -
Django booleanfield modelform
So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything. models: class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms: from .models import * class TaskForm(forms.ModelForm): title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'})) class Meta: model = Task fields = '__all__' html: <div class="main-container"> <form method="POST" action="/"> {% csrf_token %} <input type="submit"/> {{ form.title }} </form> {% for task in tasks %} {{ form.complete }} {% if form.complete == True %} <h1><strike>{{task.title}}</strike></h1> {% else %} <h1>{{task.title}}</h1> {% endif %} {% endfor %} </div> views: def index(request): tasks = Task.objects.order_by('-created') form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'to-do.html', context) -
Why is the HTML source code is displayed when using django built-in template tags? [closed]
html template code. I'm sure this is the right syntax, but the HTML source code is displayed instead of the input field. -
give me return "None" when pass variable to antoher html page
still learn about django and want to try pass variable, i want to pass variable that i got from index.html to process.html, when i clicked the button give me value "None" not the value from video.id, views.py def process(request): context = { } videoid = request.POST.get('videoid',None) context['videoid'] = videoid print(videoid) print(context) return render(request, 'search/process.html', context) slice of my index.html code to pass the value of video.id index.html <form action="/process" method="POST" id="videoform"> {% csrf_token %} <a type="submit" name="videoid" value= "{{video.id}}" form="videoform" href="/process" class="btn btn-sm btn-outline-secondary" target="_blank">Test</a> </form> process.html <body> <h1>Event For {{ videoid }}</h1> <p>HELLO WORLD</p> </body> tested in index.html , i got the value video.id but None when pass to process.html ty, before for ur help -
how to automatically add tags to a post
Can you please tell me if there is a way to add instances of the ManytoMany class to django automatically everything. Add all tags that are to the post during its creation automatically, without selecting them manually. -
Value error. The view 'users.views.register' didn't return an HttpResponse object. It returned None instead
Python 3.8.5, Django 3.1.6 I'm learning python and django with book Python Crash Course: A Hands-On, Project-Based Introduction to Programming (Erik Matthes)enter image description here Now I cannot continue because I cannot find a solution to the problem. ValueError at /users/register/ The view users.views.register didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm def register(request): # return HttpResponseRedirect(reverse('index')) print(request.method) import pdb; pdb.set_trace() if request.method != "POST": form = UserCreationForm() else: print('\nelse\n') form = UserCreationForm(request.POST) print('\n'+str(form.is_valid())+'\n') if form.is_valid(): new_user = form.save() authenticated_user = authenticate(username=new_user.username, password=request.POST['password1'], confirm_password=request.POST['password2']) login(request, authenticated_user) return HttpResponseRedirect(reverse('index')) context = {'form': form} return render(request, 'users/register.html', context) urls.py from django.urls import re_path from django.contrib.auth.views import LoginView, LogoutView from django.views.generic import RedirectView from . import views urlpatterns = [ re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'), re_path(r'^logout/$', LogoutView.as_view(template_name='learning_logs/index.html'), name='logout'), re_path(r'^register/$', views.register, name='register') ] register.html {% extends 'learning_logs/base.html' %} {% block content %} <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{form.as_p}} <button name="submit">Register</button> <input type="hidden" name="next" value="{% url 'index' %}" /> </form> {% endblock content %} Pls help me. I've been trying unsuccessfully to fix this for a week now. … -
upload images from postman using function in django rest framework
Model: class Department(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Employee(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE,related_name='employee') name = models.CharField(max_length=100) address = models.CharField(max_length=100) image = models.ImageField(upload_to='employee_pic',null=True,blank=True) class Meta: ordering =('id','name') def __str__(self): return self.name Serializers.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id','name','address','image','department'] class DepartmentSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True,read_only=True) class Meta: model = Department fields=['id','name','employee'] views.py @api_view(["GET","POST"]) def employeeList(request): if request.method == "GET": data = Employee.objects.all() all_data = EmployeeSerializer(data,many=True) return JsonResponse(all_data.data,safe=False) elif request.method == "POST": data = JSONParser().parse(request) new_data = EmployeeSerializer(data,request.data) if new_data.is_valid(): new_data.save() return JsonResponse(new_data.data,status = status.HTTP_201_CREATED) urls.py path('api/function/employee', views.employeeList, name='employee'), I need to post image from postman and in views.py i want to use function for image post. I want to create my views using function. I don't want to use class like ModelViewSet i would to use almost all function. Thanks in advance. -
Django custom command: AttributeError: 'Settings' object has no attribute 'setmodule'
I'm currently working on a webscraper with Scrapy and the data is stored in Django. When i start the scraper with a custom command. But i got stuck at this error: AttributeError: 'Settings' object has no attribute 'setmodule' I checked my settingsfile and couldn't find a Setmodule attribute. My custom command file: /webscraper/management/commands/crawl-test.py import os # Django requirements from django.core.management.base import BaseCommand from django.conf import settings # scrapy requirements import scrapy from webscraper.webscraper.spiders.WebSpider import WebSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class Command(BaseCommand): help = "Web Scraper" def handle(self, *args, **options): process = CrawlerProcess(get_project_settings()) os.environ['SCRAPY_SETTINGS_MODULE'] = 'webscraper.settings' settings_module_path = os.environ['SCRAPY_SETTINGS_MODULE'] settings.setmodule(settings_module_path, priority='project') process = CrawlerProcess(get_project_settings()) process.crawl(WebSpider) process.start() If you need more information just leave a comment! -
Automatically Delete Duplicate objects in template
I am Building a WebApp and I am stuck on an Problem. What i have Build and What i am trying to do :- I build a Private Chat App , If user_1 accept user_2's FriendRequest then a ChatBox will be automatically created in the Chats page. BUT When a user unfriend another user then ChatBox is still there ( Which is no problem ) BUT When the unfriended user again send send friend request then another ChatBox is automatically creating with the same user , AND i want it to delete previous or delete newer chat after second accepted request. What have i tried I also tried .distinct() function BUT it didn't work for Me. I also tried many solutions like This. BUT nothing worked. views.py def accept_friend_request(request,user_id): from_user = get_object_or_404(User,id=user_id) frequest = FriendRequest.objects.filter(from_user=from_user,to_user=request.user).first() user1 = frequest.to_user user2 = from_user chat_box = ChatBox(user_1=user1,user_2=user2) chat_box.save() frequest.delete() return redirect('profile',user_id=user_id) I don't know what to do now. Any help would be Appreciated. Thank You in Advance. -
can you create a social network or a search engine with django python [closed]
can you create a social network or a search engine like google with django python. -
Microservices in Django
I am trying to build a project based on Microservices using Django rest Framework where i have some data coming from a different project running on different port. In illustration , the data in red circle should be coming from a project running on different port based on the id stored in 1st project (one to many relationship). I was able to get the data from 2nd project via api request but wasn't able to display it in the response as in the image below How do i achieve something like this in django rest framework? -
Override method of a django builtin Class
Just for example, I need to modify the implementation of AdminSite.get_app_list like following From #app['models'].sort(key=lambda x: x['name']) To app['models'] = sort_with_name_length(app['models']) //my own method Expected/desired approach: I supposed that it should be achievable by just writing following code in any of my custom module's models.py or sites.py file class MyAdminSite(AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) for app in app_list: #app['models'].sort(key=lambda x: x['name']) app['models'] = sort_with_name_length(app['models']) #an example change I need return app_list But what above code does is nothing, its never executed, until I use Monkey patching guided by this answer. What I could achieve from django.contrib.admin import AdminSite class MyAdminSite(AdminSite): def get_app_list(self, request): # res = super(MyAdminSite, self).get_app_list(request) //gives following error # super(type, obj): obj must be an instance or subtype of type # So i have to rewrite complete method again in my module like following app_dict = self._build_app_dict(request) app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) for app in app_list: #app['models'].sort(key=lambda x: x['name']) app['models'] = sort_with_name_length(app['models']) return app_list AdminSite.get_app_list = MyAdminSite.get_app_list Problem being faced: Above does what I need in a totally undesired way. This solution has two problems It will not allow me Multilevel Inheritance (I would not be able to have child and grand child) Its … -
Trouble shooting with postgresql to connect with Django | Window 10
I install PostgreSQL version 10 also, install pgAdmin4 During the PostgreSQL installation, as Every developer know default username = Postgres My PostgreSQL username was Postgres. installation window asked me the password, so put the new password Now when I connect PostgreSQL to my Django project I install this module pip install psycopg2 I created a new database using pgAdmin4 named 'mydb' In my Settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USERNAME':'postgres', 'PASSWORD' : '<my_Password_here>' , # I entered the same password that i provided during postgres installation 'HOST' : 'localhost', 'PORT': '5432', } } postgres username = 'postgres' where my Window Username = 'Huzaifa' ERROR is here django.db.utils.OperationalError: FATAL: password authentication failed for user "Huzaifa" Why Postgres using my Window User (username) for authentication NOTE: I already set environment variables as following C:\Program Files\PostgreSQL\10\lib C:\Program Files\PostgreSQL\10\bin -
Unable to deploy django to python 3.8/Linux 2 on Elastic Beanstalk due to "postgresql95-devel is not available to be installed"
This is my requirements.txt: asgiref==3.3.1 boto3==1.17.23 botocore==1.20.23 certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.6 defusedxml==0.7.1 Django==3.1.7 django-allauth==0.44.0 django-cors-headers==3.7.0 django-rest-auth==0.9.5 djangorestframework==3.12.2 idna==2.10 jmespath==0.10.0 oauthlib==3.1.0 psycopg2==2.8.6 pycparser==2.20 PyJWT==2.0.1 python-dateutil==2.8.1 python3-openid==3.2.0 pytz==2021.1 requests==2.25.1 requests-oauthlib==1.3.0 s3transfer==0.3.4 six==1.15.0 sqlparse==0.4.1 urllib3==1.26.3 The main error message I see in my logs is: postgresql95-devel is not available to be installed. I am able to deploy a similar requirements.txt in an older environment (python 3.6) but for some reason this fails when on python 3.8. I even used the same deployment.zip that succeeded in 3.6 but this suddenly fails in 3.8. Is this a configuration error or a versioning error? Not sure how to debug this. -
How do I implement graphql with social auth in django?
I am facing an error while implementing it. The error is in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I am using python3.9.1 and django-graphql-social-auth0.1.4. -
while signup 'AnonymousUser' object has no attribute '_meta'
class SignupView(View): def get(self, request): userform = UserForm() studentform = StudentForm() facultyform = FacultyForm() deptform = DepartmentForm() roleform = RoleForm() return render(request, 'signup.html', {'userform': userform, 'studentform': studentform, 'departmentform': deptform, 'roleform': roleform, 'facultyform': facultyform}) def post(self, request): user_role = { 'Student': StudentForm(request.POST), 'Faculty': FacultyForm(request.POST), } roleform = RoleForm(request.POST) if roleform.is_valid(): temp_role = roleform.cleaned_data['role'] usertype = user_role.get(temp_role) userform = UserForm(request.POST, request.FILES) deptform = DepartmentForm(request.POST) if userform.is_valid() and usertype.is_valid() and deptform.is_valid() and roleform.is_valid(): role = roleform.save(commit=False) role1 = Role.objects.filter(role=role).first() # saving user with department user = userform.save(commit=False) # department and Role saved dept = deptform.save(commit=False) dept1 = Department.objects.filter(department=dept).first() user.department = dept1 user.role = role1 user.save() new_user = usertype.save(commit=False) new_user.user = user new_user.save() login_userr = authenticate( username=userform.cleaned_data['username'], password=userform.cleaned_data['password']) login(request, login_userr) return redirect('user_profile', pk=user.id) else: return render(request, 'signup.html', {'userform': userform, 'departmentform': deptform, 'roleform': roleform}) else: return render(request, 'signup.html', {'userform': userform, 'departmentform': deptform, 'roleform': roleform}) -
Exported HTML table to excel giving warning while opening the file using office Excel
I am trying to export HTML table to xls format. But when I try to open the file using Excel, I am given a warning message. The waring message: I using this lines of code: var file = new Blob([ html.outerHTML], { type: "application/vnd.ms-excel" }); var url = URL.createObjectURL(file); var filename = dateSelected + "-" + "attendance" + ".xls" //here we are creating HTML <a> Tag which can be trigger to download the excel file. var a = document.createElement('a'); a.id = "export"; document.body.appendChild(a); //here we are checking if the bwoswer is IE or not if IE then we use window.navigator.msSaveBlob function otherwise Go with Simple Blob file. if (window.navigator && window.navigator.msSaveBlob) { window.navigator.msSaveBlob(file, filename); a.click(); document.body.removeChild(a); document.body.removeChild(html); } else { a.download = filename; a.href = url; a.click(); document.body.removeChild(a); document.body.removeChild(html); } I tried to change the blob type but nothing is working. How can i solve this issue? -
Django Blog url error NoReverseMatch at /
I git this error home.html page when I but the url to user posts page the url is work fine in other pages but in home page I get this error Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)/$'] I don't know if their something I need to but in home.html to let me access the post.author.usernname home.html {% extends "blog/base.html" %} {% block content %} <h1>Blog Home!</h1> {% for post in posts %} <article class="media content-section"> <img class = "rounded-circle article-img" src = "{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class = "btn btn-outline-info mb-4" href="?page=1">First</a> <a class = "btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class = "btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-4' and num < page_obj.number|add:'4' %} <a class = "btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> … -
AWS ec2 Nginx + Django server easily gets to 100% CPU utilisation without much traffic
Hi I am using AWS EC2 instance (c5.18xlarge (72vcpu and 144 Gib ram)) with Nginx + Django and postgresql. The problem is it gets to 100% CPU utilisation in 400-500 concurrent users and slows down. Here are my settings: postgresql.conf max_connections = 800 shared_buffers = 50000MB Nginx.conf user www-data; worker_processes 128; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; worker_rlimit_nofile 50000; events { worker_connections 10000; #multi_accept on; } sysctl.conf net.core.somaxconn = 65000 net.core.netdev_max_backlog = 65535 fs.file-max = 90000 net.ipv4.ip_forward = 1 kernel.shmmax=1006632960 gunicorn_start.bash NAME="django_app" # Name of the application DJANGODIR=/home/ubuntu/project # Django project directory SOCKFILE=/home/ubuntu/env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=128 # how many worker processes should Gunicorn spaw TIMEOUT=120 DJANGO_SETTINGS_MODULE=project.settings # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" I know the server can't overload on the current usage of the app. Please suggest how can this be solved. Or how can it be debugged to reach the problem. -
Reverse for 'send_form' with no arguments not found. 1 pattern(s) tried: [u'app/send_message/(?P<flag>\\d+)/$']
I am trying to build a form to be used in 2 pages (index and contact). Once the form performs method post, it will bring a page either success or failed (simple html page with few words). I am stuck due to the error shown above and I’m still new in using Django. Appreciate any help. Thank you urls.py from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app/', include('app.urls')) ] app/url.py from .views import * app_name = "app" urlpatterns = [ url(r'^home/$', home, name='home'), url(r'^contact/$', contact, name='contact'), url(r'^send_message/(?P<flag>\d+)/$', send_form, name='send_form'), url(r'^send_message/success/$', success, name='success'), url(r'^send_message/failed/$', failed , name='failed'), ] views.py from django.core.mail import send_mail from .forms import MessagesForm from django.conf import settings rom django.shortcuts import render, redirect def home(request): empty_form = send_form(request) cover_title = PageServiceCover.objects.latest('id').title cover_text = PageServiceCover.objects.latest('id').text context = {'cover_title': cover_title, 'cover_text': cover_text,'form':empty_form} return render(request, 'index.html', context) def send_form(request): if request.method == 'POST': form = MessagesForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] category = form.cleaned_data['category'] text = form.cleaned_data['text'] form.save() subject=[name, phone, category] send_mail(subject, text, email, [settings.EMAIL_HOST_USER], fail_silently=False) return redirect('thanks', flag='success' ) else: return redirect('not_working', flag='failed') def success(request): return … -
Download File From s3 using django and render it to browser
I have a Django app in which we have a download button and on click, on that button, the file should be rendered to the browser. I have already tried using the download_file method but the issue is the file is downloaded to the local system. Here is how my current code looks like: def downloadObject(sourceBucket, key): content_type = 'application/x-zip' s3_temp = boto3.client('s3') file = s3_temp.get_object(Bucket=sourceBucket, Key=key) response = FileResponse(file, content_type=content_type, filename="{}".format(key)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(key) return response