Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django MakeMigrations Error Traceback
Here is what appears when i try to use python manage.py makemigrations traceback error Here is models.py code ----------------------code------------------------------------- from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'categories' # def get_absolute_url(self): # return reverse("store:category_list", args=[self.slug]) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) author = models.CharField(max_length=255,default='admin') description = models.TextField(blank=True) image = models.ImageField(upload_to='images/') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=4, decimal_places=2) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title ------------------code end------------------------------- im new and i dont know whats the problem -
'ForwardManyToOneDescriptor' object has no attribute 'user_type'
Models.py class UserType(models.Model): owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) user_type=models.CharField(max_length=20,default='admin') Views.py def register(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') fname = request.POST.get('firstname') lname = request.POST.get('lastname') email = request.POST.get('email') newpass = make_password(password) newuser = User.objects.create(username=username,password=newpass,first_name=fname,last_name=lname,email=email) newuser.save() usertype = request.POST.get('usertype') newtype = UserType.objects.create(user_type=usertype) newtype.save() messages.success(request, "Registration successful") if UserType.owner.user_type == 'Student': return redirect('Stuproadd') elif UserType.owner.user_type == 'Teacher': return redirect('Teachproadd') else: return redirect('index') return render(request, 'register.html') register.html <body> <h1>Register</h1> <div class="container"> <form method="post"> {% csrf_token %} <label>Username:</label> <input type="text" name="username" placeholder="Enter your username" required /><br><br> <label>First Name:</label> <input type="text" name="firstname" placeholder="Enter First Name" required /><br><br> <label>Last Name:</label> <input type="text" name="lastname" placeholder="Enter last name" /><br><br> <label>Email:</label> <input type="text" name="email" placeholder="Enter your email" required /><br><br> <label>password</label> <input type="password" name="password" placeholder="enter your password" required /> <br><br> <label>confirm password</label> <input type="password" name="password" placeholder="confirm your password" required /> <br><br> <label>Select your Role:</label> <input type="radio" name="usertype" value="Student"> <label>Student</label> <input type="radio" name="usertype" value="Teacher"> <label>Teacher</label> <button type="submit">Register</button> Already User,<a href="{% url 'index' %}">Login Here</a> </form></div> </body> This is the code.I'm getting error as 'ForwardManyToOneDescriptor' object has no attribute 'user_type' After clicking register button, I want to go to stuproadd when the user type is student and teachproadd when the user type is teacher. How is it? pls help -
Django : meaning of {% url 'zzz' %}?{{ yyy }}?
I came across a code in a HTML file and I did not understand how it works. {% url 'calendar' %}?{{ prev_month }} Especially, what does the "?" mean? And how is the code interpreted? It is used in a button to switch between month but I cant figure out how it works. I tried to print different places in the code to see what is executed with but I did not find anything interesting. Thanks -
how to output data from a linked table in django?
I have a built-in User table and a Note table associated with it by key. class Note(models.Model): header = models.CharField(max_length=100) note_text = models.TextField() data = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py. I tried different ways, don't know how to do that. -
create a subarray of products with unique username (django)
I need an array of customer orders where username are unique and the order quantity should be added on. I got the result using annotate but I need an subarray with product name and respective quantity as sub array. Please check the outputs I got and outputs required below. Thanks in advance views.py orders = Order.objects.values('staff_id', 'staff__username', 'product__name').annotate(quantity=Sum('order_quantity')).order_by() models.py class Product(models.Model): name = models.CharField(max_length=100, choices=PRODUCTS, null = True) quantity = models.PositiveIntegerField(null = True) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) Output: [ { "staff_id":15, "staff__username":"John", "product__name":"samsung", "quantity":2 }, { "staff_id":15, "staff__username":"John", "product__name":"apple", "quantity":18 }, { "staff_id":16, "staff__username":"test", "product__name":"apple", "quantity":100 } ] Output required [ { "staff_id":15, "staff__username":"John", "product": [ { "product__name":"samsung", "quantity":2 }, { "product__name":"apple", "quantity":18 } ] }, { "staff_id":16, "staff__username":"test", "product": [ { "product__name":"apple", "quantity":100 } ] } ] -
How to merge two model in one fieldset in django admin module
I have two table like below tableA field1 field2 field3 tableB field4 field5 Group 1 field1: textfield (tableA) field3: textfield (tableA) field5: textfield (tableB) Group 2 field2: radiobutton (tableA) field4: textfield (tableB) I tried the solution like form inlines but I want the grouping of fields in one form, not a separate inline form. -
Any help, on why is returning the same status in every object here?
So I have a search endpoint here which will fetch the users that contains certain entry and check if there is any on going friends relationship. My endpoint: path('filter/', SearchUserByStringAPIView.as_view()), My View: class SearchUserByStringAPIView(ListAPIView): queryset = User.objects.all() serializer_class = UserProfileSerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = self.queryset.filter(username__icontains=self.request.query_params.get('search')) return queryset My Serializer: class UserProfileSerializer(serializers.ModelSerializer): friendship = serializers.SerializerMethodField() def get_friendship(self, obj): user_obj = self.instance.values_list('id') friends_obj = Friend.objects.filter(Q(receiver=self.context['request'].user) | Q(requester=self.context['request'].user)).values_list('requester', 'receiver', 'status') if not friends_obj: pass else: for f in friends_obj: for i in user_obj: if int(i[0]) in f: return str(f[2]) pass class Meta: model = User fields = ['id', 'username', 'about_me', 'avatar', 'friendship'] My Response : [ { "id": 2, "username": "BB", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 3, "username": "BiG", "about_me": "", "avatar": "http://127.0.0.1:8000/media-files/BigG/Screen_Shot_2022-11-14_at_22.06.55.png", "friendship": "A" }, { "id": 7, "username": "babybabybear", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 13, "username": "shadabjamil", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 14, "username": "sirberkut", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 17, "username": "buddlehman", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 20, "username": "tforbes", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 30, "username": "ol99bg", "about_me": "", "avatar": null, "friendship": … -
How to send mail from users Gmail with Oauth in django
I'm currently working on website project. It's intended to be used by business owners to send invoices to their customers. Each owner is a django user model instance and have an organization model associated to them. Now I don't know how to ask permission from owner to give me access to him account and used these credentials to send invoices to customers. I'm working with django and drf. A minimalist HTML CSS and JavaScript are used for front. I had already done mail sending with Gmail but only for desktop app and I needed to save app credentials to filesystem. Does exist anyway to do it with web app ? Thanks in advance. -
Why doesn't show profile picture from the database?
setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py profile_photo = models.ImageField(null=True,blank=True,upload_to='upload') everything all my pages - my question pages here my database problem I have tried many times and search everything in here. but not yet show profile_image in database. Can anyone tell me what's problem in my page? -
Using Flex To Create a 3x2 Grid | Django Template for loop
I am using Django Templating for my blog, and am adding cards using a for loop. I am trying to create a 3x2 structure of the added cards. Currently, each card takes up an equal amount of space within the div. I am trying to model what they have at Ahrefs Blog. That similar sort of structure for their most recent 6 posts. This is my HTML/Bootstrap 5 code: <div class="latest-articles"> {% for post in post_list %} <div class="card mb-4 mx-3 publishedPost"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text">{{ post.author }} | {{ post.createdOn }}</p> <p class="card-text">{{post.content|slice:":200" }}</p> <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> This is my CSS code: .latest-articles { display: flex; flex-wrap: wrap; flex-direction: row; justify-content: center; align-items: stretch; padding-top: 0; text-align: center; position: relative; padding: 10px; } .publishedPost { flex: 1; } Any help is massively appreciated -
Pass data in body of API request
I need to update some info in my database using PUT request and Django rest framework So i have this urls and i need to update max_date parameter (pass True or False) but i have 0 ideas how to do it without passing a variable in the url, like api/config/max_date/<str:bool> -
How do I put django cms plugins classes inside multiple files instead of just putting it all inside cms_plugins.py?
So I have a project where I am using Django CMS as the root of my project. First of all I'm new to Django CMS, and I now want to code some plugins to put into my pages. I searched for the solution but everywhere it says that I should put it inside cms_plugins.py. I tried creating a folder named cms_plugins and created an __init__.py file inside it. Then I created the plugin inside a file named ThePlugin.py and coded my plugin the same way I did it in cms_plugins.py. Unfortunately it's not working. If someone can help me I'd be really gratefull. Thanks. -
Is Django only good for web applications where a user logs in? [closed]
Is Django only good for web applications where a user logs in? The reason I ask is because I recently learned Django and built a website where a user could sign up, input their measurements, and the website tells them how many calories they should eat. Is there a way to build this website in a way where the user doesn't need to sign up or log in? I've seen Javascript-based exampled where data is carried from page to page using cookies but using Python / Django the only way I know how to do this is by using a database. -
How to generate newsfeed / timeline consisting of different types of contents?
I have to implement a newsfeed for an application where I need to show different types of content. And in the future, some new types of content may come. I have the following idea in my mind at a high level. At this point of time, I'm not concerned about ranking, caching, etc. My focus is to generate newsfeeds having different types of content. class ContentType1(models.Model): pass class ContentType2(models.Model): pass class ContentType3(models.Model): pass class Content(models.Model): c_type = models.CharField( max_length=6, choices=[ ('TYPE1', 'Type 1 content'), ('TYPE2', 'Type 2 content'), ('TYPE3', 'Type 3 content') ] ) type_1 = models.ForeignKey(ContentType1, null=True, blank=True) type_2 = models.ForeignKey(ContentType2, null=True, blank=True) type_3 = models.ForeignKey(ContentType3, null=True, blank=True) The idea is to have a general Content model having separate fields for every type of content and a field named c_type which determines the type of the content and guides to access the corresponding field. And responding to users' requests from the Content queryset. I'm not fully satisfied with the approach, looking for a better approach maybe something with polymorphism or any better approach using Django. -
You're using the staticfiles app without having set the required STATIC_URL setting - Django
I have 5 months of experience in django and I can not just find the solution of the error which I encounter. I think it depends on frontend files, I can not deal with static files right now Recently, I have been building a chat app called PyChatt Whole project available on Github -> here Please I need your help urgently!!! traceback: Traceback (most recent call last): File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\python_projects\Webogram\Internal\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\management\commands\runserver.py", line 35, in get_handler return StaticFilesHandler(handler) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 75, in __init__ self.base_url = urlparse(self.get_base_url()) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 30, in get_base_url utils.check_settings() File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\utils.py", line 49, in check_settings raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting. and settings.py: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-pke21+-&vpt2=ka6$a_=x5vz-@#_)o^ro#eet+h03sy&y-l+8w' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'UsersAuthentication', 'MessageHandleEngine', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { … -
Check box field in django forms showing error
Based on my django project I want to add multiple users to a group and I'm trying to do this using a form. But when I try adding choices via CheckBoxSelectMultiple() widget its not working as expected. models.py file from django.db import models from members.models import User from django.contrib.auth.models import Group class Sprint(models.Model): status_choice = [('Working','Working'), ('Closed','Closed')] sprint_name = models.CharField(max_length=180) sprint_created = models.DateTimeField(auto_now= True) lead = models.ForeignKey(User, on_delete=models.CASCADE, related_name='team_lead') sprint_members = models.ForeignKey(Group, on_delete=models.CASCADE, related_name = "member") sprint_period = models.PositiveIntegerField() sprint_status = models.CharField(max_length=10, choices=status_choice, default='Working') forms.py file from django import forms from .models import Sprint from members.models import User from django.core.exceptions import ValidationError from django.contrib.auth.models import Group class SprintForm(forms.Form): sprint_name = forms.CharField() sprint_period = forms.IntegerField(label="Sprint period (in days)", min_value=7) lead = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), label="Team Lead") sprint_members = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), widget= forms.CheckboxSelectMultiple(), label="Team members") # class Meta: # model = Sprint # fields = ['sprint_name', 'lead', 'sprint_period', 'sprint_members'] def clean(self): cleaned_data = super().clean() lead = cleaned_data.get('lead') team = cleaned_data.get('sprint_members') if team and lead: if lead in team: raise ValidationError('Team lead cant be in team') def save(self): team = Group.objects.get_or_create(name=f'team{self.cleaned_data["sprint_name"]}')[0] for team_member in self.cleaned_data['sprint_members']: team.user_set.add(team_member) Sprint.objects.update_or_create( sprint_name=self.cleaned_data["sprint_name"], lead=self.cleaned_data["lead"], sprint_period=self.cleaned_data["sprint_period"], _members=team ) views.py file class SprintCreationView(generic.FormView): model = Sprint template_name … -
WebSocket dosn't work with postman (django channels)
I have a Django project which I run locally on my mac. And I use channels to create websocket connection. And an interesting thing happened: The web socket works when I try to connect through .html file: myTemplate.html const ws = new WebSocket( 'ws://' + window.location.host +'/ws/test/?token=' +'**mytoken**' );' I can send, and receive messages. But the same URL doesn't work in postman or https://websocketking.com/ Firstly, I thought it is because I run server locally. But on real server nothing works at all. I searched all stackoverflow and implement everything - to no avail. asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev') django.setup() from channels.routing import ProtocolTypeRouter,get_default_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import path, re_path from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from myapp import consumers, routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) ), }) settings ASGI_APPLICATION = 'spacetime.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', *** ] vccode console Django version 4.1.2, using settings 'spacetime.settings.dev' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the … -
Django. Asynchronous requests are executed in only one async event loop
I'm trying to find out how to use Django 4.0 asynchronous request support. There is one very strange thing I can't understand: Django (uvicorn or asgi.py) creates only one event loop for two different views, despite the fact that I specified max_workers=8 in uvicorn settings. This can lead to a case, when we have a lot of views (ex. 100) and in this views there are a lot of CPU-bound logic (ex: conditions, loops, calculations, etc) and a lot of IO-bound logic. Using async/await we speed up and optimize all IO-bound operations, but our CPU-bound logic is slowing down our event-loop. Instead of using event-loop for every process (worker), it uses only one loop, while other workers (7) stand still. I think, it isn't a normal behavior. What do you think? Check the code below to see more details: views.py import asyncio import os import random import time from django.http import HttpResponse from django.utils.decorators import classonlymethod from django.views import View class AsyncBaseView(View): @classonlymethod def as_view(cls, **initkwargs): view = super().as_view(**initkwargs) view._is_coroutine = asyncio.coroutines._is_coroutine return view class AsyncTestView(AsyncBaseView): async def get(self, request, *args, **kwargs): r = random.randint(1,4) print('Recieved', r) print('PID = ', os.getpid()) # Simulate long code-inside operations (conditions, loops, calculations, ets) … -
Trying to make Follow button dynamic. Follow, Unfollow feature addition
If we click, follow button it should update followers then show unfollow and if clicked again it should show follow, decrementing followers. urls.py urlpatterns = [ path('',views.index, name = 'index'), path('signup',views.signup, name = 'signup'), path('signin',views.signin, name = 'signin'), path('logout',views.logout, name = 'logout'), path('settings',views.settings, name = 'settings'), path('profile/<str:pk>',views.profile, name = 'profile'), path('like-post',views.like_post, name = 'like-post'), path('upload',views.upload, name = 'upload'), path('follow',views.follow, name = 'follow'), ] profile.html <span style="color: white; font-size: 27px;"><b>{{user_followers}} followers</b></span> <span style="color: white; font-size: 27px;"><b>{{user_following}} following</b></span> <input type="hidden" value="{{user.username}}" name="follower"> <input type="hidden" value="{{user_objects.username}}" name="user"> {% if user_object.username == user.username%} <a href = "/settings" data-ripple="">Account Settings</a> {% else %} <a data-ripple="">{{button_text}}</a> {% endif %} views.py @login_required(login_url='signin') def profile(request, pk): user_object = User.objects.get(username=pk) user_profile = Profile.objects.get(user=user_object) user_posts = Post.objects.filter(user=pk) user_post_length = len(user_posts) follower = request.user.username user=pk if FollowersCount.objects.filter(follower = follower, user = user).first(): button_text = 'Unfollow' else: button_text = 'Follow' user_followers = len(FollowersCount.objects.filter(user=pk)) user_following = len(FollowersCount.objects.filter(follower=pk)) context = { 'user_object': user_object, 'user_profile': user_profile, 'user_posts':user_posts, 'user_post_length':user_post_length, 'button_text': button_text, 'user_followers': user_followers, 'user_following': user_following } return render(request, 'profile.html', context) models.py class FollowersCount(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) def __str__(self): return self.user admin.py from django.contrib import admin from .models import Profile, Post, LikePost, FollowersCount # Register your models here. admin.site.register(Profile) admin.site.register(Post) admin.site.register(LikePost) admin.site.register(FollowersCount) I have … -
(Many to one relation) not forwarding sub-fields of child object when creating parent object
I am creating a Project object, with a milestone child object as a field of project, using ForeignKey and nested-serializers. first i wrote the test for creating milestone(s) on creating a new project : PROJECTS_URL = reverse('project:project-list') def test_create_project_with_new_milestones(self): """Test creating project with milestones""" payload = { 'title': 'Test', 'time_hours': 10, 'milestones': [ { 'title': 'FirstMilestone', 'hierarchycal_order': 1, 'order': 1 }, { 'title': 'FirstMilestoneSub', 'hierarchycal_order': 1, 'order': 2 }, { 'title': 'SecondMilestone', 'hierarchycal_order': 2, 'order': 1 }, ], } res = self.client.post(PROJECTS_URL, payload, format='json') """ ... + rest of the test ...""" Then updated serializers.py adding function to create milestones and updating the create function adding creation of milestones in a similar way as i did for tags(working for tags but tags is many to many relation ship and has only a name field): class ProjectSerializer(serializers.ModelSerializer): """Serializer for projects""" tags = TagSerializer(many=True, required=False) milestones = MilestoneSerializer(many=True, required=False) class Meta: model = Project fields = ['id', 'title', 'time_hours', 'link', 'tags', 'milestones'] read_only_fields = ['id'] ... def _create_milestones(self, milestones, project): """Handle creating milestones as needed.""" auth_user = self.context['request'].user for milestone in milestones: milestone_obj, created = Milestone.objects.create( user=auth_user, project=project, **milestone, ) project.milestones.add(milestone_obj) def create(self, validated_data): """Create a project.""" tags = validated_data.pop('tags', []) milestones … -
The view "../{api}" didn't return an HttpResponse object. It returned None instead. Unable to make api fetch request due to following error?:
I have a views.py containing an api. I am calling a function that does a fetch request. I get an error relating to my code not returning a specific object type. Setup: vuejs frontend, django backend Function in methods: add_auction_item(){ console.log('testing..'); if (this.item_name.length > 0){ var auc_item = { 'item_name': this.item_name, 'item_condition': this.item_condition, 'posted_by': this.posted_by, 'created_at': this.created_at }; this.auction_items.unshift(auc_item) fetch('/add_auction_item_api/', { method:'POST', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken':'{{ csrf_token }}', 'Content-Type':'application/json' }, body: JSON.stringify(auc_item) }) } Api in views.py: @login_required @csrf_exempt def add_auction_item_api(request): if request.method=='POST': data = json.loads(request.body) item_nme = data['item_name'] item_cond = data['item_condition'] item_pstd_by = data['posted_by'] Item.objects.create(item_name=item_nme, item_condition=item_cond,posted_by=item_pstd_by) return JsonResponse({'new':'updated'}) -
How can I access Django model fields in form via JavaScript to auto calculate fa ield?
I would like to auto-calculate my deposit amount height in a form. Therefore, I included JavaScript to make it happen. The idea: After entering the net into the form, the suitable deposit height will be displayed in the amount field. And there is nothing to do for the user here. I really appreciate any suggestions since I am total beginner with Django. I tried to access the field via known methods like netObj.fishing_type and ['fishing_type'] but I feel like this is not the issue. Somehow I can't access the model fields of the triggered record. html file {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content%} <p> </p> <div class ="form-group"> <form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <script> // Get the input elements by targeting their id: const net_input = document.getElementById('id_net'); const vessel_input = document.getElementById('id_vessel'); const amount = document.getElementById('id_amount'); // Create variables for what the user inputs, and the output: let netObj = 0; let vesselObj = 0; let height = 0; // Add an event listener to 'listen' to what the user types into the inputs: net_input.addEventListener('input', e => { netObj = e.target.value; console.log(netObj); updateAmount() }); // Update the value of net … -
How to test file upload in pytest?
How to serializer a file object while using json.dumps ? I 'm using pytest for testing file upload in django and I 've this function def test_file_upload(self): # file_content is a bytest object request = client.patch( "/fake-url/", json.dumps({"file" : file_content}), content_type="application/json", ) I 've tried to set the file_content as a bytes object but I 'm getting this error TypeError: Object of type bytes is not JSON serializable I need to send the whole file to my endpoint as json serialized -
How to rollback changes if error into chain celery django task?
The scheme is: chain(group | result_task). How can I rollback changes in database if error? Is it possible to use database transactions in this situation? -
my static folder where I place my js ans css files is not at the root of my django project. How to call these satic files in the template?
Here is the configuration of my static_root variable: STATIC_ROOT = [os.path.join(BASE_DIR,'vol/web/static')] My templates are at the root of the project. TEMPLATES={ ... 'DIRS':[os.path.join(BASE_DIR, 'templates')], ... } This is how I call my bootstrap.min.css file in a project template: <link rel="stylesheet" href="{% static 'assets/plugins/bootstrap/css/bootstrap.min.css' %}"> But it doesn't work because the file is not loaded. What's the right way to do it?