Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jquery not working with Whitenoise when adding compression and caching support
I have an app that is working fine with static files and jQuery when simply using WhiteNoise. However, I am trying to add the compression and caching support and I am facing some problems. As explained in their documentation, I added: #settings.py STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' Then I run python manage.py collectstatic, which creates many gzip compressed files. Finally, when I push it to Heroku some Javascript code is not working anymore, and the console shows several errors like this one: Uncaught ReferenceError: $ is not defined And also this one: Uncaught ReferenceError: jQuery is not defined These errors only happen when I push to Heroku, in my local environment with python manage.py runserver everything still works just fine. I tried what the legacy documentation suggests: Troubleshooting If you’re having problems with the WhiteNoise storage backend, the chances are they’re due to the underlying Django storage engine. This is because WhiteNoise only adds a thin wrapper around Django’s storage to add gzip support, and because the gzip code is very simple it generally doesn’t cause problems. To test whether the problems are due to WhiteNoise or not, try swapping the WhiteNoise storage backend for the Django one. If you’re running Django … -
Saving a Model and get it after save to use it as ForeignKey to create another Model
I have the following 2 models: class Note(models.Model): name= models.CharField(max_length=35) class ActionItem(models.Model): note = models.models.OneToOneField(Note, on_delete=models.CASCADE) target = models.CharField(max_length=35) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) In other models(based on some conditions) I trigger an utility function that create a Note: def create_note(target=None, action=None): note = Note(target=target, name=name).save() transaction.on_commit( ActionItem(note=note, target=target).save()) I get the following error: null value in column "note_id" violates not-null constraint DETAIL: Failing row contains (6, null). If I use: So, I presume the error appears because save, doesn't return anything. I need the Note to pass it as a FK to ActionItem, an be sure it was saved. -
Differentiate users in django
I am learning django framework. I have two group of users manager and employees. At the login page i want to differentiate these two groups. If employee has logged in then redirect it to homepage and if manager logged in redirect it to '/manage' page. how should i do this in django -
django modelform how to know input type is checkbook?
My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type. If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately. The default type='checkbox’ interface is too ugly models class Employee(AbstractBaseUser): """ 用户表 """ username = models.CharField(max_length=30, verbose_name='姓名') email = models.EmailField(verbose_name='邮箱', unique=True) is_true = models.BooleanField(default=False, verbose_name='是否超级用户') views class ModelFormDemo(ModelForm): class Meta: model = self.model if self.list_editable: fields = self.list_editable else: fields = '__all__' excluded = self.excluded def __init__(self, *args, **kwargs): super(ModelFormDemo, self).__init__(*args, **kwargs) def add_view(self, request): form = ModelFormDemo() if request.method == "POST": res_dict = {'status': 1, 'msg': 'success'} form = ModelFormDemo(request.POST) if form.is_valid(): obj = form.save() else: res_dict['msg'] = form.errors res_dict['status'] = 2 return JsonResponse(res_dict) return render(request, "xadmin/add_view.html", locals()) html <form class="layui-form" method="post"> {% csrf_token %} {% for field in form %} {% if field.name == 'employee' %} <input type="hidden" name="employee" value="{{ user.id }}"> {% else %} <div class="layui-form-item"> <label class="layui-form-label">{{ field.label }}</label> <div class="layui-input-inline"> {{ field }} </div> </div> {% endif %} {% endfor %} <div class="layui-form-item"> <div class="layui-input-block"> <input type="button" class="layui-btn" lay-filter="add" lay-submit="" value="add"> </input> <button type="reset" class="layui-btn layui-btn-primary">reset</button> </div> </div> </form> -
django nginx cant serve image on https browser say mixed content
hi i used lets encrypt to make https for my django-angular app now my site load in https but my product image that are in my upload folder not serve in "http" and browsers say mixed content and that image are loading in http. you can see that in this image -> here in my nginx config : server { listen 80; server_name robinlearn.com www.robinlearn.com 94.130.4.123; return 301 https://robinlearn.com$request_uri; } server { listen 443 default ssl http2; server_name 94.130.4.123; include snippets/ssl-robinlearn.com.conf; proxy_set_header X-Forwarded-Proto https; ssl_prefer_server_ciphers On; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS; client_max_body_size 1024M; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; error_page 503 @maintenance; location @maintenance { root /home/vertical/academy/static; rewrite ^(.*)$ /maintenance.html break; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; add_header Access-Control-Allow-Origin *; proxy_pass http://unix:/home/vertical/academy/academy.sock; } location /.well-known { root /home/vertical/academy/api/v1/store/; } location /static { root /home/vertical/academy/; } location /robots.txt { root /home/vertical/academy/api/v1/store/sitemap/robots.txt; } } also i addes this line to my setting.py file SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') how can i fix this issue? -
Django how to send an email with the user link?
Hi i am newbie in Django just learning from the documentation.I just used django send an email https://docs.djangoproject.com/en/2.1/topics/email/. i want to send an email in join message want to send an a url with its driver ID in it for book a car . how do i send an url with his id . for example i am having 4 user in my employe site . our company employe hit the link send an email to the user which is registered . after click on send an email how do i get the driver id in my url and send him as in join message a link where his id in the url . Views.py def rentacar_carapp_approve(request): if request.POST: try: args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = driver_email if to_email is not None: join_message = """Please hit the link and book a car "url with his id " """ send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) print("email sent") except Driver.DoesNotExist: print("Driver doesn't exists") return HttpResponseRedirect('/mega-admin/rentacar/carapp-manager/') Url.py url(r'^rentacar/car/(\d+)/driver/(\d+)/$', extension_views.rentacar_car), -
Celery worker exiting prematurely during Matplotlib subplot()
I'm using Celery with django and django-celery-beat/django-celery-results. Celery works fine up until it reaches this bit of code: figure, ax = plt.subplots(figsize=(15,3)) It then exits citing signal 11: [2018-09-04 19:43:21,928: ERROR/MainProcess] Process 'ForkPoolWorker-1' pid:42611 exited with 'signal 11 (SIGSEGV)' [2018-09-04 19:43:21,962: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/Users/user/.local/share/virtualenvs/venv/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). Know what might be happening? Celery settings: CACHE_LOCATION = "redis://%s:6379" % REDIS_HOST CELERY_BROKER_URL = CACHE_LOCATION CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' versions: billiard==3.5.0.4 celery==4.1.0 -
Django - querying many FK models from parent
Given the following pseudo code: class A(models.Model) class B(models.Model) a = models.FK(A) class C(models.Model) b = models.FK(B) class D(models.Model) b = models.FK(B) If I have the PK of A, how may I retrieve all related instances of every child model? (B, C and D). I hope that makes sense. Thank you -
Correct way to configure caddy, S3, and CloudFront
My ultimate goal is having Caddy, Django, S3, and CloudFront with best practice setup. Current situation: Caddy, Django, S3(No CloudFront yet) The problem is Chrome is not execute front from S3, but css it does Here is the console errors Access to Font at 'https://herr.s3.amazonaws.com/static/admin/fonts/Roboto-Regular-webfont.woff' from origin 'https://herr.reviews' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://herr.reviews' is therefore not allowed access. Access to Font at 'https://herr.s3.amazonaws.com/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'https://herr.reviews' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://herr.reviews' is therefore not allowed access. I am doubt. If my configuration is wrong. Why css comes to the browser? here is my admin url CaddyFile www.{$DOMAIN_NAME} { redir https://herr.reviews } {$DOMAIN_NAME} { proxy / django:5000 { header_upstream Host {host} header_upstream X-Real-IP {remote} header_upstream X-Forwarded-Proto {scheme} } log stdout errors stdout gzip } I confirm I can upload and download media file from S3 CaddyFile is a default setup form django-cookies-cutter Question: Where am I wrong? -
What can cause pycharm debugger freeze with docker compose?
I'm using docker-compose to run project with three containers: django, postgres, redis. When I launching it in Pycharm Pro 2018.2.2 with simple "RUN" it works, but when I'm launching it with debug mode, it freezes. As I understand, there are 2 processes: watcher that reloads server and the dev-server itself. If connect bash into container and run top: 1 root 20 0 1071804 97980 30028 S 0.3 0.6 0:16.39 python 27 root 20 0 394948 48244 11088 S 0.0 0.3 0:00.85 python 37 root 20 0 18212 3184 2860 S 0.0 0.0 0:00.01 bash 53 root 20 0 21952 2448 2124 R 0.0 0.0 0:00.19 top i can see, there are 2 processes (as in normal run mode) what can it be? docker-compose version 1.21.2, build a133471 docker-py version: 3.4.1 CPython version: 2.7.15rc1 OpenSSL version: OpenSSL 1.1.0g 2 Nov 2017 Docker version 18.06.1-ce, build e68fc7a -
Gunicorn not creating .sock file on AWS EC2
I'm stuck with creating a Django web app following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#check-for-the-gunicorn-socket-file I think I've read all related questions on SO: django gunicorn sock file not created by wsgi Gunicorn not generating sock file https://github.com/benoitc/gunicorn/issues/1166 None of them helped. I'm following each step exactly as described but still the myapp.sock file is not created. The main project directory is /home/ubuntu/puchalatravel It's content: ubuntu@ip-172-31-35-104:~/puchalatravel$ ls -l total 60 -rw-r--r-- 1 ubuntu ubuntu 40960 Sep 4 09:37 db.sqlite3 -rwxrwxr-x 1 ubuntu ubuntu 545 Sep 4 07:42 manage.py drwxrwxr-x 3 ubuntu www-data 4096 Sep 4 09:32 puchalatravel drwxrwxr-x 4 ubuntu ubuntu 4096 Sep 4 07:41 puchalatravelenv drwxrwxr-x 3 ubuntu ubuntu 4096 Sep 4 09:34 static Access to the folder: ubuntu@ip-172-31-35-104:~$ ls -l total 1616 drwxrwxr-x 4 ubuntu ubuntu 4096 Aug 30 07:25 eb-virt -rw-rw-r-- 1 ubuntu ubuntu 1642522 Aug 30 07:11 get-pip.py drwxrwxr-x 6 ubuntu www-data 4096 Sep 4 09:37 puchalatravel Content of /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/puchalatravel ExecStart=/home/ubuntu/puchalatravel/puchalatravelenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/puchalatravel/puchalatravel.sock puchalatravel.wsgi:application [Install] WantedBy=multi-user.target Content of /etc/nginx/sites-available/puchalatravel server { sserver { listen 8000; server_name ec2-18-188-249-6.us-east-2.compute.amazonaws.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/puchalatravel; } location / { include proxy_params; … -
customize django-controlcenter line chart stroke width
I am using django-controlcenter for a dashboard but the default line width of the LineChart is a bit too thick. Is there a way to customize the line width? Btw, i checked the chartist.js, there is configuration options for the line styles but can not find any place in django-controlcenter to do that. /* Use this selector to override the line style on a given series */ .ct-series-a .ct-line { /* Set the colour of this series line */ stroke: red; /* Control the thikness of your lines */ stroke-width: 5px; /* Create a dashed line with a pattern */ stroke-dasharray: 10px 20px; } -
Stopping services started in django appconfig ready() function?
If I am starting some services or threads inside ready() function of a django application. Here are few questions that I have in same regards: How to gracefully shutdown django server? Similar to ready() function is there some sort of shutdown function or should I be doing such things in some other fashion or style in django ? -
Django signals is functioning even for django - admin when written for a model
class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) def create_form(sender, instance, created, **kwargs): print('form sent') post_save.connect(receiver = create_form, sender= Leave) I've written a post_save signal for my model, so that each time the ModelForm is saved it print's form sent, but the same happens if I alter some fields in the /admin and save. How do I stop that and write another signal if admin alters any field. I've tried this for admin but it doesn't work from django.contrib import admin def admin_alter(sender, instance, created, **kwargs): if Leave.status == '1': print('admin altered') post_save.connect(receiver = after_accepting, sender= admin) -
Django; How to write the process to update ImageField manually?
I'm working on test in Django project. I want to test validator that is related to the image's width and height. But I couldn't figure out how to do it. How can I set size parameter when updating the image? class TestValidators(TestCase): def setUp(self): self.user = CustomUser.objects.create(username='user1') def test_validate_user_image(self): #set the user's image and test it -
I want to return file url use Django。in order to web font can download the file with the link what should i do?
I have no idea how to return file url use Django。in order to web font can download the file with the link. who can help me. thanks anyone who can offer ideas. -
How to set the `app_settings`'s `AuthenticationMethod` to `username_email`?
In my project I use the allauth, and in my custom LoginSerializer's validate method: if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Authentication through username if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: user = self._validate_username(username, password) you see there are app_settings.AuthenticationMethod.EMAIL and app_settings.AuthenticationMethod.USERNAME types. I read the source code I found the: There has another type USERNAME_EMAIL : class AppSettings(object): class AuthenticationMethod: USERNAME = 'username' EMAIL = 'email' USERNAME_EMAIL = 'username_email' Where can I set the allauth use the AuthenticationMethod.USERNAME_EMAIL? -
Django modal loginview - error: "form" should contain a valid Django Form
I'm trying to do my login with bootstrap modal so it can be accessed from any page through my navbar with the login-popup. The problem now is how do I pass that form on so all of the pages can access it? At the moment I get this error: BootstrapError at / Parameter "form" should contain a valid Django Form. Instead of using a seperate page for my login form I have now this: login3.html {% load bootstrap3 %} <div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" align="center"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </div> <div id="div-forms"> <form id="login-form" action="{% url 'login3' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-body"> {% bootstrap_form form %} </div> <div class="modal-footer"> {% buttons %} <button type="submit" class="btn btn-primary">Login</button> {% endbuttons %} </div> </form> </div> </div> </div> </div> View: class Login3View(NextUrlMixin, RequestFormAttachMixin, FormView): form_class = LoginForm template_name = 'accounts/login3.html' success_url = '/' default_next = '/' And then I'm simply including the template login3.html together with my navbar so the form gets loaded at every page. I saw at a different question an answer from C14L (Django login from in modal window) that looked … -
How to perform aggregate or function for fields present in different model but inter-related?
This is my code class ledger1(models.Model): Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2) User_Name = models.CharField(max_length=100) Address = models.TextField() State_Name = ( ('Choose','Choose'), ('Andra Pradesh','Andra Pradesh'), ('Arunachal Pradesh','Arunachal Pradesh'), ('Assam','Assam'), ('Bihar','Bihar'), ('Chhattisghar','Chhattisghar'), ('Goa','Goa'), ('Gujrat','Gujrat'), ('Haryana','Haryana'), ('Himachal Pradesh','Himachal Pradesh'), ('Jammu and Kashmir','Jammu and Kashmir'), ('Jharkhand','Jharkhand'), ('Karnataka','Karnataka'), ('Kerala','Kerala'), ('Madhya Pradesh','Madhya Pradesh'), ('Maharasthra','Maharasthra'), ('Manipur','Manipur'), ('Meghalaya','Meghalaya'), ('Mizoram','Mizoram'), ('Nagaland','Nagaland'), ('Odisha','Odisha'), ('Punjab','Punjab'), ('Rajasthan','Rajasthan'), ('Sikkim','Sikkim'), ('Tamil Nadu','Tamil Nadu'), ('Telengana','Telengana'), ('Tripura','Tripura'), ('Uttar Pradesh','Uttar Pradesh'), ('Uttarakhand','Uttarakhand'), ('West Bengal','West Bengal'), ) State = models.CharField(max_length=100,choices=State_Name,default='Choose') Pin_Code = models.BigIntegerField() PanIt_No = models.CharField(max_length=100,blank=True) GST_No = models.CharField(max_length=100,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("accounting_double_entry:ledgerdetail", kwargs={'pk':self.pk}) class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,) Credit = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return str(self.By) def get_absolute_url(self): return reverse("accounting_double_entry:detail", kwargs={'pk':self.pk}) I was wondering how can I perform aggregate function for Debit and Credit field (which is under journal model) in order of which falls under ledger If I perform aggregate function in general it will give the total amount of debit and credit present in journal but I dont want that I want It should give the total amount which is present for a particular ledger... I have made foreign key relations for TO and By fields … -
Using django-ipware get_client_ip instead of get_real_ip
In django-ipware version 2.1 ; old get_real_ip function is deprecated. When I use the new get_client_ip ; my test units are not showing the same results. Means that the two functions do not behave the same. The following is an original test from django-ipware test unit (not mine) def test_http_x_forwarded_for_multiple(self): request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_FOR': '192.168.255.182, 10.0.0.0, 127.0.0.1, 198.84.193.157, 177.139.233.139', 'HTTP_X_REAL_IP': '177.139.233.132', 'REMOTE_ADDR': '177.139.233.133', } ip = get_real_ip(request) self.assertEqual(ip, "198.84.193.157") The above works fine of course, but I want to ensure that using the new get_client_ip will give the same results (for a system upgrade purposes). But the test is actually failing the assertion: def test_http_x_forwarded_for_multiple(self): request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_FOR': '192.168.255.182, 10.0.0.0, 127.0.0.1, 198.84.193.157, 177.139.233.139', 'HTTP_X_REAL_IP': '177.139.233.132', 'REMOTE_ADDR': '177.139.233.133', } ip, is_routable = get_client_ip(request) self.assertEqual(ip, "198.84.193.157") resulting: AssertionError: '177.139.233.132' != '198.84.193.157' After digging into the code, I found that the new get_client_ip is not iterating inside the meta like get_real_ip . It checks out the left-most ip (or right-most depending on the settings) and skips to the next meta if a Public IP is not found My question(s) now are: How can I call get_client_ip in a way that returns the same ip returned by … -
Parse django datetime field
I have a problem with serialization of datetime field. I'm using serializers.DateTimeField from django rest framework and I'm getting 400 status when I'm trying to send 2018-09-04T00:00:00+0100 as query param. If timezone offset is negative - it works perfect. Here is django error: "date": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." ] Also I found all input formats for datetime field and I'm sure that my datetime is valid print(formats.get_format_lazy('DATETIME_INPUT_FORMATS')) ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z', '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z', '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z', '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z', '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S%z'] -
AttributeError at /project/new/
I am trying make a project creating part for my django app. but I get this error: AttributeError at /project/new/ 'ProjectForm' object has no attribute 'save' This is my view: view.py def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = form.save() project.author = request.user project.published_date = timezone.now() project.save() return redirect('blog/project_detail.html', pk=project.pk) else: form = ProjectForm() return render(request, 'blog/project_new.html', {'form': form}) This is my model models.py class Project(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title this is my forms file forms.py class ProjectForm(forms.Form): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=True, help_text='Required.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') project_name = forms.CharField(max_length=30, required=True, help_text='Required') project_description = forms.CharField(max_length=10000, required=True, help_text='Required.') project_notes = forms.CharField(max_length=1000, required=False, help_text='Optional.') class Meta: model = Project fields = ('first_name', 'last_name', 'email', 'project_name', 'project_description', 'project_notes') And this is mt html file. I am not sure but in this part I cannot be sure about "button" code. I may be wrong project_detail.html <form method="POST" style="text-align: center" > {% csrf_token %} <input type='hidden' value='m3KqcAqxJtXsJLS8ZRfhlXvTiXc1G0K0Whojb71JSe4jDsHYPwuOWKPIlFELyGoQ'/> <p> <label for="id_first_name">name</label><br> <input type="text" name="first_name" required id="id_first_name" … -
how to save on database
Django code views.py: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from home.models import Post @csrf_exempt def home(request): context = {'request_method': request.method} if request.method == 'POST': context['request_payload'] = request.POST.dict() post_data = dict(request.POST) print(post_data) for key, value in post_data.items(): for subvalue in value: print(key, subvalue) if key == 'name': m = Post.name(subvalue) m.save() if key == 'description': print(subvalue) p = Post.description(subvalue) p.save() if request.method == 'GET': context['request_payload'] = request.GET.dict() return HttpResponse() code models.py from django.db import models class Post(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=150) Result in print(post_data) are {'name': ['luca', 'jeams'], 'description': ['all', 'all2']}. Result extract value in print(key, value) are : name Luca name jeams description all description all2 I would like to save this data on database, but it does not work. How can i do? -
add `@` and `.` match base on the `[\w-]+` regex
I use the bellow regex for matching the username: url(r'^(?P<username>[\w-]+)/$', UserDetailAPIView.as_view(), name="detail"), It works fine for ordinary characters, but now I want add the @ and . base the existing regex, can you tell me how to add it? -
Python Django pdfkit wkhtmltopdf UnknownContentError
I'm getting an UnknownContentError when generating a PDF document from a project URL (https://ourcodeworld.com/articles/read/241/how-to-create-a-pdf-from-html-in-django) - using pdfkit (wkhtmltopdf). Could someone please advise where I'm going wrong. This line causes the error: pdf = pdfkit.from_url('http://127.0.0.1:8000/cbib/open_detailed_research_outputs/', False, options) The URL is valid and displays the way it should in the browser. Could someone please advise where I'm going wrong. [Other URLs in my web app project seem to work except for this one.] For example, this works: pdf = pdfkit.from_url('http://127.0.0.1:8000/cbib/research_outputs/', False, options) Further error info: OSError at /cbib/open_detailed_research_outputs/download/ wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [=======> ] 13% [==============================> ] 50% Error: Failed to load http://127.0.0.1:8000/cbib/open_detailed_research_outputs/, with network status code 299 and http status code 500 - Error downloading http://127.0.0.1:8000/cbib/open_detailed_research_outputs/ - server replied: Internal Server Error [============================================================] 100% Counting pages (2/6) [============================================================] Object 1 of 1 Resolving links (4/6) [============================================================] Object 1 of 1 Loading headers and footers (5/6) Printing pages (6/6) [> ] Preparing [============> ] Page 1 of 5 [========================> ] Page 2 of 5 [====================================> ] Page 3 of 5 [================================================> ] Page 4 of 5 [============================================================] Page 5 of 5 Done Exit with code 1 due to network error: UnknownContentError Request Method: …