Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError after installing Pillow
The HTTP is giving me the ModuleNotFoundError whichever link I go. The ModuleNotFoundError is giving me the following information: ModuleNotFoundError at /web/ No module named 'django.core.context_processors' Request Method: GET Request URL: http://127.0.0.1:8000/web/ Django Version: 3.1.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'django.core.context_processors' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /Users/william/Documents/coding/WDTP/wfw_fixed/env/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/wfw_fixed/wfw', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Documents/coding/WDTP/wfw_fixed/env/lib/python3.9/site-packages'] Server time: Sat, 23 Jan 2021 00:07:14 +0000 It is happening since I installed Pillow. In my settings.py: """ Django settings for wfw project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Test for settings templates path SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wfw_editor.apps.WfwEditorConfig', 'feedback.apps.FeedbackConfig', ] MIDDLEWARE … -
Django unittest handle PermissionDenied
As docs says https://docs.djangoproject.com/en/2.2/topics/testing/tools/#exceptions; The only exceptions that are not visible to the test client are Http404, PermissionDenied, SystemExit, and SuspiciousOperation. Django catches these exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check response.status_code in your test. I handle a custom a login mixin for raising an error to user logged in but has no access to that page. class LoginQuizMarkerMixin(LoginRequiredMixin): def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: if not self.request.user.has_perm('quizzes.view_sittings'): raise PermissionDenied("You don't have any access to this page.") return super().dispatch(*args, **kwargs) I my unitest, it working fine. class TestQuestionMarking(TestCase): def setUp(self): self.c1 = Category.objects.create_category(name='elderberries') self.student = User.objects.create_user(username='student', email='student@rebels.com', password='top_secret') self.teacher = User.objects.create_user(username='teacher', email='teacher@jedis.com', password='use_d@_force') self.teacher.user_permissions.add(Permission.objects.get(codename='view_sittings')) .... def test_paper_marking_list_view(self): # should be 302 (redirection) marking_url = reverse('quizzes:quiz_marking') response = self.client.get(marking_url) print('response1', response) # should be 403 (permission denied) self.client.login(username='student', password='top_secret') response = self.client.get(marking_url) print('response2', response) # should be 200 (allowed) self.client.login(username='teacher', password='use_d@_force') response = self.client.get(marking_url) print('response3', response) But for somehow, it the error of PermissionDenied it showed an error like this: response1 <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/?next=/quizzes/marking/"> WARNING 2021-02-04 00:28:44,270 log 1 139681767683904 [log.py:222] Forbidden (Permission denied): /quizzes/marking/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) … -
My images doesn´t appear in my ecommerce using Django
When i run my code with the local server my images are not visualized, there are images icons but not the image itself. settings.py: MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') my template tienda.py: {% extends 'tienda/index.html'%} {%load static%} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{{product.imageURL}}" alt="" class="thumbnail" > <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Agregar al carrito</button> <a class="btn btn-outline-success" href="">Ver</a> <h4 style="display: inline-block; float: right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {%endfor%} </div> {% endblock %} my model Product: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank = False) images = models.ImageField(null=True, blank=True) -
Django with jQuery/datatable
I have seen the following Python code which uses jQuery and datatable req = request.GET sort_col = req['columns[%s][data]' % req['order[0][column]']] glob_search_val = req['search[value]'] if req['order[0][dir]'] != 'asc': Where can I find more information on the structure of columns, order, search (and other) parameters passed to the server from jQury/datatable? -
Django override delete method
How can I override delete method ? I want to prevent delete not your posts by users. Using JWT auth serializers.py class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = '__all__' ... ... def delete(self, instance): user = self.context['request'].user if user.pk != instance.author.id: raise serializers.ValidationError( {"authorize": "You dont have permission to delete this post."}) instance.delete() views.py class PostDelete(generics.DestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated] -
How to add a CORS Domain Wildcard rule with Static Port
I'm trying to set up a CORS rule in my Django python web app to allow any domain/subdomain from port 8092 to access my API. I have added this line http://*:8092 to my CORS array, but no luck. I'm getting the following error Origin http://mbps-mbp.lan:8092 is not allowed by Access-Control-Allow-Origin. My goal is to allow Cross-Origin communication for port 8092 to my API. Is it possible to add a rule like that? -
why is django altering my data depending on server state?
I use an endpoint to clear and re-seed my data in my Django API. The data is from two arrays of objects stored within my project and then imported to my views.py. One array is profiles and the other is posts, which which include integers to be used as foreign keys referencing profiles. This works great the first time I run the functions after restarting the server. However, when I run the function again, django somehow alters my imported data to swap the integer for the entire referenced database object it references. Obviously, this breaks my code. in views.py: from .fixtures.seed import all_profiles, all_posts def seed(request): print('all posts zero: ', all_posts[0]['profile']) #logging the issue in question Profile.objects.all().delete() reset(Profile) for profile in all_profiles: add_profile(profile) Post.objects.all().delete() reset(Post) for post in all_posts: add_post(post) Comment.objects.all().delete() reset(Comment) for comment in all_comments: add_comment(comment) return HttpResponse('database cleared and seeded') def add_profile(new_profile): profile_instance = Profile.objects.create(**new_profile) profile_instance.save() def add_post(new_post): found_profile = Profile.objects.get(id=new_post['profile']) new_post['profile'] = found_profile post_instance = Post.objects.create(**new_post) post_instance.save() def reset(table): sequence_sql = connection.ops.sequence_reset_sql(no_style(), [table]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) log when running seed function first time: all posts zero: 5 [04/Feb/2021 00:01:37] "GET /utility/seed/ HTTP/1.1" 200 27 log when running second time: all posts … -
Django | Admin display foreign key as field rather than object
I have a Django project with the following two models setup: class List(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) name = models.CharField(max_length=50) class ListItem(models.Model): team_list = models.ForeignKey(List, on_delete=models.CASCADE) content = models.TextField() index = models.IntegerField() I have them registered in my admin as follows: class ListAdmin(admin.ModelAdmin): list_display = ('team_name', 'name') def team_name(self, obj): return obj.team.name admin.site.register(List, ListAdmin) class ListItemAdmin(admin.ModelAdmin): list_display = ('team', 'team_list_name', 'index') def team(self, obj): return obj.team_list.team.name def team_list_name(self, obj): return obj.team_list.name admin.site.register(ListItem, ListItemAdmin) This is great because now when I am looking at all of my "List items" in Django Admin, I can readily see the name of the list each item belongs to. However, when I am adding a new list item in admin I can only view the lists as an object (EX: "List Object (1)"). How can I make it so that the dropdown menus for foreign keys will display an object field rather than the object type? -
CORS Domain Wildcard with Static Port
I'm trying to set up a CORS rule in my Django python web app to allow any domain/subdomain from port 8092 to access my API. I have added this line http://*:8092 to my CORS array, but no luck. Is it possible to add a rule like that? -
Can the Django Admin show the models.JSONField contents with indenting (like "json.dumps(obj, indent=4)")
I don't really understand the 'encoder' part of the JSONField class: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#jsonfield I don't even think that's what I want since its for "An optional JSON-encoding class to serialize data types not supported by the standard JSON serializer" but I'm just trying to display the field contents in a nicer way. How does one use this to show the value of the JSONField, in the Django Admin, that is pretty-printed in some way? -
The view ecommerceapp.views.CheckoutView didn't return an HttpResponse object. It returned None instead
I'm trying to fix this issue in regards to the HttpResponse but I can't find where the problem is exactly. This is by building an ecommerce store and I want to check that all the data of the form is validated before proceeding. But whenever I try to do this code, the error pops out and I still can't figure out why. I've tried removing some things but it is still the same. Any help I would really appreciate it! views.py: def is_valid_form(values): valid = True for field in values: if field == '': valid = False return valid class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = checkoutForm() context = { 'form': form, 'order': order, } shipping_address_qs = Address.objects.filter( user=self.request.user, address_type='S', default=True ) if shipping_address_qs.exists(): context.update( {'default_shipping_address': shipping_address_qs[0]}) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") def post(self, *args, **kwargs): form = checkoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): use_default_shipping = form.cleaned_data.get( 'use_default_shipping') if use_default_shipping: print("Using the defualt shipping address") address_qs = Address.objects.filter( user=self.request.user, address_type='S', default=True ) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info( self.request, "No default shipping address available") return redirect('core:checkout') else: print("User … -
ValueError: Field 'id' when filter model data based on user
How do I return objects based on the user who made the model entry? Here is what I've tried below but I get an error: models.py class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) name = models.CharField(max_length = 100) library = models.CharField(max_length = 100, null = True) def __str__(self): return "File id: {}".format(self.id) query from .models import Csv x = Csv.objects.get(user = "site_manager") returns the error in the description from .models import Csv x = Csv.objects.get(library = "example library") returns a file from the database as intended. Why does this not work when I search based on username? -
CORS error in browser, terminal says Forbidden (CSRF cookie not set.)
Apparently this is a bug that creeps up quite often but none of the solutions I have found have made a difference so far for me. I am using a React front end with Django Rest Framework and Django Channels. The django server on port 8000 handles both the react routes as well as the api routes. Everything worked perfectly until suddenly when I was surfing through the website, I started getting the errors in the title, which I found weird because it was working fine before and I didn't change any of the code. I have tried many different ways to fix it. When I try to console.log the csrf cookie on login it logs it, so the cookie is definitely being sent with the request. Similar requests that handle things like registering users or loading user data get the same error. Attempts to fix it First I thought the error started happening because I switched to ASGI/Channels development server, so I disabled this and went back on standard django development server, but the error was still there. I have tried adding django-cors-headers and setting ALLOWED_HOSTS to ['*']. I also tried clearing the browser's cache and using a different … -
Django, Don't save the form to the base
I am doing my first project in Django and I am having 2 problems, I cannot figure out why the form is not being saved. It seems that I do everything according to the documentation. It does not give out obvious errors. And why empty_label doesn't apply Tried using different form forms.Form and ModelForm, but unsuccessfully ( models.py from django.db import models class Cars(models.Model): name = models.CharField(max_length=255, verbose_name='Автомобиль', default='МЭ') class Meta: verbose_name = 'Автомобиль' verbose_name_plural = 'Автомобили' def __str__(self): return self.name class Trip(models.Model): date = models.DateField(auto_now=False, verbose_name='Дата') car = models.ForeignKey(Cars, on_delete=models.CASCADE, verbose_name='Автомобиль') start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(max_length=20, blank=True, verbose_name='Отработано часов') deal_me = models.IntegerField(verbose_name='Сделки МЭ', blank=True, default=0) deal_gts = models.IntegerField(verbose_name='Сделки ГТС', blank=True, default=0) gain = models.IntegerField(verbose_name='Выручка', null=True, default=0) class Meta: verbose_name = 'Доставка' verbose_name_plural = 'Достваки' forms.py from django import forms from .models import Cars, Trip class TripForm(forms.ModelForm): class Meta: model = Trip fields = ['car', 'date', 'start_work', 'finish_work', 'deal_me', 'deal_gts', 'gain'] car = forms.ModelChoiceField(queryset=Cars.objects.all(), empty_label="Выберите автомобиль", required=True) date = forms.DateField(required=True) start_work = forms.TimeField(required=True) finish_work = forms.TimeField(required=True) deal_me = forms.IntegerField(required=False) deal_gts = forms.IntegerField(required=False) gain = forms.IntegerField(required=True) widgets = { 'car': forms.Select(attrs={'class': 'custom-select'}), 'date': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}), 'start_work': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}), 'finish_work': forms.TextInput(attrs={'class': 'form-control', … -
Django ORM inputting List of List with unequal amount of elements
I have a list of lists, that looks as such: major_list = [['element 1', 'element 2', 'element 3'],['element 1' 'element 2' 'element 3', 'element 4']] I have created a table in models for I would like to have access to Django ORM that looks as such: class Reviews(models.Model): element1 = models.CharField(max_length=400, default='') element2 = models.CharField(max_length=400, default='') element3 = models.CharField(max_length=400, default='') element4 = models.CharField(max_length=400, default='') I am attempting to add these two list to the table using a for loop structured as: for y in major_list: reviewz = StudentReviews(element1=y[0], element2=y[1], element3=y[2], element4=y[3]) reviewz.save() Knowing that my list are different lengths, I would assume the instances where the list does not include an element4, would just fill as the default value, in this case: ' '. But I am getting the error saying my list index is out of range. Which makes sense, but I thought the default value would take over. Does anyone have any ideas/help. I can clarify more if this comes off as confusing. Thanks! -
Django Social Auth Always returning created=True for post_save signal
I'm using Django social auth to enable login with Discord. It works to log in the user and create their account if it doesn't exist, but I also have a profile model (DiscordProfile) thats in a OneToOne relationship with the User model. When it goes through the pipeline the following happens: If a user didn't exist before: User model gets created somewhere before step 8 Pipeline populates profile with information and saves profile If a user did exist already: Pipeline matches user properly Pipeline repopulates profile with information fetched from social auth (to keep it in sync) Pipeline saves profile Profile post_save shows created == True for the instance, thus a new model gets created with blank values and the old one gets deleted. My pipeline: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'discordapi.DiscordProfile.pipeline.create_user', 'discordapi.DiscordProfile.pipeline.populate_profile', ) Pupulate profile: def populate_profile(backend, user, response, *args, **kwargs): print(user.discord_profile) user.discord_profile.discord_id = kwargs['uid'] user.discord_profile.discord_discriminator = response['discriminator'] user.discord_profile.discord_username = kwargs['details']['username'] user.discord_profile.discord_avatar = response['avatar'] user.discord_profile.discord_access_token = response['access_token'] user.save() print('Finished populating profile') ### Note: have also tried doing something like below: # profile = user.discord_profile # ... # profile.save() DiscordProfile model: class DiscordProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="discord_profile") discord_id = models.BigIntegerField(null=True, blank=True) discord_username = models.CharField(max_length=32, … -
Why is my model field out of scope in the constraints?
(Models.py) class Bug(models.Model): title = models.CharField(max_length=200) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator") lead = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.SET_NULL, related_name="lead") contributors = models.ManyToManyField(User, default=None, blank=True, null=True, related_name="contributors") project = models.ForeignKey(Project, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, default=0) description = models.TextField() class Meta: constraints = [ models.CheckConstraint( check=( models.Q( abs(datetime.now().microsecond - created_at.microsecond) > 10 ) ), name="%(app_label)s_%(class)s_exact_date", ) ] When I attempt to run tests on it I get the following error: NameError: name 'created_at' is not defined I am trying to enforce a constraint that the created_at date for a bug be either exactly the time it was created or within some tight bound of the time that it was created. I wish to enforce it at the database level because I'm trying to secure the data not only from form entry (in which case I could just add a validator or add editable=false on the field), but also from any other attempt to save incorrect data to the database through the ORM. I'm also using constraints rather than validators because I don't want to have to override multiple functions (save(), update(), etc). System information: Python v3.9.0, Django v3.1.4 -
I am trying to use text choices and I receive this erro - python 'appstat' cannot be converted to a MySQL type", None
I receive this error : django.db.utils.ProgrammingError: (-1, "Failed processing format-parameters; P ) Here is the models.py where the error originates: class Person(models.Model): class AppStat(models.TextChoices): Submitted = 'SUB', ('Submitted') HRREV = 'HR', ('HR Reviewed') Contacted = 'CON', ('Contacted') Accepted = 'AC', ('Accepted') Rejected= 'REJ', ('Rejected') It works fine in a local environment, but it doesn't when I move to an environment in a docker container using mysql connector.''' Exception Value: (-1, "Failed processing format-parameters; Python 'appstat' cannot be converted to a MySQL type", None) -
Django ORM Merge Dependencies from Duplicate Entries
(I am using PostgreSQL) I have a table called Operation with two critical pieces of information, X and Y. The entry is uniquely identified by these two pieces of information. Due to an issue with a form, users were able to create duplicate Operation entries with the same X and Y. This would be no problem to remove the duplicate entries from Operation, however Operation is used in other tables, so deleting the instance would delete the dependent data. For any Operation entry with duplicates, I would like to merge all the duplicates into one, and move the dependencies under the single, merged Operation instance. -
AttributeError: 'QuerySet' object has no attribute 'product' ERROR
Hi I'm building a Webshop with a cart and checkout function. Now I'm trying to add the products and their quantity to an Email form which I want to send to an email obviously but I don't know how I could get the item.name or the item.quantity without getting an error as shown below. I have the following models: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) # Nicht nötig image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total … -
Django Query across multiple tables (also my first post on stackoverflow)
I am very new at Django and can use some help on a query using 3 tables. Here is what my models contains. class VolunteerRecord(models.Model): eventname = models.CharField(help_text=_('Name of the event'),max_length=256, blank=False, default='') category = models.CharField(max_length=256, blank=False, choices=CATEGORY_CHOICES) hours = models.FloatField(blank=False) date=models.DateField(help_text=_('Enter the date of the event'),validators=MaxValueValidator(limit_value=date.today)]) mileage = models.FloatField(blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) streetaddress1 = models.CharField(blank=True, max_length=256) streetaddress2 = models.CharField(blank=True, max_length=256) city = models.CharField(blank=True, max_length=30) state = models.CharField(max_length=256, blank=False, choices=US_STATES) zipcode = models.CharField(blank=True, max_length=15) county = models.CharField(max_length=256, blank=False, choices=STATE_COUNTIES) I would like to filter all VolunteerRecords where the owner's county = request.user's county So far I have... (not sure what I am suppose to put where my ??? are) def history(request): current_user_county = request.user.profile.county records = VolunteerRecord.objects.filter(????=current_user_county) -
Updating a model field in django using queryset with Django
I'm trying to create a small version of an online shop using Django and the main purpose of this post is to update a field belonging to my product model called maximum_stock each time an order is validated by the user after checking his cart. My Product Model code is : name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) maximum_stock = models.PositiveIntegerField() # The field that will be using ordered_stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) tva = models.DecimalField(max_digits=4, decimal_places=2, choices=CHOICES) The code for the cart forms.py where the user can choose the quantity wanted for the product : from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 31)] # Here the maximum quanity value is setted in hard to 30 and the goal is to set this value dinamically receiving the maximum_stock - the ordered quantity ( this value represent the available stock ) class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)``` And here is the order views.py file from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from shop.models import Product from cart.cart import Cart def … -
html table with for loop in django templates, want one header for table
I have a for loop in django templates. {% for regel in regels %} <table style="margin-left: 40px" class="tg"> <tr> <th style="width: 50px" class="tg-0lax">{{ regel.0 }}</th> <th style="width: 100px" class="tg-0lax">{{ regel.2 }}</th> </tr> </table> How can i get 1 header for the whole table, because if i put in a header i creates the header for every iterations. So every row gets the same header -
How to see who the active user is without request Django
I am working on a class based view and one of the functions is validating that the form has the correct selections. I need to reference the active user without using request as my function form_valid inherits only two parameters being: self and form. How could I make reference to the user who filled out the form in the form_valid function? -
Access Denied Error While Loading Images from AWS S3 Buckets
I am trying to load my static image files using AWS S3 Buckets in my Django Project, but I am getting access denied error. I created a IAM user and granted full access to S3. I also installed django-storages and boto3. I have added 'storages' in INSTALLED_APPS list in settings.py This is the error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>41C48F59569D1B9F</RequestId> <HostId>OBKr0zh+DmpcbvesTTFi9wLmKb4Y8GMgg7knOMKlcVBLkU47SKPEyttj4sUjY3cbu8hkfjCpos0=</HostId> </Error> This is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-2' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' This is my CORS code: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "POST", "GET", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] This is my Bucket-Policy: { "Version": "2012-10-17", "Id": "ExamplePolicy01", "Statement": [ { "Sid": "PublicReadForGetBucketObjects", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::sample" }, "Action": [ "s3:GetObject", "s3:GetBucketLocation", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::bucket/*", "arn:aws:s3:::bucket" ] } ] }