Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
WebSocket HANDSHAKING /tunnelws/ticket/0fa9dd05-0d91-4baa-923e-05f6af6f55a0/ [127.0.0.1:56637] Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 71, in call return await application(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 254, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py", line 181, in call return await super().call(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py", line 26, in call return await self.inner(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 150, in call return await application( File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 62, in call await await_many_dispatch([receive], self.dispatch) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\generic\websocket.py", line 175, in websocket_connect await self.connect() File "E:\VirtualLab\VirtualLab\VirtualLab_Server\VirtualLab_Server\guacdproxy\consumer.py", line 42, in connect if ticket.user != self.scope['user']: File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", line 187, in get rel_obj = self.get_object(instance) File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py", … -
How to correctly serve my React production build through Django. Currently having MIME type issues with current configuration
I'm trying to deploy my react/django web-app to a linux-VM droplet. I'm not using a webpack for the JS content. Instead, I'm serving npm run build static files through a CDN sub-domain, digital ocean s3 bucket. I'm able to python manage.py collectstatic which then pushes my react production build folder to the CDN. When I visit my production website, it currently just loads up a blank page with these console errors: Refused to apply style from 'https://www.my_website_URL.com/static/css/main.ce8d6426.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to execute script from 'https://www.my_website_URL.com/static/js/2.ca12ac54.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to execute script from 'https://www.my_website_URL.com/static/js/main.220624ac.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. There aren't any network errors that provide any useful information for this matter. The issue has to be server side (django)... I think. Project set up: The react production build is inside my core django folder. Here is how I link my React through django: core urls.py def render_react(request): return render(request, "index.html") #index.html being created by react, not django templates urlpatterns = [ … -
Creating your own sdk for a django website
I have a website on django and I need to create a telegram bot for this site. You need to create an sdk for the site and use it when creating a telegram bot. How can this be done? -
Call a function after creating or updating django model instances
# Do something after each create()/update() or bulk_create()/bulk_update() I want to call a function each time a model instance is created/updated or bulk operation is performed. Where can I put that function so that it is called all these times? I know we can add post_save listener, but I think, it is not called for bulk operations. I am also bulk_updating this model's instances from migration RunPython, so can it trigger that function from migration as well? P.S. I'm using Django 3.1.7 with MySQL -
Django Forms from Model instances in loop
Is it possible to create forms from model instances created in Django's admin? So from a model like this. #models.py # Math, Language Arts, Physical Development etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False, null=True) display_name = models.CharField(max_length=50, blank=True, null=True) # Shapes, Gross Locomotor Movement Skills etc... class Standard(models.Model): name = models.CharField(max_length=50, blank=False, null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) Create a form that loops through each Standard/Domain created in Django's admin #forms.py class DomainStandardForm(): fields = [] standards = Standard.objects.get.all() for standard in standards: #create form fields from each Standard End result of DomainStandardForm -
Django 3.2 - how can i made redirect with context?
The main page is block with random instance of model. Also there is a page with form for add new instance . After create new instance i want redirect to main page, but it must render not random instance, it must render instance, which i create. How can i make this? main page controller: def brick_page_foo(request): peekeys = [] for item in Brick.objects.filter(is_published=True): peekeys.append(item.pk) brick = Brick.objects.get(id=random.choice(peekeys)) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) add form controller: def add_brick(request): if request.method == 'POST': form = BrickAddForm(request.POST, request.FILES) if form.is_valid(): brick = form.save() print(colored(brick, 'yellow')) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) else: form = BrickAddForm() return render(request, 'brick/add_brick.html', {'form':form}) -
Possible source of cascade deletion on Django 1.9 project?
I'm working on a Django 1.9 project with a huge source and lots of is inherited from previous developers. When I delete a User object from the shell there are many other related objects that get deleted as well. I get a print output with a Tuple containing: (# of deleted objects, {u'CLASS_NAME': #number of deleted objects...}) I've searched all the code throughly and there are no Signals attached to User pre_ post_ or on_ delete, neither I can find where this print output is constructed... so, I have no idea where this is coming from. Any ideas for other possible ways this can be happening? -
changing 'DEFAULT_FILE_STORAGE' causing high TTFB ( waiting time ) with boto3
My settings ... AWS_ACCESS_KEY_ID = 'MY_KEY' AWS_SECRET_ACCESS_KEY = 'MY_SECRET_KEY' AWS_STORAGE_BUCKET_NAME = 'wallpapers' AWS_S3_ENDPOINT_URL = 'https://sgp1.digitaloceanspaces.com' AWS_S3_CUSTOM_DOMAIN = 'wallpapers.sgp1.cdn.digitaloceanspaces.com' AWS_QUERYSTRING_AUTH = False AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media') MEDIA_ROOT = 'media/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' ... when I open 'http://127.0.0.1:8000/' this causes high TTFB... but when I comment out/ remove this in settings.py... #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' then everything works fine -
plt.close() or plt.clf() doesnt effect on image
I save my image with plt.savefig(). But after that plt.close() doesnt work and it shows the previous pics as well. Could you please indicate the error, please. I cant avoid the error "networkx.exception.NodeNotFound: source node KAZ/TNS/Алматы not in graph" in nx.all_simple_paths(g, source=point1.point, target=point2.point), if the both points are not in graph. Here is my views.py point1 = get_object_or_404(Point, pk=pk1) point2 = get_object_or_404(Point, pk=pk2) g = nx.Graph() g2 = nx.Graph() data = [] content = {'name':None, 'points': None, 'sum_line':0, "sum_cable": 0} for form in Form61KLS.objects.all(): g.add_edge(form.point1.point, form.point2.point, weight=form.total_length_line) g2.add_edge(form.point1.point, form.point2.point, weight=form.total_length_cable) g.add_node(form.point1.point, pos=(1, 20)) g.add_node(form.point2.point, pos=(1, 20)) path = [] for p in nx.all_simple_paths(g, source=point1.point, target=point2.point): path.append(p) for p in path: path_length = nx.path_weight(g, p, weight='weight') path_length1 = nx.path_weight(g2, p, weight='weight') finish_total = copy.deepcopy(content) finish_total['name'] = "Варианты:" finish_total['points'] = p finish_total['sum_line'] = path_length finish_total['sum_cable'] = path_length1 data.append(finish_total) for p in nx.all_simple_edge_paths(g, source=point1.point, target=point2.point): for t in p: total = copy.deepcopy(content) total['name'] = "Разбивка:" total['points'] = t path_length = nx.path_weight(g, t, weight='weight') path_length1 = nx.path_weight(g2, t, weight='weight') total['sum_line'] = path_length total['sum_cable'] = path_length1 data.append(total) pos = nx.spring_layout(g) labels = nx.get_edge_attributes(g, 'weight') nx.draw_networkx_edge_labels(g, pos, edge_labels=labels, font_size=8, font_color='blue', font_family='sans-serif', font_weight='normal', horizontalalignment='center', verticalalignment='center') nx.draw(g, pos=pos, node_size=250, node_color='blue', linewidths=1, font_size=7, font_family='sans-serif', edge_color='y', with_labels=True) if os.path.exists(BASE_DIR + … -
Delete from django database with many form in same template
I am new to django and I'm trying to build a to do list so what I click on "✓" button it turn the item to green from red using javascript and now Iam trying to make the button "X" delete objects from the django database so I stuck here this is my code I am waiting for your help my views from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == "POST" : form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect("/") context = { 'tasks' : tasks , 'form' : form } return render(request,"tasks/list.html", context) def deletetask(request, pk): if request.method == "POST" and "delete" in request.POST: print(request.POST) print("good work") item = request.POST.get(id=pk) Task.objects.delete(id=item) return render(request,"tasks/list.html") my forms.py from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' my models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) creted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title my template <h3>Hello world from templates</h3> <form action="/" method="POST"> {% csrf_token … -
How can I parse and show sequence charts and flow charts of markdown content on html?
I'm developing a blog app by using django, there's a feature is that showing articles written by markdown. Now I have been able to successfully parse some markdown syntax, but I can't do it well on sequence charts and flow charts. Are there some modules can do it well? Thank for your answer firstly!! -
Django/Python feeding back ImproperlyConfigured for makemigrations for AppConfiguring
Following along a tutorial and I have been able to solve all my little issues so far until I get to my back-end creating my own 'app' for data I can lookup with SQlite. My work flow: > DJANGO-WEBSITE: > capstone_project_website: > settings.py > apps: > accounts: > models.py > apps.py > requirements: > scripts: > manage.py my /mymodels.py: from django.db import models from django.contrib.auth.models import User class UserInterest(models.Model): # name of interest name = models.CharField(max_length=64, unique=True) normalized_name = models.CharField(max_length=64, unique=True) # string function to print the name def __str__(self): return self.name class UserPersona(models.Model): name = models.CharField(max_length=64, unique=True) normalized_name = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=200) def __str__(self): return self.name # Create your models here class UserProfile(models.Model): # Owner. Foreign key. Whenever we fetch user, we should fetch the user profile # related_name = we can access profile through user object aka request.user.profile user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") # settings is_full_name_displayed = models.BooleanField(default=True) # details bio = models.CharField(max_length=500, default=True, null=True) website = models.URLField(max_length=500, default=True, null=True) persona = models.ForeignKey(UserPersona, on_delete=models.SET_NULL, blank=True, null=True) interests = models.ManyToManyField(UserInterest, blank=True) my /settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "capstone_project_website.apps.accounts", ] my /apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = "accounts" the error … -
Can I add Django context as prerendered text in input field?
Let's say we have: <input type="text" value="{{ title }}" /> This obviously doesn't work. Can I get context to be shown as prerendered text in input field, providing the fact that I have stored the text in another language somewhere else, and I converted it in html language in views.py and gave it a context? -
Processes in Python 3.9 exiting with code 1 when use Postgres
I have a piece of code that generates an Insert SQL query and executes it using Django cursor. This works correctly with Python 3.8 but I've updated my Ubuntu which cames with Python 3.9 and now It's always exiting with code 1. def __save_result_in_db(self, combinations: List[CorResult], experiment: Experiment, table_name: str): insert_query_prefix = f'INSERT INTO {table_name} ... VALUES ' insert_template = "('{}','{}',..." + str(experiment.pk) + ")" for chunk in self.get_chunks_of_list(...): insert_statements: List[str] = [ insert_template.format( # SOME fields ) for cor_result in chunk ] insert_query = insert_query_prefix + ','.join(insert_statements) with connection.cursor() as cursor: cursor.execute(insert_query) logging.warning(f'THIS MESSAGE IS PRINTED!') # Calling p = Process(target=self.__save_result_in_db, args=(result_combinations, experiment, table_name)) p.start() p.join() if p.exitcode != 0: logging.error(f'Process for experiment with id = {experiment.pk} has exit with code {p.exitcode}') # Always is 1 raise ExperimentFailed Even putting an explicit exit(0) at the end of __save_result_in_db doesn't prevent to the process to exit with code 1. Is there I'm missing? Any kind of help would be really appreciated -
python django why the form is not showing in the html page?
** for some reason my form is not showing in the template can someone tell me why , think you. ** views.py i think the problem is here but i cant find it i followed the documentation and got nothing also def contact(request): print(request.POST) forms=contactform(request.POST or None) if forms.is_valid(): print(forms.cleaned_data()) context= { "title":"contact", "form": forms } return render(request,"form.html",context) ``` > forms.py ``` from django import forms class contactform(forms.ModelForm): full_name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) ``` > form.html ``` {% extends "gta.html" %} {% block ferr%} {% if title %} <h1>{{title}}</h1> {% endif %} <form method="POST" action="."> {% csrf_token %} {{forms.as_p}} <button type="submit">submitt</button> </form> {% endblock %} -
Can I return a different Django Response based on whether or not the view is invoked from swagger?
I am using Django-Rest-Framework for my API. And I am documenting that API w/ swagger using drf_yasg. One of my views returns a Django FileResponse. When I access the view directly at "http://localhost:8000/api/my_documents/1" it successfully displays the (PDF) file. But when I access it via swagger it successfully returns a 200 but gives the following message: Unrecognized response type; displaying content as text. This is b/c of this issue in swagger itself. As suggested in that ticket, the problem goes away if I change the "Content-Disposition" response header from "inline" to "attachment". However, I don't want to always download the file. My question is: Can I determine whether the request was made by swagger in the view and conditionally change the headers? Something like: class MyDocumentView(GenericAPIVIew): def get(self, request, pk): my_document = MyDocument.objects.get(pk=pk) response = FileResponse(my_document.file) # (file is a FileField) # WHAT DO I PUT HERE ?!? if request.is_from_swagger: response.headers["Content-Disposition"] = response.headers["Content-Disposition"].replace("inline", "attachment") return response Thanks. -
Why does Django require change permission to add a foreign key?
I have two models in my application, Product and Holder. A Holder can have n products, and a Product must have one Holder. These are the classes: class Product: title = models.CharField(verbose_name=_('Title'), max_length=100) holder = models.ForeignKey(verbose_name=_('Main Holder'), to=Holder, on_delete=models.PROTECT) ... class Holder: name = models.CharField(verbose_name=_('Name'), max_length=50, unique=True) ... When a user that is a staff_member tries to create or change a Product, that specific user has to have the database's change_holder permission assigned to them, otherwise they can't assign a Holder to that Product. The list of holders won't even load up on the respective field on Admin, as the following image illustrates. Anyway, what I'd like to know is what justifies this behavior. Why would a user need permission to change the foreign key model, if they're not changing that model, but the one that contains the key? -
How can i implement a function to any user add products to my site(Django)?
I am trying to insert my product by category, and the product attributs in django. I have two model Product(Tool) and Category. If i'm logged has user i want to add my product in my site. This is my product models from django.db import models from django.urls import reverse from model_utils.models import TimeStampedModel from utool import settings class AvailableManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_available=True) class Category(TimeStampedModel): name = models.CharField(max_length=255, unique=True) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") class Meta: ordering = ("name",) verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:list_by_category", kwargs={"slug": self.slug}) class Tool(TimeStampedModel): category = models.ForeignKey( Category, related_name="tools", on_delete=models.CASCADE ) name = models.CharField(max_length=255) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") image = models.ImageField(upload_to="tools/%Y/%m/%d", blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) is_available = models.BooleanField(default=True) # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = models.Manager() available = AvailableManager() class Meta: ordering = ("name",) def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:detail", kwargs={"slug": self.slug}) And this is my product views from django.views.generic import DetailView, ListView from .models import Category, Tool class ToolDetailView(DetailView): queryset = Tool.available.all() class ToolListView(ListView): category = None paginate_by = 6 def get_queryset(self): queryset = Tool.available.all() category_slug = self.kwargs.get("slug") if category_slug: self.category = get_object_or_404(Category, slug=category_slug) queryset = queryset.filter(category=self.category) return queryset … -
'SalaryAdmin' object has no attribute 'request'
Hello I want to add method to list display in django admin but am getting error say SalryAdmin has no attribute request here my admin @admin.register(Salary) class SalaryAdmin(admin.ModelAdmin): list_display = ['user_name', 'action'] def action(self, obj): if not self.request.user.is_superuser: if obj.hr_state == 'request-change-approved' and self.request.user.user_role.position.code == 'HRM': return True else: return False else: return True any help appreciated -
Using ckeditor in Django without the built-in provided forms
I am new to Django and till now, I have not been using Django forms. Instead, I have been making my own customised forms in templates by using Bootstrap and css. But, now, I have a field where I want to use a rich text editor like Ckeditor. Is there a way to use it without the Django built-in forms? Thank youuu for your reply :)) -
use of upload_to function when creating on object in django
here is my model in django : import os def upload_location_buy(instance, filename): ext = filename.split('.')[-1] filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext) print(os.path.join('uploads', filename)) return os.path.join('uploads', filename) class Buy(models.Model): pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='') When i try : b = Buy(pic_front="appartement_a.jpg") b.save() it does nothing exception linking the current pic in the current path, so not using the function in the model. And when i do : b = Buy(pic_front=upload_location_buy("appartement_a.jpg")) b.save() it give me an error because it seems to need the instance. TypeError: upload_location_buy() missing 1 required positional argument: 'filename' How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ? When i upload a pic in the admin it works. how to give it the instance name or do it correctly ? regards -
I am getting an error no such table: users_profile. Why so?
I have the following Profile model as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField("Profile", blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) path('users/', users_list, name='users_list'), @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) my_friends = request.user.profile.friends.all() sent_to = [] friends = [] for user in my_friends: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends += friend for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = random.sample(list(users), min(len(list(users)), 10)) for r in random_list: if r in friends: random_list.remove(r) friends += random_list for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) and I have users_list.html template. I have tried building the database tables with migrate command and tables have been created. But I still get the error message: no such table: users_profile What could be the problem? -
Adding item to cart in Python, Django. FieldError at /add/1 -> Cannot resolve keyword 'book' into field. Choices are: author,
I have two functions, one adds items to the cart and one removes. While I try to add the item to the cart I get an error: FieldError at /add/1 Cannot resolve keyword 'book' into field. Choices are: author, author_id, bookorder, description, id, price, publish_date, review, stock, title Where do I go wrong? Any help is appreciated! models.py from django.db.models.query import prefetch_related_objects from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return "%s, %s" % (self.last_name, self.first_name) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField() publish_date = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.IntegerField(default=2) class Meta: verbose_name ='Book' verbose_name_plural = 'Books' db_table = 'book' class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) order_date = models.DateField(null=True) payment_type = models.CharField(max_length=100, null=True) payment_id = models.CharField(max_length=100, null=True) def add_to_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = Book.objects.get(book=book, cart=self) preexisting_order.quantity += 1 preexisting_order.save() except BookOrder.DoesNotExist: new_order = BookOrder.objects.create( book=book, cart=self, quantity = 1 ) new_order.save def remove_from_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = BookOrder.objects.get(book=book, cart=self) if preexisting_order.quantity > 1: preexisting_order.quantity -= 1 preexisting_order.save() else: preexisting_order.delete() except BookOrder.DoesNotExist: pass class BookOrder(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, … -
CSRF exempt for contactform - Django
Is it safe to use a CSRF exempt for a contactform or a form using the send_mail function from Django? So according to the docs; The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by RFC 7231#section-4.2.1) are side effect free. Is a POST request, which only creates an email message and does not touch the database, considered as a "safe" method? Example code from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect def send_email(request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if subject and message and from_email: try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') *example from docs I'm just wondering if I'm not missing something before I add the CSRF exempt. Now I hear you thinking, why would someone want to disable the CSRF validation? In the EU we have to comply to the GDPR. By setting a cookie, we need to explicitly ask the user to accept cookies, if we can prevent setting … -
Emailing a PDF Generated from HTML: expected bytes-like object, not HttpResponse
I am trying to email a PDF that has been generated from a HTML template. I get the following error: expected bytes-like object, not HttpResponse generate_pdf: def generate_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None view for pdf emailing: def pdfView(request): data = {'test':'test', 'mylist': 'test' } pdf = generate_pdf('main/test.html', data) msg = EmailMessage("title", "content", to=["email@email.com"]) msg.attach('my_pdf.pdf', pdf, 'application/pdf') msg.content_subtype = "html" msg.send() return HttpResponse(pdf, content_type='application/pdf')