Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to play a sound saved in a known directory with Django, via python script (not template)?
I am developing an app in Django. I have a mp3 file saved in directory my_project/static/sounds/1607.mp3 I have a script.py file located in my_project/my_app/my_folder How can I tell my django to play it at the end of a script.py? -
(index):135 POST http://127.0.0.1:8000/hom 403 error
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script> function stopDefault(event) { event.preventDefault(); event.stopPropagation(); } function dragOver(label, text) { /* ADD ALMOST ANY STYLING YOU LIKE */ label.style.animationName = "dropbox"; label.innerText = text; } function dragLeave(label) { /* THIS SHOULD REMOVE ALL STYLING BY dragOver() */ var len = label.style.length; for(var i = 0; i < len; i++) { label.style[label.style[i]] = ""; } label.innerText = "Click to choose images or drag-n-drop them here"; } function addFilesAndSubmit(event) { var files = event.target.files || event.dataTransfer.files; document.getElementById("filesfld").files = files; submitFilesForm(document.getElementById("filesfrm")); } function submitFilesForm(form) { var label = document.getElementById("fileslbl"); dragOver(label, "Uploading images..."); // set the drop zone text and styling var fd = new FormData(); for(var i = 0; i < form.filesfld.files.length; i++) { var field = form.filesfld; fd.append(field.name, field.files[i], field.files[i].name); } var progress = document.getElementById("progress"); var x = new XMLHttpRequest(); if(x.upload) { x.upload.addEventListener("progress", function(event){ var percentage = parseInt(event.loaded / event.total * 100); progress.innerText = progress.style.width = percentage + "%"; }); } x.onreadystatechange = function () { if(x.readyState == 4) { progress.innerText = progress.style.width = ""; form.filesfld.value = ""; dragLeave(label); // this will reset the text and styling of the drop zone if(x.status == 200) { var images = JSON.parse(x.responseText); for(var i = 0; i < images.length; i++) … -
Use {% empty %} but in a form
I have a form : routine_form.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Créer une récurrence </legend> {{ form.media }} {{ form|crispy }} <div class="alert alert-warning" role="alert"> <strong>Astuce : </strong> Utilisez la touche <strong>CTRL</strong> sur Mac ou PC pour séléctionner plusieurs tâches. </div> </fieldset> <div class="form-group"> <button class="btn btn-success" type="submit">Ajouter</button> </div> </form> This form used the model RoutineList class Routinelist(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") Basicaly, RoutineList is used to create some tasks and then the form Routine used one or all of them to create a category like "Daily routine > wash my car > workout" etc. I want to show a message for when there is no task added by the user, something like "Please add a task first" I use the balise {% empty %} usually but it does not work here. -
when form is submit then a error is occur
when i click on remmber and submit the form then a error is occured MultiValueDictKeyError at /seller/ 'out' Request Method: POST Request URL: http://127.0.0.1:8000/seller/ Django Version: 2.2.7 Exception Type: MultiValueDictKeyError Exception Value: 'out' Exception Location: /home/krishan/.local/lib/python3.6/site-packages/django/utils/datastructures.py in getitem, line 80 Python Executable: /usr/bin/python3 Python Version: 3.6.8 Python Path: ['/home/krishan/Desktop/property', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/krishan/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Tue, 26 Nov 2019 10:27:23 +0000 views.py def register_seller(request): rm = request.POST.get('remember','off') if rm == 'on': if request.method == 'POST': userName = request.POST['userName'] state = request.POST['state'] city = request.POST['city'] full_address = request.POST['fulladdress'] out = request.FILES['out'] bedroom_no = request.POST['bedroom_no'] kithen_img = request.FILES['kitchen'] swimming_img = request.FILES['swimming'] phone = request.POST['phone'] email = request.POST['email'] price = request.POST['price'] floor = request.POST['floor'] squre = request.POST['squre'] garden_img = request.FILES['garden'] each = seller_detail(state=state,city=city,full_address=full_address,pro_img=out,username=userName,bedroom_no=bedroom_no,kitchen_img=kithen_img,swimming_img=swimming_img,phone=phone,email=email,price=price,floor=floor,squre=squre,gerden_img=garden_img) each.save() return redirect('home') else: return render(request,'all/seller_input.html',{'remember':'Please checkout the button'}) else: return render(request,'all/seller_input.html') -
Gunicorn failed with 203/EXEC
I'm trying to deploy my django project on CentOS 8 follow by this manual https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 My project folder is /home/xmahop/support_cabinet/support_cabinet/manage.py virtualenv folder is /home/xmahop/support_cabinet/venv/ etc/systemd/system/gunicorn.service file is [Unit] Description=gunicorn daemon After=network.target [Service] User=xmahop Group=nginx WorkingDirectory=/home/xmahop/support_cabinet/support_cabinet ExecStart=/home/xmahop/support_cabinet/venv/bin/gunicorn --workers 3 --bind unix:/home/xmahop/support_cabinet/support_cabinet/support_cabinet/support_cabinet.sock support_cabinet.wsgi:application [Install] WantedBy=multi-user.target nginx conf: server { listen 80; server_name 192.168.136.131; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xmahop/support_cabinet; 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; proxy_pass http://unix:/home/xmahop/support_cabinet/support_cabinet.sock; } } gunicorn status: Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Tue 2019-11-26 12:36:20 MSK; 33s ago Process: 9188 ExecStart=/home/xmahop/support_cabinet/venv/bin/gunicorn --workers 3 --bind unix:/home/xmahop/support_cabinet/support_cabinet/support_cabinet/support_cabinet.sock support_cabinet.wsgi:application (code=exited, status=> Main PID: 9188 (code=exited, status=203/EXEC) Nov 26 12:36:20 localhost.localdomain systemd[1]: Started gunicorn daemon. Nov 26 12:36:20 localhost.localdomain systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Nov 26 12:36:20 localhost.localdomain systemd[1]: gunicorn.service: Failed with result 'exit-code'. Nginx logs are empty. I'm tried chown xmahop:nginx to project folder and gunicorn conf file -
Sometime, object is not iterable
I try to solve this problem but I can't. It has a problem about iteration. views.py if borrow: borrow_item = Borrow_Item.objects.filter(borrow_id = borrow) for it in items: it_id = int(it) item_id = Item.objects.get(id=it_id) count = 0 for brit in borrow_item: if item_id.id == brit.item_id.id: count = count+1 break if count == 0: borrow_item = Borrow_Item(id=None, borrow_id=borrow, item_id=item_id) borrow_item.save() Sometime, it show " 'Borrow_Item' object is not iterable ". These are case that it's normal. Choose one new item. Choose more than one, by all items that select has been selected previously.(item is in cart) Choose two item, by choose one item has been selected and that item id less than another item id (new item). In the case that it causes an error. Choose more than one, by there are at least one item that has id less than existing items id Sorry, If I can't communicate to you to understand -
Integrating Dagster with Django
Hi I am trying to integrate Dagster into ongoing Django project. I am kind of struggling with providing Django context (models, apps, ...) to Dagster. As of now I am just checking wether dagit is present in sys.argv[0] in init.py of apps that are using Dagster. <!-- language: python --> ## project/app/__init__.py import sys import django if 'dagit-cli' in sys.argv[0]: print('dagit') django.setup() Can anyone help me with setup? -
I can not use django template-tag linebreak and justify
I try to justify some text that i get from my database but I also need to use the template-tag linebreak. html: <p class="justify">{{ article.contenu|linebreaks }}</p> css: .justify { text-align: justify!important; } My text won't justify itself unless I remove linebreak tag. Got any idea how to use justify and linebreak tag together ? Cordially -
Print Report in React (Client Side)
I have been stuck here for almost one month. I don't know how to achieve this one. After doing the rest task, I have to come back to this issue. Explanation Now I am doing a web app with reacts as front-end and Django as back-end that is a version upgrade from the desktop application. In the desktop application, I have done the report with crystal report and my client very likes this design. So Now client requests me to do the same design in the web app. Nightmare is coming now. How to print report in React or Django? My report has summary lines,group-by lines and other functions that support by crystal report, As u know, Event through these things are not the big deal in crystal report, In Web app, I have no idea for this. Should I print pdf with line and box and all things design by myself? I think this would be taken very long time because I have a lot of different design reports. I tried PDFMake but it does not support IE and JSPDF is I have no idea how to do for summary line and group-by line. Is there any way to … -
ModuleNotFoundError at /admin No module named 'winsound'
I am developing an app in Django. My app plays a sound using winsound module. import sys import winsound duration = 150 # milliseconds freq = 440 # Hz winsound.Beep(freq, duration) winsound.Beep(freq, duration) winsound.Beep(freq, duration) It worked fine as soon as I was developing in local, but when I pushed the app to heroku and then tryed to access the admin section, the web returned the error ModuleNotFoundError at /admin No module named 'winsound' So I tryed to pip install windsound , but apparently there is no moduled named so available for download. Thinking that the module was maybe already installed but with another name, I also tried pip freeze>requirements.txt and added 'winsound' in INSTALLED_APPS, but nothing worked. On the web I can find little information on winsound module and it appears it is not available to pip install with python... Does anybody knows how to solve it? -
My Django Admin fields does not show non asccii data correctly
I have a Django 1.11 Project with Mysql 5.7. When I write non-ASCII characters in the Django admin fields e.g. (چترال کا منظر), they display as ????????????. It does seem my database is not storing the data as I want it to; here is the my database charset. What am I missing here? -
Django NoReverseMatch at /provider/ 'provider ' is not a registered namespace
i'm learning Django and this my first project i have the above error for days trying to solve it . if i put blank html it will work but the below template makes error the HTML file is below {% extends 'base.html' %} {% block body %} <!-- Products --> <div class="total-ads main-grid-border"> <div class="container"> <div class="select-box"> <div class="browse-category ads-list"> <label>Browse Categories</label> <select class="selectpicker show-tick" data-live-search="true"> <option data-tokens="Mobiles">All</option> <option data-tokens="Mobiles">Mobiles</option> <option data-tokens="Electronics & Appliances">Electronics & Appliances</option> <option data-tokens="Cars">Cars</option> <option data-tokens="Bikes">Bikes</option> <option data-tokens="Furniture">Furniture</option> <option data-tokens="Pets">Pets</option> <option data-tokens="Books, Sports & Hobbies">Books, Sports & Hobbies</option> <option data-tokens="Fashion">Fashion</option> <option data-tokens="Kids">Kids</option> <option data-tokens="Services">Services</option> <option data-tokens="Jobs">Jobs</option> <option data-tokens="Real Estate">Real Estate</option> </select> </div> <div class="search-product ads-list"> <label>Search for a specific product</label> <div class="search"> <div id="custom-search-input"> <div class="input-group"> <input type="text" class="form-control input-lg" placeholder="Buscar" /> <span class="input-group-btn"> <button class="btn btn-info btn-lg" type="button"> <i class="glyphicon glyphicon-search"></i> </button> </span> </div> </div> </div> </div> <div class="clearfix"></div> </div> <div class="all-categories"> <h3> Select your category and find the perfect ad</h3> <ul class="all-cat-list"> </ul> </div> <ol class="breadcrumb" style="margin-bottom: 5px;"> <li><a href="/">Home</a></li> <li class="active"><a active href="{% url 'provider:provider_list' %}> All Categories </a> </li> {% if category %} <li class="active">{{category}} </li> {% endif%} </ol> <div class="ads-grid"> <div class="side-bar col-md-3"> <div class="search-hotel"> <h3 class="sear-head">Search</h3> <form method="GET" action="{% url … -
How to customize django group model
I want to change django default User and Group model relation from ManyToMany to OneToOne.But I don't know the right way to do this.I tried like this but the user field clashes roles.Role.user: (models.E006) The field 'user' clashes with the field 'user' from model 'auth.group' . models.py class Role(Group): user = models.OneToOneField(User,on_delete=models.CASCADE) -
I'am building online shop with python django
I'm working with Django to build online store and i built a cart system and i make a mistake i delete all product from data but when i deleted i found old product still on cart page and cart didn't work and give me this error enter image description here this is the cart class from decimal import Decimal from django.conf import settings from shop.models import Product from coupons.models import Coupon class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) # store current applied coupon self.coupon_id = self.session.get('coupon_id') if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart @property def coupon(self): if self.coupon_id: return Coupon.objects.get(id=self.coupon_id) return None def get_discount(self): if self.coupon: return (self.coupon.discount / Decimal('100')) \ * self.get_total_price() return Decimal('0') def get_total_price_after_discount(self): return self.get_total_price() - self.get_discount() def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0,'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def … -
Not able to authenticate Askbot with LDP authentication provider
Not able to authenticate Askbot django application on Ubantu 18.04- Able to ping the LDAP server, but still it says - "Can't contact LDAP server" Error logs shows:- Traceback (most recent call last): File "/srv/askbot/venv/local/lib/python2.7/site-packages/askbot/deps/django_authopenid/ldap_auth.py", line 127, in ldap_authenticate_default get_attrs File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 854, in search_s return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 847, in search_ext_s msgid = self.search_ext(base,scope,filterstr,attrlist,attrsonly,serverctrls,clientctrls,timeout,sizelimit) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 843, in search_ext timeout,sizelimit, File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 331, in _ldap_call reraise(exc_type, exc_value, exc_traceback) File "/srv/askbot/venv/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 315, in _ldap_call result = func(*args,**kwargs) SERVER_DOWN: {u'info': 'Transport endpoint is not connected', 'errno': 107, 'desc': u"Can't contact LDAP server"} -
How to pass value from HTML tag (other than <input> tag ) to view using Form?
How to pass value from HTML tag (other than tag ) to view using Form ? In Django I need to submit a form and pass the value holded in tag to view <div> <h3 class="media-title" id="user_name" name="user_name"> {{ username}} </h3> <button class="btn btn-small"> <a href="{% url 'add_to_group' %}"><i class="icon-plus">Add</i> </a> </button> </div> How do i fetch the value {{ username }} in view add_to_group ? -
What does binascii.hexlify(os.urandom(32)).decode() mean?
I'm trying to develop a function which would refresh token model in django rest framework.They seem to use binascii.hexlify(os.urandom(32)).decode() for generating unique tokens for every user.How does this line ensures that token generated by it will always be unique.Suppose if i want to refresh content of token after every 10 months ,then, will binascii.hexlify(os.urandom(32)).decode() will generate unique key that has not been used by any current user or i need to check whether it is being used or not? -
Django TinyMce was installed but is not working
I've installed django-tinymce and it works on my pc very well. But when I pushed to github, and downloaded to my Mac. When I want to run server it shows error as following: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tinymce' -
Javascript to Django
var upload = function(files) { $.ajax({ type: 'POST', processData: false, contentType: false, cache: false, data: {csrfmiddlewaretoken:'{{csrf_token}}', files:files}, enctype: 'multipart/form-data', url: 'files/', }); } I try to send files to Django but I am getting this error. jquery-3.4.1.min.js:2 POST http://localhost:8000/upload/files/ 403 (Forbidden) -
Django: How to download all files as zip when button is clicked?
I've seen so many answers on how to serve zip files for download in Django but no one is explicitly telling how to call it in the client side. Maybe the answer is too obvious but I really don't get it. I have a datatable and I've included a download button in each row. When the user clicks it, all associated files will be downloaded as zip. Here's my code: In my views.py: def download_zipfile(self, request): filelist = [MyModel.path_to_file1, MyModel.path_to_file2, MyModel.path_to_file3] byte_data = BytesIO() zip_name = "%s.zip" % MyModel.id_no zip_file = zipfile.ZipFile(byte_data, 'w') for file in filelist: filename = os.path.basename(os.path.normpath(file)) zip_file.write(file, filename) zip_file.close() response = HttpResponse(byte_data.getvalue(), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=%s' %zip_name zip_file.printdir() return response In my urls.py I have: urlpatterns = [ path('download/<int:pk>', download_zipfile, name='download_zipfile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my html template I have: <tr id="datarows"> <td>{{ mymodel.data1 }}</td> <td>{{ mymodel.data2 }}</td> <td>{{ mymodel.data3 }}</td> <td> <a href="{% url 'download_zipfile' mymodel.pk %}" target="_blank"> <i class="fas fa-download"></i> </a> </td> </tr> And I keep getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'download_zipfile' with arguments '('',)' not found. 1 pattern(s) tried: ['download/(?P<pk>[0-9]+)$'] I would really appreciate it if anyone would be able to help. Thanks in advance! -
Retrieve query from django ORM with related fields
I created a Company in my django app, two or more person can login with the same company. I want to show the data of one user of the company to the other user of the company. To simplify: If one user of a company creates an object, then it should be visible to all the users of that company But I am having trouble extracting the data Models.py class ItemBatch(models.Model): uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by') name = models.CharField(max_length=100) pid = models.IntegerField(blank=True) quantity = models.IntegerField(blank=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='ship_company') class User(AbstractUser): is_supplier = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) email = models.EmailField(default=False) class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) company_code = models.IntegerField(default=0) Views.py class allordersview(viewsets.GenericViewSet, mixins.ListModelMixin): queryset = ItemBatch.objects.all() serializer_class = holdSerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(uploaded_by_id=request.user) # ??Changes?? . . return Response(serializer.data) How to change the queryset such that it shows all ItemBatch of a Company ?? -
To put or not to put slash ("/") at the end of each url path
I know that using formerly url() there is a difference whether or not I put slash ("/") at the end of a sentence i.e. url(r'^fees_pricer/(?P<product>[\w-]+)/$', views.fees_pricer, name='fees_pricer'), I realized that I got the same result if I write: path('fees_pricer/<slug:prod>', views.fees_pricer, name='fees_pricer'), or path('fees_pricer/<slug:prod>/', views.fees_pricer, name='fees_pricer'), I am wondering if there is a difference or any best practice about putting shlash at the end of each path. Many thanks in advance for your answer. -
Django: How to set choices in a form to a Select widget
I am wondering if someone could help to figure out how to set initial choices to a CharField which has Select widget applied on a form level without overwriting the Meta class data(such as verbose_name coming from model level)? My form looks like that: from django.forms.widgets import Select class AssessmentFormModelForm): def __init__(self, *args, **kwargs): super(AssessmentForm, self).__init__(*args, **kwargs) # Intial choices set here (DOESN'T work) self.fields['test_taker_report_uid'].choices = [('', 'Placeholder')] class Meta: model = Assessment fields = ( 'test_taker_report_uid', ) widgets = { 'test_taker_report_uid': Select2, } I in fact know that I can make it work by removing widgets from Meta and adding it as a: class AssessmentFormModelForm): test_taker_report_uid = ChoiceField( widget=Select, choices=[('', 'Placeholder')] ) def __init__(self, *args, **kwargs): but it is annoying cause it overwrites verbose_name which i have specified on a model level, which i want to keep intact. -
django-paypal showing page not found when trying to checkout
I was able to install django-paypal and also created a sandox account, but the problem is when i try to checkout the process-payment display no page found. I think this have to do with the view.py or maybe the Order. How do i make this work properly? Model.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total Views.py: def process_payment(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % order.get_total().quantize( Decimal('.01')), 'item_name': 'Order {}'.format(order.id), 'invoice': str(order.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('shop:payment-done')), 'cancel_return': 'http://{}{}'.format(host, reverse('shop:payment-cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) context = { 'form': form, 'order': order } return render(request, 'process_payment.html', context) -
Django anonymous session issue
I have this anonymous session middleware: from __future__ import unicode_literals from importlib import import_module from django.conf import settings class AnonymousSessionMiddleware(): """This middleware is used for anonymous testing, creates an anonymous session. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = None if not response: response = self.get_response(request) if hasattr(self, 'process_request'): self.process_request(request) return response def process_request(self, request): if not request.user.is_authenticated and not request.session.session_key: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() request.session.create() And in my View I want to get the session_key (session_key = request.session.session_key) but it always be None. I think the problem is in my middleware because the def process_request(self, request) method runs after the View. What would be the best solution to launch this method first to create a new session before the View function gets called?