Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist error while I am using Class-Based Views in django for updating and deleting a record
Here, I am trying to update and delete the product, but whenever I click on the Update and Delete Link Buttons, it shows me TemplateDoesNotExist at affiliation/affproduct_form.html and for delete, it shows TemplateDoesNotExist at affiliation/affproduct_confirm_delete.html I have created the form and done adding and viewing using function-based views. Below is my models.py : #Product details uploaded class AffProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo') product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255, null=True) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product_title Below is my views for update and delete function. I have not used class-based views for creating and detail. but for updating and deleting i have done using class-based views. # update view for details class AffProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = AffProduct #model fields = ['product_title', 'uid', 'specification', 'sale_price', 'discount', 'img1', 'img2', 'promote_method', 'terms_conditions',] # fields template_name = 'affiliation/affproduct_form.html' # template for updating #success_url = "/blink_viewproduct.html" # redirect url def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def test_func(self): product = self.get_object() if self.request.user == product.user: … -
Django REST Framework: Use of 'pk' in get_object_or_404
I'm a beginner with the Django REST framework and am building an app that summarizes articles with headers. I'm trying to get information from the Article model to pass into the Summary one. I'm having trouble understanding the use of get_object_or_404 in this scenario (how to instantiate a model) and how I use the pk argument. I tried changing the status URL to status/<int:article_id> and passed article as the pk, but I get a 404 when running the POST request. I'm stuck on how to use that argument otherwise. How do I instantiate a model from my request by using get_object_or_404 properly? views.py: import json from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from rest_framework.decorators import api_view from .models import * @api_view(['POST']) def get_summary(request, pk): article = get_object_or_404(Article, pk=pk) mdl = Summary() return JsonResponse(mdl.preprocess(article.content), safe=False) models.py: # Article class class Article(models.Model): headings = models.CharField(max_length=200) content = models.CharField(max_length=500000) # Summary results class (so far) class Summary(models.Model): preprocessor = TextPreprocessor() in_text = models.CharField(max_length=500000) topics = models.CharField(max_length=200) def preprocess(self, text): return self.preprocessor.preprocess(text) urls.py: from django.urls import path, include from rest_framework import routers from .api import * from .views import * router = routers.DefaultRouter() router.register('my_api', SummaryViewSet, 'api') urlpatterns = [ path('api/', include(router.urls)), … -
AttributeError at /akolaprofile/ 'MyRegistration' object has no attribute 'get'
I am trying to create a user profile by using Django's UserChangeForm. I'm not using Django's User model and had created a custom user model (MyRegistration) by inheriting AbstractBaseUser. I have also assigned my custom user model to AUTH_USER_MODEL in the settings.py. But when I try to access the user's profile page, it throws an AttributeError stating that 'MyRegistration' object has no attribute 'get'. What could possibly be wrong? Below are my codes: models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils import timezone from .manager import FirstManager class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('Solapur', 'Solapur'), ('Latur', 'Latur'), ('Dhule', 'Dhule'), ('Akola', 'Akola'), ('Nashik', 'Nashik') ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default='Latur') designation=models.CharField(max_length=70) is_active=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username views.py: def akolaprofile(request): if request.user.is_authenticated: print(request.user) fm=UserChangeForm(request.user) return render(request, 'akola/akolaprofile.html', {'form':fm}) else: return HttpResponseRedirect('/login/') URLs: path('akolaprofile/', ve.akolaprofile, name='akolaprofile'), Template: {% block content %} <form action="" method="post"> {% csrf_token %} {{form.as_p}} </form> {% endblock content %} Traceback: Traceback (most recent call last): File "C:\Users\pande\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\pande\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Sonu\Projects\Billing\accounting\akola\views.py", line 21, in akolaprofile return render(request, 'akola/akolaprofile.html', … -
best practice for Django junction table model structure
I am using a junction table called "UserRole" for 2 different Django model called CustomUser and Role to specify many to many relationship from both of the table. My consideration is 1 customer can have multiple groups and 1 groups has multiple customers. So now I am little confused that my current model is OK or Do I need to modify from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(models.Model): """Model representing a User with some extended fields and email as username field""" USERNAME_FIELD = 'email' email = models.EmailField(max_length=100, unique=True) is_admin = models.BooleanField(default=False) permissions = models.ManyToManyField('Permission', related_name='+') # other fields goes here if needed REQUIRED_FIELDS = [] def __str__(self): """String for representing the Model object.""" return self.email class Role(models.Model): """Model representing a Role""" name = models.CharField(max_length=200) # other fields goes here if needed class Meta: ordering = ['name'] def __str__(self): """String for representing the Model object.""" return self.name class UserRole(models.Model): """Model representing a User's Role""" # ManyToManyField used because one user can have multiple roles and one role can have multiple users role_id = models.ManyToManyField(Role, on_delete=models.CASCADE, null=False, verbose_name = 'Role', related_name='role') user_id = models.ManyToManyField(CustomUser, on_delete=models.CASCADE, null=False, verbose_name = 'User', related_name='user_role') # other fields goes here if needed So my … -
how to analyzing financial stock data properly
I would like to do a lot of analysis/performance/statistics on my stock portfolio, which I plan to track with my app. E.g.: Week performance Month performance Year performance Best performer and a lot of other things I can't imagine right now... Where I'm struggling right now: - What is a good/the best way to archive this? - Also to show this info on a dashboard --> I think I should store this information somehow... But how to do this on a daily/weekly/whatever basis? --> I don't see a way to do such things while runtime? --> Maybe there is also an MVP solution, that can evolve into a top-notch solution? My models are locking like this at the moment - The position is the clamp around my orders and my EOD data. Right now I'm working with yfinance to get range financial data + finnhub API to get real time prices: class Position(models.Model): name = models.CharField(max_length=100) shares = models.FloatField(default=0.0) symbol = models.CharField(max_length=100, default="") transaction_fee_sum = models.FloatField(default=0.0) profit = models.FloatField(default=0.0) average_price = models.FloatField(default=0.0) cost_value = models.FloatField(default=0.0) last_price = models.FloatField(default=0.0) position_value = models.FloatField(default=0.0) last_update = models.DateTimeField(default=datetime.now(), blank=True) position_started = models.DateTimeField(default=datetime.now(), blank=True) position_ended = models.DateTimeField(default=datetime.now(), blank=True) isin = models.CharField(max_length=12) depot = models.ForeignKey("Depot", blank=True, … -
Django pass input data from an HTML file to a python script and then send the final data to another HTML file
I'm trying to build a simple dictionary in Django. In the home.html file there's a form, which asks the user to enter a word. This word should 'become a variable' in a python script which needs it to retrieve certain data from an API. import json import urllib.request url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + user_input response = urllib.request.urlopen(url) result = json.loads(response.read()) final_word = str(result[0]['word']) + ' \n\n' final_def = str(result[0]['meanings'][0]['definitions'][0]['definition'])) 'user_input' would be the variable where the input is stored It should then pass the data obtained from the API (in this case final_word and final_def to another HTML file, final.html I can't figure out how to do this. Any help is appreciated. Comment if I need to add some of the code. Forgive my bad english. -
Styling a email link in Django sent email
I used the example from this example email authorization : to do a user authorization email, which works fine. My email link displays as something like: Hi rascal345, Please click on the link below to confirm your registration: http://127.0.0.1:8000/activate/Mjk/aoi2oo-b778abe73e5c8c0a31910d82039d5d67/ I would like to try to style this link so that it shows as a single clickable button or anchor type link (rather than the link as shown above). I have had a look at various suggestions, but I'm sure how to display this link as a single styled button say. Any suggestions? regards Russell -
Dynamically save the form
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. Currently, I can create a dynamic form, but the thing is I fail to save all data from the form even though I create multiple forms. Now my code only can save only one form. But I want to save the whole form (with multiple form data) in DB. views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, part=part, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'part','po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), 'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}), } HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form"> <div class="form-group"> <label for="po_id" class="control-label mb-1">ID</label> {{ form.po_id }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div … -
ModuleNotFoundError: No module named 'weasyprint'
I have installed WeasyPrint==0.42.3, but when I try to import it in Django, it raises the following error: ModuleNotFoundError: No module named 'weasyprint' When I look at the requirements.txt, it actually shows that it is installed. I am using Django==2.1.5, python==3.8.5. another issue I am encountering is, the version of Django I am using is not listed in the requirements.txt, but when I check the version from the terminal, it shows that I am using the above named version. -
How to send data from any customized HTML form to Django model form without using jinja {{form}} template
This is not a bug-based problem. Basically, an advice-seeking one. I am a newbie and a great fan of Django's function-based view. It allows me to customize as I need. Like I can customize the HTML form as I want. If I wish, I can also put any icons or images or any things inside my <form> </form> tag. On the other hand, the class-based view also provides lots of attractive features in CRUD operation with the jinja form template and Django's model form. So to take advantage of those features I want to use Django's model form. But as I need to customize my <form> </form> also, I need to create an HTML form also, instead of the jinja model form (bootstrap widgets based modification is not enough for it.). So how can I send data to Django's model form from my customized HTML <form>. Kindly suggest me an overall idea in which way I should approach to solve it? You can also provide me any blog or article or tutorial types of stuff. Thanks for reading the full post. -
Best way to modify the fields in response in django rest?
I have a serializer that gives this data class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'name', 'cost', 'currency') class UserSerializer(serializers.ModelSerializer): posts = PostSerializer(many=True) class Meta: model = User fields = ('id', 'name') and it gives the response like this, { "id": 1, "name": "joe", "posts": [ { "id": 20, "name": "first post", "cost": 20.00, "currency": "USD" }, { "id": 21, "name": "second post", "cost": 30.00, "currency": "USD" } ] } However I want to change/add the fields of the response based on few conditions, Eg. if cost is less than 25, make it zero and add a discount field for every post. This is how I am doing. class MyPostView(APIView): def get(request): query_set = User.objects.all() user_and_posts = UserSerializer(query_set) response_data = user_and_posts.data # I am modifying the serializer data here :< for post in response_data['posts']: post['discount'] = 10 # some value if post['cost'] < 25: post['cost'] = 0 return Response(serializer.data, status=status.HTTP_200_OK) To me modifying the primitive data like this is not looking right, is there any alternate way in django rest to do this? or could've done better with serializer? In general, what's the best way to alter the response data we get from serializer and format it … -
Django Page not Loading Favicon in Chrome
I have a Django website with multiple pages, all of them load the favicon without errors on the top browsers (Chrome, Mozilla, Opera...) but recently I have noticed that in Google Chrome, the favicon in my index page isn't load, instead, I get a console error: GET http://127.0.0.1:8000/favicon.ico 404 (Not Found) (this is also happening in production) The problem with this is that I'm not making any request to /favicon.ico, instead, my code to load the icon is: <link rel="icon" href="{% static 'logo.ico' %}"> This is the same code used in the other pages and it loads fine in them, I have already tried to delete cache, delete Favicon folder in Chrome and to load the icon with full path: http://127.0.0.1:8000/static/logo.ico (if I paste this in browser I can see the icon) I don't understand why Chrome keeps making a default request to /favicon.ico instead of to the actual favicon. My Google Chrome version is: Version 91.0.4472.101 (Official Build) (64-bit) Django version is: 3.1.2 I don't think it is an issue with static files, because the favicon is loaded in other browsers, but also it is not a cache problem, do you have any suggestions about how to solve it? -
The url of the image without http is returned
I am writing a rest api application in the django rest framework in which I can post images. I want to receive the url of the image: https://path/image_name.jpg Here is my serializer class: class Serializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_image_url') ... def get_image_url(self, obj): return obj.image.url In this case /media/filename.jpg is returned If I add the https prefix, the link will be displayed, but if I click on it I get an error: browser can not connect to the server localhost -
django model object reuse without erasing data's
In my project I conduct one tournament on one date..so users are like to register the tournament..so I store users register info to my database.. Then the another Date I am conducting another tournament but this time I want to store the user info in the same model without erasing the old tournament data's in database. Because I don't want to create the new Model for every tournament Is there any possible ways to do that? any one help me thanks advance -
django when updating pass the required field
I want to update postModel in my template.But in models.py i don't use blank=True and null=True because when model is creating, i want from user can not pass this area without adding image.But when i was doing update, i want from user they can pass this area if they want and showing image link.How can i do this? models.py class postModel(models.Model): STATUS = ( ("yes" , "YES"), ("no" , "NO") ) image=models.ImageField( upload_to="post_images", ) title=models.CharField( max_length=100, blank=False, null=False ) slug=AutoSlugField(populate_from="title",unique=True) content=RichTextField() writer=models.ForeignKey(CustomUserModel,on_delete=models.CASCADE,related_name="articles") categories=models.ManyToManyField(CategoryModel,related_name="posts") is_slider=models.CharField(max_length=10,choices=STATUS,default="no",verbose_name="IS slider?") created_date=models.DateTimeField(auto_now_add=True) updated_date=models.DateTimeField(auto_now=True) readingCount=models.SmallIntegerField(default=0) is_published=models.CharField(max_length=10,choices=STATUS,default="no",verbose_name="Is published") forms.py class addPostForm(forms.ModelForm): class Meta: model = postModel fields=("title","categories","content","is_slider","image") widgets = { "title" : TextInput(attrs={"class":"form-control","style":"color: black; text-transform: none;"}), "categories" : SelectMultiple(attrs={"class":"form-control"}), "content" : Textarea(attrs={"class":"form-control"}), "is_slider" : Select(attrs={"class":"form-control"}), "image" : FileInput(attrs={"class":"form-control"}), } views.py @login_required(login_url="login_view") def update_post(request,slug): post=get_object_or_404(postModel,slug=slug) if request.method == "POST": form = addPostForm(request.POST or None,request.FILES or None) if form.is_valid(): post=form.save(commit=False) post.writer=request.user post.save() form.save_m2m() return redirect("update_post",slug=post.slug) else: return redirect("update_post",slug=post.slug) form=addPostForm(instance=post) context={ "form":form, "post":post, } return render(request,"update_post.html",context) -
django-admin is showing error ,How can i fix it?
When I run this command to create django project but it error, How can I fix it. C:\Users\pawat\Documents\madpro\testapp>django-admin startproject name . Traceback (most recent call last): File "c:\users\pawat\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\pawat\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\pawat\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle('project', project_name, target, **options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\templates.py", line 160, in handle with open(new_path, 'w', encoding='utf-8') as new_file: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\pawat\\Documents\\madpro\\testapp\\manage.py' -
Workaround for logging out a user logged in using HTTP Apache LDAP in django
In the Django 2.2 application, user is allowed to log in "through http (Apache LDAP)" by providing username and password in the browser prompt (as shown below): Problem is that when I logout the user using the default django logout defined in django.contrib.auth, the user is still able to access the application. In simple words, the django login and logout have no effect on the application. I have learnt that, the only way to logout the user is by closing the browser window. But I wanted to implement the logout functionality usin django. After a bit of googling about this issue, I found something relatable here, which shows the following method: class HttpAuthMiddleware(object): def process_request(self, request): if request.path == '/accounts/logout/': httpResponse = HttpResponse() httpResponse.status_code = 401 httpResponse.headers['WWW-Authenticate'] = 'Basic realm="<same realm as in the http server>"' return httpResponse else: # check for http headers - maybe the user is already logged in using http auth ... This is a workaround for the logout feature. It basically checks for the request.path == '/accounts/logout/' which helps me in using the default django logout function. I want this snippet to redirect the user back to the same login prompt that browser provides (as … -
How to get django syndicate to pull the hostname correctly
While using view reverse with django syndication, get_absolute_url() returns correctly but with wrong host, I'm always getting the link with http://localhost instead of my domain, where is that configured ? How to get it to return my hostname Thank you forum_patterns = [ path('p/<str:uid>/', views.post_view, name='post_view'), ] Post: def get_absolute_url(self): url = reverse("post_view", kwargs=dict(uid=self.root.uid)) return url if self.is_toplevel else "%s#%s" % (url, self.uid) getting: <rss version="2.0"> <channel> <title>Post Feed</title> <link>http://localhost/</link> <description>Posts that match africa</description> <atom:link href="http://localhost/feeds/tag/africa/" rel="self"/> <language>en-us</language> <lastBuildDate>Sun, 06 Jun 2021 03:56:58 +0000</lastBuildDate> -
How to refresh related objects in the django signals?
Here anothermodel_set represents the Foreign Key relationship to the AnotherModel from SenderModel. When Creating SenderModel I am not being able to query it's related objects to the AnotherModel SenderModel is being created normally by django generic CreateView. @receiver(post_save, sender=SenderModel) def some_signal(sender, instance, created, **kwargs): if created: if instance.parent_id: print(instance.id, instance, 'instance', flush=True) # returns id no issue instance.refresh_from_db() related_objs = AnotherModel.objects.filter(obj=instance) # returns None related_objs = instance.anothermodel_set.all() # returns None #But when Do this in shell related_objs = obj.anothermodel_set.all() # returns queryset -
Test Django with dictionary in dictionary data
Description I'm using Django for my website and trying to write some unit tests. However, when using dict in dict data I met some errors. I found out that view received slightly different data. From {'class_id': '1', 'filter_options': {'full_name': 'user 1'}} in data of test file to <QueryDict: {'class_id': ['1'], 'filter_options': ['full_name']}>. I means that value has changed to array, and value of nested dict wasn't detected. Code # test.py def test_search_with_full_name(self): data = {'class_id': '1', 'filter_options': {'full_name': 'user 1'}} response = self.client.post('/api/students', data, format='json') self.assertEqual(response.status_code, 200) # view.py class SearchStudentView(generics.GenericAPIView): def post(self, request): print(request.data) if not 'class_id' in request.data: return HttpResponse('class_id is required', status=400) class_id = request.data['class_id'] students = Users.objects.filter( details_student_attend_class__course__pk=class_id) if 'filter_options' in request.data: filter_options = request.data['filter_options'] if 'full_name' in filter_options: students = students.filter( full_name=filter_options['full_name']) Thanks for any help! -
How to create a slot interval between two hours in Django
I am trying to create slot intervals from two given times ie Input : Start time : 1:00 End time : 2:00 Output: 1:00-1:15 , 1:15 - 1:30, 1:30-1:45 , 1:45 - 2:00 Code I am currently using: THE SLOT GENERATOR import datetime def time_slots(start_time, end_time): t = start_time while t <= end_time: yield t.strftime('%H:%M') t = (datetime.datetime.combine(datetime.date.today(), t) + datetime.timedelta(minutes=15)).time() USAGE: >>> import datetime >>> start_time = datetime.time(13, 00) >>> end_time = datetime.time(14, 00) >>> list(time_slots(start_time, end_time)) THE ISSUE IS : If I give inputs as Start time as 9:00am ie datetime.time(9, 00) Endtime as 12:00am ie datetime.time(0, 00) then i get an empty list , So how do i solve it CODE REFERENCED FROM: Create 15-min slots between two hours in Django -
Notes should be showed only for the author
In my note taking project, I want to do so, that notes should be showed only for the author of the object. I am trying to solve this problem for 3 days. But, I could not solve this. Please Help! Thanks in an advance view.py @login_required(login_url='login') def index(request): tasks = Task.objects.all() if request.method=='POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save() obj.owner = request.user obj.save() return redirect('/') form = TaskForm() user = request context = { 'tasks' : tasks, 'form':form, 'obj':obj } return render(request, 'list.html',context) models.py class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
django session value not passing.The value is not passing while creating session in cart in ecommerce project
Iam creating an Ecommerce site and iam creating session to for the cart functionality.but my values is not passing to the session dictionary. basket.py ''' class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self,product): product_id=product.id print(product_id) if product_id not in self.basket: print(product.price) self.basket[product_id]={'price':product.price} print(self.basket[product_id]) print(self.basket) self.session_modified=True ''' views.py ''' def add_product(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id =int(request.POST.get('productid')) print(product_id) product = get_object_or_404(Product, id=product_id) print(product) basket.add(product=product) response=JsonResponse({'test':'data'}) return response ''' when i am printing all the values are showing in the terminal but when i am decoding the session key the value are not passing or showing {'skey': {}} are showing. -
How to use multiple if statements to color p tags
Im trying to color these four p tags based off of if they are either the correct answer or the one a user picked, there seems to be an error in the if statements however because it will only color it green or red, the loop doesnt go to color the red one for what the user picked and green for the correct answer <p {% if quiz.correctness1 == 0 %} {% if quiz.userAnswer1 == 'a' %} style="color:red;" {% endif %} {% endif %} {% if quiz.answer1 == 'a' %} style="color:green" {% endif %}> A. {{ quiz.q1Choice1 }}</p> <p {% if quiz.correctness1 == 0 %} {% if quiz.userAnswer1 == 'b' %} style="color:red;" {% endif %} {% endif %} {% if quiz.answer1 == 'b' %} style="color:green" {% endif %}> It will only color red if they are wrong and the if statements don't countinue to do both red and green -
How to nest these Serializes without facing AttributeError: 'BlogPost' object has no attribute 'review_set'
I followed Dennis Ivy proshop Tutorial He used the same approach as the code is class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' class ProductSerializer(serializers.ModelSerializer): reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_reviews(self, obj): reviews = obj.review_set.all() serializer = ReviewSerializer(reviews, many=True) return serializer.data Now I need a Blog for the eCommerce Project and I created another app named blog and Created the models as class BlogPost(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200, null=True, blank=True, help_text="Like How To Treat Hypertension etc") image = models.ImageField(null=True, blank=True, default='/placeholder.png') rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) youtubeVideoLink = models.CharField(max_length=1000, null=True , blank=True) def __str__(self): return str(self.createdAt) class BlogPostReview(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) But when I serialize them via same approach as mentioned above.... class BlogPostReviewSerializer(serializers.ModelSerializer): class Meta: model = BlogPostReview fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): blog_post_reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = '__all__' def get_blog_post_reviews(self, obj): blog_post_reviews = obj.review_set.all() …