Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" ] } ] } -
How to make Django OneToOne relation unique across models
I have User model, and 2 profile models (ProfileA, ProfileB). Profile models are OneToOne to User, but how to make User to be unique in both Profile models? class User(): name = CharField() class ProfileA(): user = OneToOneField(User) class ProfileB(): user = OneToOneField(User) user = User.objects.create(name='abc') profileA = ProfileA.objects.create(user=user) profileB = ProfileB.objects.create(user=user) The problem is that I'm allowed to create profileA and profileB with the same user object, but I want to disallow. -
I am getting django.db.utils.DataError: value too long for type character varying(7) error
print(languages,type(languages), len(languages)) self.Project = Projects( name=each['name'][:20], language=languages[:9], About=each['description'][:60] ) print(self.Project, self.Project.clean()) print(self.Project.language) self.Project.save() gives the error ... JavaScript CSS HTML 18418 7866 504 <class 'str'> 34 Local-ctf-event None JavaScrip Traceback (most recent call last): File "/mnt/DATA/programing/Mainsiteport/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(7) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> ... ... ... File "/mnt/DATA/programing/Mainsiteport/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/mnt/DATA/programing/Mainsiteport/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/mnt/DATA/programing/Mainsiteport/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: value too long for type character varying(7) my models.py is from django.db import models from django.core.exceptions import ValidationError class Projects(models.Model): name = models.CharField( max_length=28 ) language = models.TextField(max_length=250,blank=True,null=True) About = models.TextField( max_length=250,blank=True,null=True) def __str__(self): return (self.name) i tried to change the model declatatoin from Texfield to charfield and slugfield and change the max_length nothing seem to work I did tried to create object from admin i get the same error,the datbase is postgresql -
AttributeError: 'QuerySet' object has no attribute 'product' ERROR trying to print QuerySet data
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 So I'm trying to get the product name and quantity from an Query set. But I get an error as described in the title AttributeError: 'QuerySet' object has no attribute 'product'. I'm trying to append the product name and quantity a customer has selected to a message variable which will be send to an … -
How do display a form and the result of the form in a table format on the same page in django?
Ive spent the past week looking for help with this and i cannot find any resources to help, if someone can link me to a resource or anything that would be great. -
How to use django graph variable in javascript
Function for graph : def graph_on_surf_one_segment(result): fig = plt.figure() plt.plot(draw_X,draw_Y) plt.title("On surface movement") plt.xlabel("x") plt.ylabel("y") imgdata = StringIO() fig.savefig(imgdata, format='svg') imgdata.seek(0) data = imgdata.getvalue() return data views.py graph = graph_on_surf_one_segment(result) graph_2 = graph_on_surf_one_segment(result_zero) return render(request, "segments_to_download.html", {"result":result,"graph":graph,"graph_2":graph_2}) In html is classic {{ graph|safe }}. This will display a graph. I need to display only one graph and below the graph will be the button, that will switch between these two or more graphs, if the 1st graph is displayed, after clicking the second one will be displayed. I cant load graphs into variables and then compare them. If load graph into variable like this var a = {{graph}}, it gives an error. It is possible to do this ? -
How do I separate my templates correctly in Django?
I'm in doubt as to how I can make my templates in Django. I created three apps on my django: User Posts Index And each app I create a folder called "templates" and there I make the templates for these pages, but there is a problem! Whenever I put the same page in my view that I created in another template, all the repeated content appears there, is there any way to make this not happen? -
Django rest framework, serializers and data
So, I am getting data from a front and. Let's say it's a department name: "COINS" and key: "coins". I am defining a method in my serializer class, just to see what data actually is. def validate(self, data): print(data) return data I have tried getting data from the context, but I only get the key: "coins". Name is not present in data, BUUUT it's present in the validated_data Have spent all day figuring it out. How does they kwarg is present in validate_data, but not in data. Thanks in advance -
Heroku error after deploying (No module named '_tkinter')
I have an web app deployed on heroku (using Python), I am using now Pyppeteer to make some automatic jobs in a web site. After deploying I am getting this issue: Request Method: GET 3.1.4 ModuleNotFoundError No module named '_tkinter' /app/.heroku/python/lib/python3.6/tkinter/init.py, line 36, in /app/.heroku/python/bin/python 3.6.12 ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Anyone faced this issue? I already used the buildpacks for chrome and puppeteer but getting same error. Also have tried: import matplotlib matplotlib.use("Agg") Thanks!! -
Importing Signing and Verifying key for JWT RSA algorithm in Django rest framework
I'm working on a django rest api application that uses JWTAuthentication using django-rest-framework-simplejwt. Since the RSA algorithm is in use, the signing and verifying key needs to be set. The implementation below worked for me. SIMPLE_JWT = { 'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None, 'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None, } After upgrading to django 3 and running py -Wa manage.py test. This are some of the warning messages being displayed. D:\path\to\settings.py:398: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key' mode='r' encoding='cp1252'> 'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None, ResourceWarning: Enable tracemalloc to get the object allocation traceback D:\path\to\\settings.py:399: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key.pub' mode='r' encoding='cp1252'> 'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None, ResourceWarning: Enable tracemalloc to get the object allocation traceback I tried an alternative to solve this issue but it seems to break the app when authenticating users. This is the attempted solution. def get_file(file_url): if os.path.isfile(file_url): with open(file_url) as f: return f return None SIMPLE_JWT = { 'SIGNING_KEY': get_file('./jwtRS256.key'), 'VERIFYING_KEY': get_file('./jwtRS256.key.pub') } This doesn't work when trying to log in and returns a 500 with TypeError: Expecting a PEM-formatted key. -
Model with a lot of fields with a clearly visible pattern: is a loop possible when declaring model fields?
Django 3.1.6 class RasterImage(models.Model): img_original = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_original", ) img_100_100_webp_1x = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_100_100_webp_1x", null=True, blank=True, width_field="img_100_100_webp_1x_width", height_field="img_100_100_webp_1x_height") img_100_100_webp_1x_width = models.PositiveIntegerField() img_100_100_webp_1x_height = models.PositiveIntegerField() img_100_100_1x = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_100_100_1x", null=True, blank=True, width_field="img_100_100_2x_width", height_field="img_100_100_2x_height",) img_100_100_2x_width = models.PositiveIntegerField() img_100_100_2x_height = models.PositiveIntegerField() class Meta: verbose_name = _("Raster image") verbose_name_plural = _("Raster images") For each picture I'll store a hundred of image files. The pattern of each field is clearl: width, height, device pixel ratio, webp or not. Then fields to keep width and height. The question Is it possible to organize such a model field set in a loop somehow? P.S.: Don't persuade me to use django-imagekit or something. I'll keep process images locally. -
Django REST Framework: POST view for ManyToManyField
User has to be able to create new chat and add there participants. For new chat I need new chat's ID (which has to be generated automatically) and chat participants (who will be chosen out of other users in database by the user who creates a chat). Here is the chat model: class Chat(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) chat_participants = models.ManyToManyField(User, blank=True) class Meta: db_table = 'chat' verbose_name_plural = 'chats' And here is the serializer: class ChatSerializer(serializers.ModelSerializer): chat_participants = ChatParticipantsSerializer(many=True, read_only=True) class Meta: model = Chat fields = '__all__' PS. ChatParticipantsSerializer contains name and last name of participants (it uses a customized User model). Here is the view (it is incorrect, but I leave it here for any cases. Generic views don't help me, so I decided to write it from the scratch): @api_view(['POST']) @permission_classes((IsAuthenticated,)) def create_or_update_chat(request): new_chat = Chat.objects.create() The only field I need here is chat_participants for user's choice. After choosing participants, user just should click the 'POST' button (which is prepared by Django REST Framework itself for 'POST' requests) and that's all. But unfortunately I couldn't find the proper post where this problem is properly solved. -
Django Form css not displaying flex properties
I'm setting up a comment form for a blog with django. I want to have the submit form on the left and the already existing comments on the right, but I can only get them to display underneath each other. I've been trying with flexbox display: row Here is my code: entry_detail.html <div class="comment_section"> <div class="left"> <h2>What do you think?</h2> <form method="POST" class="comment_form"> {{ comment_form.as_p }} {% csrf_token %} <a href="{% url 'entry_detail' pk=entry.pk %}" <div> <input type="submit" value="Add my thoughts" class="form_btn"> </div> </form> </div> <div class="right"> {% for comment in entry.comments.all %} <div class="comment_box"> <p> {{ comment.name }} says: </p> <p class="comment_text"> {{ comment.text|linebreaks }} </p> <p class="detail_date comm"> {{ comment.date_posted }} </p> </div> {% empty %} <h2 class="background">Be the first to share your thoughts!</h2> {% endfor %} </div> </div> css: .comment_section { border-top: 1px solid #8f666c; margin-top: 2%; display: flex; flex-direction: row; width: 100%; border: 1px solid green; } .left, .right { display: flex; flex-direction: column; width: 45%; border: 1px solid blue; } .right { background-color: transparent; height: inherit; align-self: top; border: 1px solid red; } The rest of my flexbox css works, so I'm guessing the problem lies somewhere with the form? -
Modifying Available and CHosen Choices For ManyToMany Field With Horizontal Filter
Within the Model Admin, is it possible to control what's shown in a ManyToManyField horizontal_filter widget, in both the available and chosen fields? For instance, I have a County model and a Territory model, and want to hide a County if it's already assigned to a Territory. The problem with the below is that selected County objects will be hidden in both the "Available" and "Chosen" widget with horizontal_filter. Is it possible to only hide them in the "Available" column? class TerritoryAdmin(admin.ModelAdmin): filter_horizontal = ('counties',) ordering = ('territory_name', ) # remove counties already assigned to a territory def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'counties': assigned = Territory.objects.all( ).values_list('counties__fips_code', flat=True) kwargs["queryset"] = County.objects.exclude(fips_code__in=assigned) return super().formfield_for_manytomany(db_field, request, **kwargs) -
how to fix (CSRF token missing or incorrect ) react/redux + django
i'm developing authentication [login_page localhost:8000/login/][1] i tried to login but my state is LOGIN_FAIL [LOGIN_FAIL][2] I've checked it's working on postman and I know my template should have this code. <form method="post">{% csrf_token %} But, If I paste this code into Login.js, it makes an error. Like this Login.js: const Login = ({ login }) => { const [formData, setFormData] = useState({ email: '', password: '' }); const { email , password } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = e => { e.preventDefault(); login(email, password); }; // Is the user authenticated // Redirect them to the home page return ( <form method="post">{% csrf_token %} <div className="container mt-5"> {/* <h1>회원가입</h1> <p>이메일로 회원가입</p> */} <form onSubmit={e => onSubmit(e)}> <div className="form-group"> <input className="form-control" type="email" placeholder="이메일" name="email" value={email} onChange={e => onChange(e)} required /> </div> <div className="form-group"> <input className="form-control" type="password" placeholder="비밀번호" name="password" value={password} onChange={e => onChange(e)} minLength='6' required /> </div> <button className='btn btn-primary' type='submit'>login</button> </form> <p className='mt-3'> <Link to='/signup'>signin</Link> </p> <p className='mt-3'> <Link to='/reset_password'>find password</Link> </p> </div> </form> ); }; error code: Forbidden (CSRF token missing or incorrect.): /http//localhost:8000/auth/jwt/create/ [04/Feb/2021 01:33:26] "POST /http//localhost:8000/auth/jwt/create/ HTTP/1.1" 403 2513 authentication trigger code: export const login = (email, password) => … -
Can I use file returned by urllib.request.urlopen as reqular file(file opened with open file)?
below is my Django code import urllib.request as request ... bookmark, created = Bookmark.objects.get_or_create(title=title, url=url, owner=owner) icon = request.urlopen("https://saved.io/assets/img/favicon.ico") bookmark.fav_icon = icon #fav_icon is ImageField bookmark.save() I want to assign the icon retrieved by urlliblib.request module to bookmark.fav_icon which django ImageField -
How to change datetype timestamp without timezone to timestamp with timezone in the Django
models.py class sample(models.Model) a = models.DateTimeField(blank=true, default=true) POSTGRES sample Table a column datetype is a timestamp without timezone I need to change 'a' column datetype timestamp without timezone to timestamp with timezone using Django model. how to achieve this scenario. -
How to redirect to a custom admin page by using a custom admin field in django admin panel
Having my PlugAdmin class class PlugAdmin(admin.ModelAdmin): list_display = (...'custom_link') in admin.py among the other fields of my model I have defined the custom_link field as below: def custom_link(self, obj): info = (obj._meta.app_label, obj._meta.model_name) return mark_safe('<a class="custom" href="%s">Advanced Config Page</a>' % reverse('admin:%s/%s/advanced-config' % info, args=(obj.pk,))) By pressing the custom_link my aim is to redirect to advanced_config_view which is a custom admin page that was defined properly(both in admin.site.urls and as view: def get_urls(self): urls = super().get_urls() my_urls = [ path('<uuid:plug_id>/advanced-config/', self.admin_site.admin_view(self.advanced_config_view), name = "advanced_config"), ] return my_urls + urls def advanced_config_view(self, request, plug_id): plug = Plug.objects.get(id = plug_id) context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), plug = plug, ) return TemplateResponse(request, "custom_admin/advanced_config.html", context) My page can not load and i got the error from Traceback : Template error: In template /home/giorgos/.local/share/virtualenvs/backend-tSqKtrJ_/lib/python3.7/site-packages/django/contrib/admin/templates/admin/base.html, error at line 65 Reverse for 'stations/plug/advanced-config' not found. 'stations/plug/advanced-config' is not a valid view function or pattern name. 55 : <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a> 56 : {% endblock %} 57 : </div> 58 : {% endif %} 59 : {% endblock %} 60 : {% block nav-global %}{% endblock %} 61 : </div> 62 : <!-- END Header … -
Retrieving data with time for multiple users
So I'm making a Django project and the idea is to make a quiz Question shows up, you have four answers you press one and then based on speed and if you got the right answer you get some points. So I made that using ajax and setTimeout and interval functions and a hidden input field for score that's updated every 0.1 seconds (or 0.01 but it doesn't really matter). So the simplified form part looks something like this: <form> <input name="answer1" type="submit" value="Answer 1 Text"> .... # 4 answers <input name="score" type="hidden" value="10"> # The score is based on time left </form> Now I'm not sure how vulnerable that is (I'm guessing it's not very secure to do it like that (especially the score part) and also if for some reason tab is not focused it does intervals and timers once every second (I can make that work but it doesn't really fix the problem)). Now I'm not sure if it would be best to continue working on this solution or use something like channels to receive answers from users (there would be many users answering at the same time so not sure if going the channels route would … -
Django disable Foreing check in sqllitle for development?
Is there a way to disable foreign keys when using sqllitle as database? Loaddata would often fail because of foreign keys, and disabling it would make all work, in mysql I would usually set an init command but it doesn't seem to work with sqllitle. I came up with something like this in settings.py: if 'loaddata' in sys.argv: from django.db import connection cursor = connection.cursor() cursor.execute('PRAGMA foreign_keys = OFF') But it fails as there is in the library base a thing that would reenable it. -
How to add a 'MultipleChoiceField' filter using django-filters
You know when you use the following in forms.py COLORS_OPTIONS = ( ('Red', 'Red'), ('Green', 'Green'), ('Blue', 'Blue'), ) class ColorsForm(forms.ModelForm): color = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=COLORS_OPTIONS) class Meta: model = Color fields = '__all__' and it displays it as checkboxes in your template? I want to do the exact same thing just using django-filters (in order to filter of course). How can I do that? -
Django Restframework using password for jwt_secret
I want to make older refresh tokens invalid whenever a user updates their password. Django restframework jwt takes a function that returns a secret jwt for a particular user. def jwt_get_secret_key(user): jwt_secret = ... return jwt_secret Instead of this being some set value. I wanted it to be a hash of the users password. What's the best implementation for this approach?