Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No difference between PUT and PATCH in Django REST Framework
Here are my simple viewset and serializer classes: class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'email', 'first_name', 'last_name'] .... class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Suppose I want to update only my user's first name. In that case, I should use PATCH {"first_name": "New First Name"}. But at the same time, it looks like that PUT {"first_name": "New First Name"} also works the same way, though it shouldn't, because it should expect that all the fields are specified. At least I thought so. Am I wrong? And if I'm, then what is the difference between update and partial_update in Django Rest Framework and is there any reason to keep them both (since any additional method implies additional testing, so the latter question is a bit philosophical). By the way, I'm using djangorestframework==3.8.2. Thank you. -
Django: How do I redirect a post and pass on the post data to another server
I have 2 Django apps on different servers. When processing a POST request in one of them I sometimes need to pass the request to the second app. Is there a way to do this kind of redirect? -
Can someone please explain why I would need to reference two models in Django?
Can someone explain how I would reference another model in Django and also why I would need to? -
Errors occurring when running django-cron
I have defined multiple crons in one of my apps in Django. When I run python manage.py runcrons the following error occurs. In the crons I'm accessing database and same table may be accessed by different crons. Also I'm doing my job by ,multiple concurrent subprocesses. File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/home/social/centralsystem/apps/crawler/utils.py", line 12, in user_queuing model.cancel_crawling() File "/home/social/centralsystem/apps/social/models.py", line 47, in cancel_crawling ).update(is_crawling_from=None) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/models/query.py", line 647, in update rows = query.get_compiler(self.db).execute_sql(CURSOR) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1205, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 900, in execute_sql raise original_exception File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 890, in execute_sql cursor.execute(sql, params) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/social/centralsystem/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: SSL error: decryption failed or bad record mac -
Saving Excel File as Table in the Django Database
is there any way to save an Excel File to the Django Database, so i can call the sheet with e.g. Document.objects.all? I have this as my views.py. def read_file(request): file = 'C:/Users/admin/Desktop/djangoexcel/media/documents/TestExcel.xlsx' test = pd.read_excel(file) test2 = (pd.DataFrame.to_html(test, classes = 'table table-striped')) return TemplateResponse(request, 'documents/read_file.html', {'test2' : test2}) def index(request): documents = Document template = loader.get_template('documents/index.html') context = { 'documents': documents } return HttpResponse(template.render(context, request)) def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('documents:index') else: form = DocumentForm() return render(request, 'documents/model_form_upload.html', { 'form': form }) This is my models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to="documents/") uploaded_at = models.DateTimeField(auto_now_add=True) I would like to manipulate the data from the Excel Sheet through a template so i can update, delete and add entries on the website with generic views or something like that. Is there any way to do it? -
Python - Django [error 404 page not found urls]
I have written the following simple piece of code, I just wanted to check whether when accessed the POST method, it says 405, but instead it says page not found. views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import helloform def index(request): form = helloform() return render(request, 'hello/index.html', {'form' : form}) def **addintodb**(request): form = helloform(request.POST) print(request.POST) return redirect(index) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), **path('add', views.addintodb, name='addtodb')**, ] index.html > **form action="{% url 'addtodb' %}" method="POST" role="form"** > ... > </form> -
Create custom filter
Currently my view is as follows: from rest_framework.permissions import AllowAny from dynamic_rest.viewsets import DynamicModelViewSet from django_filters.rest_framework import DjangoFilterBackend from .models import Purchase from .serializers import PurchaseSerializer class PurchasesViewSet(DynamicModelViewSet): queryset = Purchase.objects.all() serializer_class = PurchaseSerializer permission_classes = (AllowAny,) filter_backends = (DjangoFilterBackend,) filter_fields = ('name', 'color') Which allows me to filter by exact name and color. My data has a date field (DateField type). I would like to create a custom filter by "quarter", so that this kind of request: /purchases/?quarter=2018Q1 provides a list of objects with date field in the specified quarter. Note that quarter is not a model field. What would the approach of creating such a custom filter? -
How to send event email request from gmail to outlook in Django 2
I was trying to create an appointment management system where people can send invitation meeting mail to admin. I can send single mail from user to admin but how could I send an event email from Gmail to outlook Here is my settings.py code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'appoint@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 EMAIL_USE_TLS = True here is my views.py def sendRequest(request): email = EmailMessage('Subject', 'Body', to=['appoint@dekkotops.com']) email.send() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Now I need to send event email not a single mail from my system gmail accout -
Nginx, Gunicorn, Django, Celery(Redis): upstream prematurely closed connection 502 gateway
I run a setup with docker-compose on linux server. Two days ago I added gunicorn + nginx to the setup. Unfortunately, all rest api endpoints that start celery tasks stopped working (it returns 502 gateway not found). When I try to send a post form on calculate shortest path that starts celery task, 502 gateway returns. Issue: Summary URL: http://192.168.0.150:8001/tspweb/calculate_shortest_paths/ Status: 502 Bad Gateway Source: Network Address: 192.168.0.150:8001 Here are the logs from django container and nginx container. tspoptimization | [2018-10-31 07:26:30 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:15) nginx_1 | 2018/10/31 07:26:30 [error] 8#8: *9 upstream prematurely closed connection while reading response header from upstream, client: 192.168.0.103, server: localhost, request: "POST /tspweb/calculate_shortest_paths/ HTTP/1.1", upstream: "http://192.168.128.2:8001/tspweb/calculate_shortest_paths/", host: "192.168.0.150:8001", referrer: "http://192.168.0.150:8001/tspweb/warehouse_list.html" nginx_1 | 192.168.0.103 - - [31/Oct/2018:07:26:30 +0000] "POST /tspweb/calculate_shortest_paths/ HTTP/1.1" 502 157 "http://192.168.0.150:8001/tspweb/warehouse_list.html" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15" "- Everything was working perfectly before gunicorn + nginx were added (on local system without those 2 it works perfectly fine). That means that it is not timeout issue. My suspicion is that the nginx+gunicorn doesn't 'redirect' the POST request from form into celery. I started celery with loggging on to a file and this … -
Django apply styling to update filefield
I currently use django-imagekit to upload a file to a PostModel. I use the CreateView and a PostCreateForm to get the required field in the form and use css to style the form. Now when I create the PostUpdateView, the filefield receives additional tags and text without html elements. post_form_update.html <form action="" enctype="multipart/form-data" method="post" novalidate> {% csrf_token %} {{ form.as_p }} <div class="field-wrapper col s12 no-marg"> <button class="btn green" type="submit" value="Submit">Voeg toe</button> </div> </form> generated by browser <p> <label for="id_image">Image:</label> Huidige: <a href="/media/2018/10/25/20130513122019resized11651368441737.jpg">2018/10/25/20130513122019resized11651368441737.jpg</a> <input type="checkbox" name="image-clear" id="image-clear_id"> <label for="image-clear_id">Wissen</label><br> Wijzigen: <input type="file" name="image" accept="image/*" id="id_image"> </p> The paragraph containing the file-field shows the text "Huidige" and "Wijzigen", I would like to hide these but since they're not wrapped in an element I can't use CSS to hide them. I can't use display:none or color: #fff since I need the input file and label tag inside the paragraph. Any ideas? -
Why django-extra-views InlineFormSetFactory shows me 3 forms in place of 1?
I'm using django-extra-views to embed many-to-one objects forms in a main form. I have: # view.py from .models import Content, MultilanguageTitle from extra_views import CreateWithInlinesView, UpdateWithInlinesView, InlineFormSetFactory from .forms import TitleForm class TitleInline(InlineFormSetFactory): model = MultilanguageTitle fields = '__all__' form_class = TitleForm class CreateContent(LoginRequiredMixin, CreateWithInlinesView): model = Content fields = "__all__" template_name = "content/create_content.html" inlines = [TitleInline] def form_valid(self, form): return super(CreateContent, self).form_valid(form) ... My template is in the following: <div class="form-group title-repeater"> <div class="form-group"> <label>Title - Language</label> <div data-repeater-list="repeater-group"> {% for formset in inlines %} {% for form in formset %} <div class="input-group mb-1" data-repeater-item> <div class="col-md-9 pl-0"> {{ form.text }} </div> <div class="col-md-1 pl-0"> {{ form.lang_code }} </div> <div class="col-md-1 pl-0" id="button-addon2"> <button class="btn btn-danger" type="button" data-repeater-delete><i class="ft-x"></i></button> </div> </div> {% endfor %} {% endfor %} </div> </div> <button type="button" data-repeater-create class="btn btn-primary"> <i class="ft-plus"></i> Add title in another language </button> </div> I have a question and a problem: problem: this code is running but I display 3 forms in formset and I don't understand why because I am in creation phase. Is there any config param set to 3 in the stack? Is there any other reason? question: I'm using this library because I have to implement … -
User object not iterable when using exclude
My function: @login_required(login_url='/account/login/') def SearchView(request): query = request.GET.get("search") # if query: profile = User.objects.filter( Q(is_client=True,first_name__icontains=query) | Q(is_client=True,last_name__icontains=query) ).exclude(request.user).distinct() hub = Hub.objects.filter( Q(name__icontains=query) ) task = Task.objects.filter( Q(title__icontains=query), ) results = list( chain(profile, hub, task)) # key=lambda objects: objects.created_at paginator = Paginator(results, 5) # Show 5 contacts per page page_request_var = "page" page = request.GET.get(page_request_var) contacts = paginator.get_page(page) notifications = Notification.objects.filter(receiver=request.user) context = { 'profile':profile, 'page_request_var':page_request_var, 'contacts': contacts, } return render(request,'search.html',context) I want the search results to exclude current user. The users are sent as profile.The problem is ,when i use exclude, Its showing error "User object is not iterable" . -
How to force install package in virtualenv ?
Trying to install django with different version that in system, it shows me: Installing collected packages: Django Found existing installation: Django 1.7.11 Not uninstalling django at /home/user/lib/python2.7, outside environment /home/user/webapps/v2_dev/venv Successfully installed Django-1.8.19 But in fact there is old version tried with different commands: ./venv/bin/pip install Django==1.8.11 pip install Django==1.8.11 -
migrate error 'No migration to apply' also not add table in postgresql in django
I'm trying to create a model for an eCommerce site but after makemigrations when I trying to migrate terminal show "No migration to apply" but when I checked database no new table was there. Please help me. ` from django.db import models from django.utils import timezone # Create your models here. class Collection(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ProductCategory(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Color(models.Model): color = models.CharField(max_length=50, null=True) def __str__(self): return self.color class Size(models.Model): size = models.CharField(max_length=20, null=True) def __str__(self): return self.size class Products(models.Model): name = models.CharField(max_length=200, null=True) for_people = models.ForeignKey(Collection, on_delete=models.CASCADE) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) description = models.TextField() old_price = models.FloatField(null=True, blank=True) price = models.FloatField(null=True) input_date = models.DateTimeField(auto_now=False, auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.name class Image(models.Model): product_name = models.ForeignKey(Products, related_name='pro_images', on_delete=models.CASCADE) image = models.ImageField(upload_to='media/product_img/', null=True, blank=True) def __str__(self): return self.product_name.name + 'image' ` The below picture of my terminal please check it Terminal show -
Using property field in annotate in Django 2
I'm using Django 2.x and Django REST Framework. I have a model AmountGiven with a property field amount_due like class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') interest_rate = models.FloatField(blank=True, default=None, null=True, help_text='% of interest to be calculated') total_due = models.FloatField( blank=True, default=0.0, editable=False ) @property def interest_to_pay(self): if self.interest_rate: datetime_diff = datetime.now(get_localzone()) - datetime.combine( self.given_date, datetime.min.time(), get_localzone() ) days = datetime_diff.days duration_in_year = days/365 simple_interest_amount = (self.amount * duration_in_year * self.interest_rate)/100 return simple_interest_amount return 0 @property def total_payable(self): return self.amount + self.interest_to_pay @property def amount_due(self): returned_amount = 0 for returned in self.amountreturned_set.all(): returned_amount += returned.amount total_due = self.total_payable - returned_amount self.total_due = total_due self.save() return total_due I need to generate graph data for Django REST Framework response for the total due amount for the contact. def top_ten_due(request): qs = Contact.objects.filter( user=request.user ).values('first_name', 'last_name').annotate( total_due=Sum('amountgiven__total_due') ).order_by( '-total_due' )[:10] graph_data = [] for q in qs: d = { 'contact': q['first_name'] if q['first_name'] else '' + ' ' + q['last_name'] if q['last_name'] else '', 'value': q['total_due'] if q['total_due'] else 0 } graph_data.append(d) return Response(sorted(graph_data, key=lambda i: i['value'], reverse=True)) The amount due is calculated by amount_due property of the AmountGiven model. And in order to generate the … -
How to acess form based on index django
I am trying to access the form based on the index value how can i do that exactly? Ex: {% for line in data_lines %} {{line}} {% with x=forloop.counter %} {{form.x}} {% endwith %} {% endfor %} -
How to define structure of a JSON in Django Rest Frame Work
I have the following serializer in Django: class ScopeIntentSerializer(serializers.Serializer): reference_object = serializers.JSONField( binary=True, error_messages= { 'binary': 'Reference object is not a valid JSON Object' } ) I want the reference_object to be a JSON array of key value pairs as in: reference_object: [ {'key': 'something', 'value': 'something else'}, {'key': 'somewhere', 'value': 'somewhere else'}, ] I tried to achieve this using a ListField and DictField, which did'nt work as expected. -
How to include migrate command while deploying django application in gae
I have deployed django application in app engine flexible. I'm able to run migrations using cloud_sql_proxy. But i want to add migrate step as a part of deployment. Where do i specify that in app.yaml file ? Also tried gcloud beta app gen-config --custom Which creates docker file. on adding migration command in docker file, recieved the following error: could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'password', 'PORT': '5432', 'HOST': 'connection-name', }} app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT wsgi beta_settings: cloud_sql_instances: connection-name runtime_config: python_version: 3 Please suggest approach to add migrate command. -
django query to get posts from users followed by a user
My models: class ClientProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client_profile') follows = models.ManyToManyField(User, related_name='follows',blank=True) profile_picture = models.ImageField( blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) dob = models.DateField(auto_now = False, null = True) profile_summary = models.TextField() my_career_objective = models.TextField() educational_qualification = models.CharField(max_length=200) work_experience = models.IntegerField(blank=True, null=True) skill_set = models.TextField(blank=True) address_1 = models.CharField(max_length=300,blank=True) address_2 = models.CharField(max_length=300,blank=True) # new fileds about_me = models.TextField(blank=True) birthplace = models.CharField(max_length=150,blank=True) lives_in = models.CharField(max_length=150,blank=True) occupation = models.CharField(max_length=150, blank=True) gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True) marital_status = models.CharField(choices=MARITAL_CHOICES,max_length=150, blank=True,default=1) religion = models.CharField(max_length=150, blank=True) political_incline = models.TextField(blank=True) # other_social_networks = models.TextField(blank=True) hobbies = models.TextField(blank=True) favorite_tv_shows = models.TextField(blank=True) favorite_movies = models.TextField(blank=True) favorite_games = models.TextField(blank=True) favorite_music_band_artists = models.TextField("Favorite Music, Bands / Artists", blank=True) favorite_books = models.TextField(blank=True) favorite_writers = models.TextField(blank=True) other_interests = models.TextField(blank=True) subscription = models.TextField(blank=True, null=True, default="Free") def __str__(self): return str(self.user.first_name) + " " + str(self.user.last_name) class Task(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) todo = models.ForeignKey(ToDo, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() timestamp = models.TimeField(auto_now=True) datestamp = models.DateField( auto_now=True) like = models.ManyToManyField(User,related_name='user_likes',blank=True) is_verified=models.BooleanField(default=False,blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('student:dashboard') objects = PostManager() @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return … -
Converting a class based view into a 'normal' view
I have written the following django rest framework view: # urls.py url(r'user/company', views.UserViewSet.as_view({"get": "companyInfo"}), name="company_info"), # views.py class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() permission_classes = (permissions.IsAuthenticated,) @action(methods=["get"], detail=True) def companyInfo(self, request): user = request.user company = user.get_company() detail = {} detail['company'] = company.name detail['num_users'] = company.num_licenses if company else None return Response(detail) How would I write this exact same view as a 'normal' django view with django rest framework. For example, something like this: # urls.py path('user/company/', views.company_info, name='company_info'), # views.py @require_GET def company_info(request): user = request.user company = user.get_company() detail = {} detail['company'] = company.name detail['num_users'] = company.num_licenses if company else None return Response(detail) I suppose the above is a start, but I think I still need to authenticate properly (using jwt), which the UserViewSet is automatically doing somehow. -
Problem while running a server in django basic app
I have to started to learn django and I'm facing a problem on starting a localhost. the error I have got is:- C:\Users\acer\Desktop\Example>py manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0637DC90> Traceback (most recent call last): File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\acer\AppData\Local\Programs\Python\Python37-32\lib\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 'pages.app' And the error in my code is the include statement shown below from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] if you know the solution then please help.... -
Django - wagtail Inline panel CSS edits
I am using wagtail on django and creating a page where I will create questions and allow students to answer it by typing in the input box. I am using inline field where the wagtail gives me the option to choose various input option like(singleline, multiline, radio button etc). For my questions, I am choosing a singleline option. The problem I am facing is with the text box, the text box is too small, is there a way to increase the size(width) of the text box. model.py class QuestionPage(AbstractForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) points_for_this_activity = models.IntegerField(blank=True, default=0) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Create your question"), FieldPanel('points_for_this_activity', classname="title"), FieldPanel('thank_you_text', classname="full"), ] question.html <div class ="container"> <h1>{{ page.title }}</h1> {% if user.is_authenticated and user.is_active or request.is_preview %} {% if form %} <div>{{ page.intro|richtext }}</div> <form action="{% pageurl page %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input class="btn-md btn-primary" type="submit"> </form> {% else %} <div>You have already answered this. Go to the next question.</div> {% endif %} {% else %} <div>To fill in the form, you should log in.</div> {% endif %} {% endblock %} </div> -
CRSF cookie not set in iframed Django View within another site
Long time lurker, first time poster here. I have a Django app with about a dozen views that I am currently hosting on Heroku. I can do POST requests just fine to the app when directly going to the app url, and I have the 'django.middleware.csrf.CsrfViewMiddleware' enabled. I am running Django 2.1 I am currently having an issue where I am trying to embed this Django app within an iframe, on another site that I host on Weebly. I always get a 403 error when trying to do a post on any of the Django forms. The reason is "CSRF cookie not set." I am doing this through Chrome on Ubuntu. I checked the Applications tab in the Developer console, and do see the csrftoken key-value pair set in the cookie for the Heroku domain. The Weebly domain does not contain the csrftoken key-value pair. I figured it would just use the cookie from the Heroku app domain and use the csrftoken, but that doesn't appear to be the case. In Django, here are my settings regarding CSRF: CSRF_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ['example123.herokuapp.com', 'app123.weebly.com'] I REALLY don't want to disable security or use the csrf_exempt decorator, as that feels … -
xhtml2pdf is creating URL with WinAnsiEncoding in Django
I am clicking a button and calling the django class and getting response in ajax success(function(data)) ajax $('.contract-download').click(function(){ $.ajax({ url:'{% url 'app:contract' %}', method:'GET', data:{ 'data-invoice':$(this).attr('data-invoice'), 'data-order':$(this).attr('data-order') }, success:function(data){ console.log(data) window.open("data:application/pdf,charset=utf-8" + escape(data)) } }) }) the new window it is creating its url is simply in WinAnsiEncoding %PDF-1.4 %���� ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R /F2 4 0 R /F3 8 0 R /F4 10 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /BitsPerComponent 1 /ColorSpace /DeviceGray /Filter [ /ASCII85Decode ] /Height 23 /Length 223 /Subtype /Image /Type /XObject /Width 24 >> stream 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> endstream endobj 4 0 obj << /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font >> endobj 5 0 obj << /Contents 24 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 23 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject << /FormXob.c7485dcc8d256a6f197ed7802687f252 3 0 R >> >> /Rotate … -
Clear the SimpleListFilter when searching
I am using 'search_fields' and 'list_filter' in my site. when i do a search URL becomes like ① /ur/corelog/?q=test and search function works well,and when I use list_filter url becomes like ②/url/corelog/?scoreRange=0+-+0.9 which is expected. what I am worrying is, if I do a search (url becomes as ① ) and then I use a filter the url becomes like ② above and search text is despairing as I wanted. /url/corelog/?scoreRange=0+-+0.9 If I use filter first (url becomes as ② ) and then I use search, url becomes as follows (Search text and filter both includes). url/corelog/?q=test&scoreRange=0+-+0.9 I need ① (/ur/corelog/?q=test) instead. and search is not working either. How can I clear my filter when performing a search? follow is my admin class and list_filter Class CoreLogAdmin(admin.ModelAdmin): form = CoreLogAdminForm search_fields = ('question',) list_filter = (RangeFilter,) list_display = ('question', '_predicted_result', 'datetime_created') fields = ('question', 'predicted_result', 'datetime_created') class RangeFilter(admin.SimpleListFilter): title = 'Score' parameter_name = 'scoreRange' template = 'admin/shuchi_logging/input_filter.html' def lookups(self, request, model_admin): return ( ('Yes', ''), ) def queryset(self, request, queryset): value = self.value() """ making queryset """ return queryset