Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update multiple rows with Django (different ids) using different values for each id (as keys)
Let's say I have a model: I have some items: grocery = { status : True, fruits: ['1', '23', '55'], comments: {'1': "test", '23': "test2", '55': ""} I have a rough potential Django update query: Fruit.objects.all().filter(id__in=grocery.get('fruits')).update(status=grocery.get('status'), comment=grocery.get('comments')) I'm successfully updating the status but I want to dynamically update the comments so that if the Fruit object in question has, for example, id: 23, the fruit comment will be test2, or if the object has 'id: 55' it will be '' -
Django - Date problem in CRUD application
I'm using flatpickr for date informations in my Django application. The problem is when I want to update worker informations, in edit.html page default value of birth_date is not displaying correctly. For example, I've created worker Xen who was born in 01-05-1997, and click to update his name, in birth_date input it displays today's date. Here are my codes: forms.py class WorkerForm(ModelForm): class Meta: model = Worker fields = "__all__" widgets = { 'birth_date': DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class':'datetimefield'}) } models.py: class Worker(models.Model): ... birth_date = models.DateTimeField(blank=True, null=True) edit.html: ... <div class="form-group row"> <label class="col-sm-2 col-form-label">İşçinin doğum tarixi</label> <div class="col-sm-4"> <input class="datetimefield" type="date" name="birth_date" id="birth_date" value="{{ worker.birth_date }}" /> </div> </div> ... <script> window.addEventListener("DOMContentLoaded", function () { flatpickr(".datetimefield", { enableTime: true, enableSeconds: true, dateFormat: "Y-m-d H:i:S", time_24hr: true, locale: "az", }); }); </script> -
i got this Error TypeError at / Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models
i got this Error Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models import os from time import sleep from flask import Flask, render_template, request from selenium import webdriver from werkzeug.utils import secure_filename def Twitter(user, pwd, path, desc, speed): if user: driver = webdriver.Chrome( executable_path=r"C:\Users\pc\Downloads\chromedriver.exe" ) driver.get("https://twitter.com/login") user_box = driver.find_element_by_class_name( "js-username-field" ) user_box.send_keys(user) # password pwd_box = driver.find_element_by_class_name( "js-password-field" ) pwd_box.send_keys(pwd) login_button = driver.find_element_by_css_selector( "button.submit.EdgeButton.EdgeButton--primary.EdgeButton--medium" ) login_button.submit() sleep(speed) # Attach-Media img_box = driver.find_element_by_css_selector( "input.file-input.js-tooltip" ) img_box.send_keys(path) sleep(speed * 3) # Discription text_box = driver.find_element_by_id( "tweet-box-home-timeline" ) text_box.send_keys(desc) # Tweet tweet_button = driver.find_element_by_css_selector( "button.tweet-action.EdgeButton.EdgeButton--primary.js-tweet-btn" ) tweet_button.click() sleep(speed * 5) driver.refresh() driver.close() return 1 pass -
Email Verification in Django when a new user signs up
I am creating a user registration page for my website. I want to send an email verification mail to the mail the user inputs while registering. I tried many solutions but nothing seems to work for me. My code: views.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'Home/register.html', context) def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') return redirect('login') context = {} return render(request, 'Home/login.html', context) forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password1", "password2"] -
Django how the query GenericForeignKey relation(s)?
I want to display my users the content they have already brought by the "my_purchases" view (see below). For each object the user buy's a license is getting created and placed at the Licenses model: licensable_models = models.Q(app_label='App', model='model1') | \ models.Q(app_label='App', model='model2') class Licenses(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=licensable_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') license_holder = models.ForeignKey(User, verbose_name="License Holder", on_delete=models.CASCADE, null=True) paid_amount_usd = models.DecimalField(verbose_name="License Price (USD)", max_digits=8, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))], null=False) paid_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "License" verbose_name_plural = "Licenses" ordering = ['-paid_date'] Creating a license and accessing the content after payment works fine! I expect that there is no buggy code but I currently don't really understand how I can create a query to grab all related objects the user has already brought and a license as been created. views.py def my_purchases(request): user = User.objects.get(pk=request.user.pk) template = 'App/my_purchases.html' if request.method == 'GET': list_my_purchases = sorted( chain( < how does this query have to look like? > ), key=attrgetter('paid_date'), reverse=True ) paginator = Paginator(list_my_purchases, 10) # Show 10 purchases per page page = request.GET.get('page') my_purchases = paginator.get_page(page) args = {'user': user, 'my_purchases': my_purchases, } return render(request, template, args) At each of my Model1 and Model2 (mentioned … -
Django password reset _getfullpathname error
I am trying to set up a password reset form but I get the following error after trying to send an email, weirdly I noticed that if I put email that doesn't match any of the emails provided by users it works, error only occurs when email matches one provided by a user. Error: TypeError at /password_reset/ _getfullpathname: path should be string, bytes or os.PathLike, not NoneType urls.py from django.contrib.auth import views as auth_views #import this urlpatterns = [ ... path('accounts/', include('django.contrib.auth.urls')), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), path("password_reset/", views.password_reset_request, name="password_reset"), ] views.py def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "registration/password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("/password_reset/done/") password_reset_form = PasswordResetForm() return render(request=request, template_name="registration/password_reset_form.html", context={"password_reset_form":password_reset_form}) password_reset_form.html {% extends 'base.html' %} {% block content %} <!--Reset Password--> <div class="container p-5"> <h2 class="font-weight-bold mt-3">Reset Password</h2> <hr> <p>Forgotten your password? Enter your email address below, and we'll email … -
Django rest raising error "The submitted data was not a file. Check the encoding type on the form." to angualar Http Client
The are any solutions to the problem but m not able to find the root cause and also to mention no of the solution is working in my case. What I am trying to do is to upload a file to Django rest API from a angular Http Client Service. I am taking up the input form the user passing to the service at the end I have declared a type specific for the type of model I am creating an object for but I am not getting the same error again and again. I read some where that Django file uploader doesn't understand some char-set format but I still can't understand whats wrong with it. ``` var report = <CompleteReport> { title:'heelo', description:'sdfsdfs', author: 'report', article_upload_images: [uuid4(),], presentation_upload_images: [uuid4(),], report_article: article_object, report_image: image_object, report_podcast: podcast_object, report_presentation: presentation_object, report_video: video_object }; let headers = new HttpHeaders({ 'Accept': 'application/json' }); let options = {headers: headers}; return this.http.post<any>(url, report, options) -
How to pass Django view's data to jquery?
I want to pass page object data to jquery to print next and previous page. I used json.dumps(page), but it didn't workout, getting error. I used django pagination but on click next and previous buttons the page is reloading. so, i am trying using jquery. How to solve this, please suggest me. views.py: def render_questions(request): questions = Questions.objects.all() p = Paginator(questions, 1) page = request.GET.get('page', 1) try: page = p.page(page) except EmptyPage: page = p.page(1) return render(request, 'report.html', {'ques': page}) template.html: <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} <div class="divs"> <div class="questionscontainer"> {% for question in ques %} <h6>Q &nbsp;&nbsp;{{ question.qs_no }}.&nbsp;&nbsp;<input type="hidden" name="question" value="{{ question.question }}">{{ question.question }}</h6> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_a}}">&nbsp;&nbsp;&nbsp;A)&nbsp;&nbsp;{{ question.option_a }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_b}}">&nbsp;&nbsp;&nbsp;B)&nbsp;&nbsp;{{ question.option_b }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_c}}">&nbsp;&nbsp;&nbsp;C)&nbsp;&nbsp;{{ question.option_c }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_d}}">&nbsp;&nbsp;&nbsp;D)&nbsp;&nbsp;{{ question.option_d }}</label> </div> {% endfor %} </div> </div> <ul class="pagination"> <li><a class="button" id="prev">prev</a></li> <li><a class="button" id="next">next</a></li> <input type="submit" value="Submit" onclick="submitTest()" class="button"> </ul> </form> script: I need to get the page object in my script and i should print one by one question using next and previous buttons. $(document).ready(function(){ $(".divs .questionscontainer").each(function(e) { if (e … -
nginx directory forbidden using passenger_wgsi.py with django
I am trying to configure plesk with django nginx , I am using my vps with centos 8 and plesk 18 . I am getting 403 forbidden error . If a place index.html it works but it is not working with passenger_wsgi.py file this is my server log proxy_error logs 020/10/22 10:30:28 [error] 119522#0: *49 directory index of "/var/www/vhosts/xxx.com/httpdocs/djangoProject/" is forbidden, client: 162.158.165.181, server: xxx.com, request: "GET / HTTP/1.1", host: "xxx.com" error logs [Thu Oct 22 08:49:00.606752 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Oct 22 08:49:00.632957 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name passenger file code import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() nginx.conf user root; worker_processes 1; #error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; #pid /var/run/nginx.pid; include /etc/nginx/modules.conf.d/*.conf; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr … -
Django: Extending base.html in django admin
I've a base.html file which has vertical and horizontal menu-bar: Wherever I want to use that I just simply write: {% extends 'base.html' %} {% block content %} //html code {% endblock content %} But I don't know how to use the same file base.html from templates directory in djando admin. I want output like this: What I Tried: How to override and extend basic Django admin templates? How do I correctly extend the django admin/base.html template? Override Navbar in Django base admin page to be same as the base.html -
Django save user and profile with signals
Im still learning Django and I am stuck at user registration / profile creation. My goal So, the purpose of this is to save the new user and at the same time save the profile of the new user with de data from the form. I use 2 forms u_form and p_form. What I have done so far: Created model Profile with OneToOneField to User Created 2 forms for User (u_form) and Profile (p_form) Created signals.py to create new Profile when new User is created In the view I have create function with u_form.save() Problem This works, but the new Profile is completely empty.. When I put p_form.save() in my view it gives me this error: NOT NULL constraint failed The code models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) voorletter = models.CharField(max_length=10) voorvoegsel = models.CharField(max_length=10) achternaam = models.CharField(max_length=200) depers = models.CharField(max_length=25) depersoud = models.CharField(max_length=25) telefoonnummer = models.CharField(max_length=25) class Meta: verbose_name = "Collega" verbose_name_plural = "Collega's" def __str__(self): return self.depers signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if … -
Django does not gracefully close MySQL connection upon shutdown when run through uWSGI
I have a Django 2.2.6 running under uWSGI 2.0.18, with 6 pre-forking worker processes. Each of these has their own MySQL connection socket (600 second CONN_MAX_AGE). Everything works fine but when a worker process is recycled or shutdown, the uwsgi log ironically says: Gracefully killing worker 6 (pid: 101)... But MySQL says: 2020-10-22T10:15:35.923061Z 8 [Note] Aborted connection 8 to db: 'xxxx' user: 'xxxx' host: '172.22.0.5' (Got an error reading communication packets) It doesn't hurt anything but the MySQL error log gets spammed full of these as I let uWSGI recycle the workers every 10 minutes and I have multiple servers. It would be good if Django could catch the uWSGI worker process "graceful shutdown" and close the mysql socket before dying. Maybe it does and I'm configuring this setup wrong. Maybe it can't. I'll dig in myself but thought I'd ask as well.. -
Error 502 with conflicting server name and (2: No such file or directory)
Mywebsite.co.uk displays a 502 Error. Running sudo tail -F /var/log/nginx/error.log outputs: 2020/10/22 09:42:13 [warn] 200096#200096: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:13 [warn] 200107#200107: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:29 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:42:50 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:42:51 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:43:00 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:43:24 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:57:01 [crit] 200110#200110: *10 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 103.42.252.150, server: _, request: "GET / HTTP/1.0", … -
How to add part of the path before the language code for django translate i18n
How to add part of the path before the language code for django i18n_patterns ? Example: my project is located at: http://domain.site/sub/admin/ When changing the language, a redirect to http://domain.site/`en`/sub/admin/ occurs automatically , but me need to so http://domain.site/sub/`en`/admin/. Thanks! urls.py code: urlpatterns = i18n_patterns ( ... path ('admin /', admin.site.urls), ... prefix_default_language = False, ) settings.py code: LANGUAGES = [ ('en', _ ('English')), ('ru', _ ('Russian')), ] i18n_switcher.py: from django import template from django.template.defaultfilters import stringfilter from django.conf import settings register = template.Library() def switch_lang_code(path, language): lang_codes = [c for (c, name) in settings.LANGUAGES] if path == '': raise Exception('URL path for language switch is empty') elif path[0] != '/': raise Exception('URL path for language switch does not start with "/"') elif language not in lang_codes: raise Exception('%s is not a supported language code' % language) parts = path.split('/') if parts[1] in lang_codes: parts[1] = language else: parts[0] = "/" + language return '/'.join(parts) @register.filter def switch_i18n(request, language): """takes in a request object and gets the path from it""" return switch_lang_code(request.get_full_path(), language) html link for change language <a href="{{ request|switch_i18n:'en' }}"> <img class="i18n_flag" src="{% static 'images/lang-en.svg' %}"/> </a> / <a href="{{ request|switch_i18n:'ru' }}"> <img class="i18n_flag" src="{% static 'images/lang-ru.svg' %}"/> … -
How to resolve JSONDecodeError at / in Django
This is my code I have been using views.py from django.shortcuts import render import requests from django.http import HttpResponse def form(request): return render(request,'hello/index.html') def home(request): a=request.POST.get("num") if not a: a=0 response = requests.post('http://127.0.0.1:5000/index'+ str(a)).json() return render(request, 'hello/index.html', {'out': response['out']}) index.html <!DOCTYPE html> <html> <body> <form action ="home" method="POST"> {% csrf_token%} <label for ="num">Your number: </label> <input type="text" name="num"> <input type ="submit" > </form> <div> {{ out }} </div> </body> </html> I am getting JsonDecoder error for these code I dont know how to solve it -
Django get fields of the ForeignKey Model efficiently?
I am using django-rest-framework as backend and react as a frontend For example if I have the following tables in Django class Master1(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Master2(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Transaction(models.Model): master1 = models.ForeignKey(Master1) master2 = models.ForeignKey(Master2) title = models.CharField(max_length = 100) I want to create a view for the Trasaction that displays several fields from each of its related models in frontend. Can someone suggest an efficient way of doing that. Should I just define the fields it needs in the view or should I use nested serializers? -
WSGI/Django 1.8 No handlers could be found for logger "django.request"
I wanted to try out graphite+graphite-web and followed this guide here: https://www.metricfire.com/blog/install-graphite-common-issues/#Log-rotation after that i got some errors and fixed a few of them! but now i got stuck at that one: On the website from graphite-web i get this error: graphite-web In the error.logs i have this error: error.log This are my wsgi.py settings: wsgi.py This are my apache2 settings: apache2-graphite.conf If u need anything else, let me know! -
AMQP service: how to check if running, stop and start it
I have an old Django app using celery==3.1.18 and amqp==1.4.9. I am trying to replace amqp with rabbitmq but I need to understand how the old system works. I cannot find any documentation helping me with this task. How do I check status, stop, start amqp services? Any link to documentation explaining how to move from amqp to rabbitmq will be greatly appreciated. Thank you. -
Invisible output in postgreSQL using jsonb
Only the table "checks_check" experiences this. It's not only invisible, there is actually no output to work with. The table was create by django 1.11. Terminal -
How to define a virtual environment in vs-code
I am a noob to vs-code (starting using it yesterday and I like it) I have a minor irritation. I am working on a django project and I'm using a virtualenv with virtualenvwrapper. The problem that I have is that (for example) in the line from django.shortcuts import render the linter says Unable to import 'django.shortcuts'pylint(import-error) My virtualenvs are in the directory ~/Envs and ls -l Envs returns drwxr-xr-x 4 jeff jeff 4096 Jun 18 14:46 django -rwxr-xr-x 1 jeff jeff 135 Jun 18 15:23 get_env_details -rw-r--r-- 1 jeff jeff 96 Jun 18 15:23 initialize -rw-r--r-- 1 jeff jeff 73 Jun 18 15:23 postactivate -rw-r--r-- 1 jeff jeff 75 Jun 18 15:23 postdeactivate -rwxr-xr-x 1 jeff jeff 66 Jun 18 15:23 postmkproject -rw-r--r-- 1 jeff jeff 73 Jun 18 15:23 postmkvirtualenv -rwxr-xr-x 1 jeff jeff 110 Jun 18 15:23 postrmvirtualenv -rwxr-xr-x 1 jeff jeff 99 Jun 18 15:23 preactivate -rw-r--r-- 1 jeff jeff 76 Jun 18 15:23 predeactivate -rwxr-xr-x 1 jeff jeff 91 Jun 18 15:23 premkproject -rwxr-xr-x 1 jeff jeff 130 Jun 18 15:23 premkvirtualenv -rwxr-xr-x 1 jeff jeff 111 Jun 18 15:23 prermvirtualenv drwxr-xr-x 4 jeff jeff 4096 Jun 18 15:26 wagtail I am working in the venv … -
Dockerized Django project deployment with supervisor - what is the correct way?
The cookiecutter-django docs are great, got the django project dockerized and it runs. Even the Supervisor example works flawlessly. Though when it comes to a new deployment, I wonder what the correct way of doing this is. Clearly, I need to run: $ docker-compose -f production.yml build But my guess is that I would have to stop supervisor first: $ sudo supervisorctl stop {{ my_project_slug }} and then run $ docker-compose -f production.yml build followed by this to bring the project back up: $ sudo supervisorctl start {{ my_project_slug }} Is that correct? Or is it ok to run the build command without stopping supervisor? -
uploading image and videos to aws s3 using Django Python takes lot of time
I am using below code in views.py: def upload(request): if request.method == 'POST': image = ImageForm(request.POST, request.FILES) video = VideoForm(request.POST, request.FILES) # Split the extension from the path and normalise it to lowercase. ext = os.path.splitext(str(request.FILES['file']))[-1].lower() print(ext) # Now we can simply use == to check for equality, no need for wildcards. if ext == ".mp4": print("mp4!") if video.is_valid: # form.save() fs = video.save(commit=False) fs.user = request.user fs.save() messages.success(request, 'Video inserted successfully.') return redirect('upload') But upload videos and photos takes a lot of time. i.e 3-4 mins. Please help me in finding a solution to this. -
PermissionError at /generate-pdf [Errno 13] Permission denied weasyprint
hello am using weasyprint to generate a pdf whats wrong with my code here getting access denied. def generate_pdf(request): """Generate pdf.""" # Model data student = Student.objects.all().order_by('last') # Rendered html_string = render_to_string('pdf-output.html', {'student': student}) html = HTML(string=html_string) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_os_students.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response If i change the line output = open(output.name, 'rb') to output = open(output.seek(0), 'rb') the page loads to infinity while in console printing [22/Oct/2020 11:36:54] "GET /dashboard HTTP/1.1" 200 84413 Not Found: /assets/media/avatars/avatar15.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar15.jpg HTTP/1.1" 404 2917 Not Found: /assets/media/avatars/avatar2.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar2.jpg HTTP/1.1" 404 2914 Not Found: /assets/media/avatars/avatar1.jpg Not Found: /assets/media/avatars/avatar13.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar1.jpg HTTP/1.1" 404 2914 Not Found: /assets/media/avatars/avatar11.jpg [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar13.jpg HTTP/1.1" 404 2917 [22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar11.jpg HTTP/1.1" 404 2917 -
django Submit function does not save data in database
I just started using django and this is my first app. i created "contact form" depending on several tutorials i'v seen, but it doesn't save data to database plus doesn't direct me to the "Thank you" html page. tried many scenarios but none worked can anyone help? i'm open to change any thing in the code just to make it work and save the data that i need to save. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # 'crispy_forms', 'widget_tweaks', models.py from django.db import models from django.conf import settings from datetime import date class Snippet(models.Model): MALE = 'MA' FEMALE = 'FE' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), ] LOCAL= 'SA' NONE_LOCAL = 'NS' NAT_CHOICES = [ (LOCAL, 'Local'), (NONE_LOCAL, 'Non_Local'), ] RIYADH = 'RH' JEDDAH = 'JH' CITY_CHOICES = [ (RIYADH, 'Riyadh'), (JEDDAH, 'Jeddah'), ] DIPLOMA = 'DP' BACHELOR = 'BA' HIGHEREDU = 'HE' OTHER = 'OT' EDU_CHOICES = [ (DIPLOMA, 'Diploma'), (BACHELOR, 'Bachelor'), (HIGHEREDU, 'Higer Edu'), (OTHER, 'Other'), ] ONE = 'On' FIVE = 'Fi' OTHER = 'Ot' INC_CHOICES = [ (ONE, '100-500'), (FIVE, '500-1000'), (OTHER, 'Other'), ] name = models.CharField(max_length=100) email = models.EmailField() mobile = models.IntegerField(default=None) gender = models.CharField( max_length=2, choices=GENDER_CHOICES, default=MALE) nat … -
Cannot delete entries from database on Django
On admin page , I created a delete entries button . I clicked and it asked me yes or no .I click yes but no effect . (The whole system designed with Django ) How to solve ? On A.html <button class="btn btn-danger btn-sm" style = "padding: 2px 4px;" id="delete"onclick = "Del('{{i.id}}')">Delete</button> <script> function Del(id){ console.log("delet*********") swal({ title: "Are you sure?", text: "To Delete this Entry!", icon: "warning", buttons: ["No", "Yes"], closeOnClickOutside: false, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ method : "POST", url : "/delete_lost_item/", data : { 'id':id, }, success : function(response){ if (response == "success"){ swal("Entry has been Deleted..!", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.reload(); }); } } }) } }); } </script> on Table Lost_Item class Lost_Item_table(admin.ModelAdmin): list_display = ['id','lebal','title','brand','species'...] URL.PY url(r'^delete_lost_item/$',delete_lost_item, name='delete_lost_item'),