Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't I save data in django model from files other than views?I am getting this error
I want to save data in a model. Lets say I want to hard code data from views.py it saves but when i try to do it by creating a seperate file it doesn't. It doesnt import models at all giving error ImportError: attempted relative import with no known parent package.Am I missing something here : I have tried doing: from .models import className from models import className from . import models and calling models.className -
Unable to show user specific link to specific page in django
I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form. So my problem is, when I filled out the form and redirect to list/ page, there are no links. My code: models.py from django.db import models from django.contrib.auth.models import User class File(models.Model): file = models.OneToOneField(User, on_delete=models.CASCADE, null=True) #Further, they are fileds, which is nececary to create schedule. #title = models.CharField('Название Графика', max_length = 50) #x_title = models.CharField('Название Оси Х', max_length = 50) #y_title = models.CharField('Название Оси Y', max_length = 50) #etc... views.py: def create(request): error = '' if request.method == 'POST': form = FileForm(request.POST) if form.is_valid(): form.save() return redirect('grafic:list') else: error = 'Форма была неверной(' form = FileForm() data = { 'form': form, 'error': error, } return render(request, 'graf/create.html', data) def list(request): qs = File.objects.filter(file=request.user) context = { 'user': request.user, 'qs': qs, } return render(request, 'graf/list.html', context) list.html {% extends 'base.html' %} {% block content %} … -
count event by day?
I need to do a count view that counts the appointments by day for example if there are 4 appointments on June 20 and 3 appointments on June 21. if I logged in on June 20 it will only show me the 4 appointments. this is my current view which didn't work models.py class Appointment(models.Model): appointment_date = models.DateField(null=True) appointment_time = models.TimeField(null=True) patient = models.ForeignKey('Patient', on_delete=models.CASCADE) reseptionist = models.ForeignKey('Reseptionist', on_delete=models.SET_NULL, blank=True, null=True) service = models.ForeignKey('Service', on_delete=models.CASCADE) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) views.py def count_appointment(request): appointment = Appointment.objects.filter(appointment_date__day=datetime.today().day).count() data = {} data['appointment'] = appointment return render(request, 'index.html', context=data) index.html {{appointment.count}} -
How to logout in django
i have created login system for my project. but this login is not django's built in authentication. I think i have successfully completed login but i am unable to logout by either built-in authentication or custom logout. def loginpage(request): if request.method == "POST": loginemail = request.POST.get('email') loginpassword = request.POST.get('password') try: var = Patient.objects.get(email=loginemail) if var.password == loginpassword: #i am not sure for this line also wheather it's right or not for login request.session['user'] = var.id return redirect('/patient') else: messages.add_message(request, messages.INFO, 'Hello world.') except: return HttpResponse("Not Logged in") return render(request, 'home/login.html') this is function i have created for login but not sure if that is working perfectly or not but if i print(request.session) it is giving <django.contrib.sessions.backends.db.SessionStore object at 0x10a150bb0> def handlelogout(request): if request.session: print(request.session) try: del request.session['user'] except: print("not logged out") return redirect('loginpage') this is function for log out. but it always print not logged out in terminal. now what can i do to specify login and logout in this project. -
django-autocomplete-light dependant filter over 3 models
I have 3 models. class FilterDefaultValues(BaseModel): value = models.CharField(max_length=255, null=True, blank=True) display_value = models.CharField(max_length=255, null=True, blank=True) class Filter(BaseModel): name = models.CharField(max_length=255) default_value = models.ManyToManyField(FilterDefaultValues, blank=True) class ProductFilter(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='filters') filter = models.ForeignKey(Filter, on_delete=models.CASCADE) value = models.ForeignKey(FilterDefaultValues, blank=True, on_delete=models.RESTRICT) urls.py class LinkedDataView(autocomplete.Select2QuerySetView): def get_queryset(self): qs = super(LinkedDataView, self).get_queryset() filter = self.forwarded.get('filter', None) if filter: qs = qs.filter(filter_id=filter) return qs urlpatterns = [ url( '^linked_data/$', LinkedDataView.as_view(model=ProductFilter), name='linked_data' ), ] forms.py class ProductFilterForm(forms.ModelForm): def clean_test(self): filter = self.cleaned_data.get('filter', None) value = self.cleaned_data.get('value', None) if value and filter and value.filter != filter: raise forms.ValidationError('Wrong owner for test') return value class Meta: model = ProductFilter fields = ('product', 'filter', 'value', 'value_type', 'product_images', 'is_variation') widgets = { 'value': autocomplete.ModelSelect2(url='linked_data', forward=('filter',)) } class Media: js = ( 'linked_data.js', ) What I want to is in the admin panel when the user selects a filter, then the value field must be populated with appropriate default values. But now what I get is: When user selects filter then only productfilter items are populated here. What I am missing here? -
Why Django cannot extends my form.html contact page and returns a TemplateSyntaxError or an Exception Thrown?
I'm trying to build a contact page ("/contact-us/") as a modular app instead of the similar already working contact page ("/contact/") located in the "/app/" directory. The former is failing, returning either Exception Thrown or TemplateSyntaxError while trying to {% extends %} the form.html with its base.html. My file structure: BlogDjango |-BlogDjango | | settings.py | | urls.py |-app | |-Templates | | | base.html | | | form.html |-blogpost |-contactform | |-Templates | | | base.html | | | form.html | | forms.py | | views.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),os.path.join(BASE_DIR,'app','templates'),os.path.join(BASE_DIR,'contactform','templates')],... base.html <!DOCTYPE html> <html> <head></head> <body> {% block content %}{% endblock %} </body></html> form.html {% extends base.html %} {% block content %} {% if title %} <h1>{{ title }}</h1> {% endif %} <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> {% endblock %} It seems that Django doesn't recognise that the base.html is located in the same directory than the form.html and therefor cannot extend it. So I get those two errors thrown at me: Exception Thrown: Failed lookup for key [base] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x000001D62DDBBAF0>>, 'request': <WSGIRequest: GET '/contact-us/'>, … -
Does HTTP 401 response from server clears user credentials from browsers cache?
My Django 2.2 application is using basic http authentication with Apache LDAP. Users can login by entering their username and password using the browser pop-up (image shown below): I'm working on writing a logout function that would return a httpresponse. Below is an incomplete example snippet of what I have mentioned: 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: ... I wanted to know if returning Status code: 401, clear the credentials in browser cache. If not, then is there any other way I can achieve this? Any help is highly appreciated! -
Python: Module not found while importing from multiple subfolders
I have a folder structure like below (attached image) enter image description here In Main.py I imported all the folders. Now Main.py calls subMain.py which is inside the Project 1. subMain.py imports spark, common etc. Now sparkUtils.py has functions from helper.py hence need to import helper.py This throws module import error that "No module named Common" I tried putting init.py in all the folders, however no luck. Can anyone help please? Thanks in advance. -
How to recover deleted data from AWS PostgreSQL database for Django project?
I tried to add a new field in my existing Django project. I run the following command to do it: manage.py makemigrations manage.py migrate appname zero manage.py makemigration manage.py migrate Now I have lost all my previous data from the database (PostgreSQL) for that application. The migration folder only has the most recent migration file. How can I retrieve previous data? I am using AWS PostgreSQL in the project. Any help/suggestion will be appreciated. -
How to include the thumbnail image with using TabularInline admin model?
What I am trying to do I would like to include thumbnail in PhotoInline and could be shown into ProductAdmin. What I have done I made two admin model which are ProductAdmin and PhotoInline. PhotoInline model is a separate admin model that only contains information of photos of products, which is to be connected to ProductAdmin. Inside of PhotoInline, I included custom admin function called product_thumbnail and tried to include list_display admin option of ProductAdmin. Here are my codes: class PhotoInline(admin.TabularInline): ''' PhotoAdmin Definition ''' model = models.Photo fieldsets = ( ( None, { 'fields': ('caption', 'file',) } ), ) extra = 0 and then ProductAdmin admin model looks as follows: @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): ''' ProductAdmin Definition ''' inlines = [ PhotoInline, ] list_display = ( 'product_name', 'product_price', 'product_color', 'product_size', 'product_category', 'is_onsale', 'is_newarrival', 'is_preorder', ) list_filter = ( 'is_onsale', 'is_newarrival', 'is_preorder', ) ordering = ('product_name', 'product_price', 'product_category') search_fields = [ 'product_name', 'product_category' ] Error that I got <class 'products.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[8]' refers to 'product_thumbnail', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'products.Product'. It seems my approach is somewhat wrong. Do I need to include separate ImageField for my Product … -
Django: Simple One:Many fields aren't showing in parent object view in admin
I'm new to Django and have made a couple of classes whereby one Account can have many Subscribers. When viewing a subscriber in the django admin, it correctly shows which account the subscriber is related to. However, when looking at the account, it does not show which subscribers it has. I saw an article (How to create many-to-one relation with django and to display it in admin interface) that suggested using inlines, although it’s not working for me. Where am I going wrong here? Models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): pass class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) date_joined = models.DateTimeField(auto_now_add=True, null=True) verified = models.BooleanField(default=False) account = models.ForeignKey( Account, on_delete=models.CASCADE) def __str__(self): return self.email list_display = ('first_name', 'email', 'date_joined', 'verified') Admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from accounts import models # does nothing class SubscriberInline(admin.TabularInline): model = models.Subscriber extra = 1 admin.site.register(models.Account, UserAdmin) # does noting class AccountAdmin(admin.ModelAdmin): inlines = [SubscriberInline, ] #inlines = (SubscriberInline, ) @admin.register(models.Subscriber) class SubscriberAdmin(admin.ModelAdmin): list_display = ("first_name", "email", "date_joined", "verified", "account") -
Remove specific object from Many-to-many relationship
I have Two models : class Product(models.Model): product_model = models.CharField(max_length=255, default='') ... class Discount(models.Model): name = models.CharField(max_length=255, default='') items = models.ManyToManyField(Product, blank=True) discount_percent = models.IntegerField(default=0, validators=[ MaxValueValidator(100), MinValueValidator(1), ] ) I want to delete specific item from items(ManyToManyField) my views : def delete_from_discount(request, id, product_url): if request.user.is_staff or request.user.is_superuser: a = Product(product_url=product_url) b = Discount(id=id) b = b.items.remove(a) return redirect("/staff/discount/"+id) else: return redirect('/staff') There is no error but also nothing change from my models, no remove my html: {% for dis in discount.items.all %} <a href="/staff/discount/delete-from-discount/{{discount.id}}/{{dis.product_url}}/">delet</a> {% endfor %} -
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