Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get model datefield value
la = model._meta.get_field(field).__str__ returns <bound method Field.__str__ of <django.db.models.fields.DateField: date>> How do I get the value of the date field specifically the year? -
Django DRF works, but gives error back to AJAX call
I have kind of successfully implemented an AJAX request for to PUT in DRF. Everything is working fine, but the error callback in AJAX is triggered: drf part: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentication,] permission_classes = [IsAuthenticated,] serializer_class = ProductSerializer def put(self, request): ... return Response(data = "OK", status = status.HTTP_200_OK) AJAX part: let write2db = function ( data ) { let csrf_token = $('[name="csrfmiddlewaretoken"]').attr('value'); $.ajax({ url: "api/products/", type: "PUT", data: JSON.stringify(data), dataType: "string", headers: { 'X-CSRFTOKEN': csrf_token, "Content-type": "application/json" }, success: function (request, status, error) { console.log(request, "--", status, "---", error) window.location = "/pe/?message=success&status=success"; }, error: function ( request, status, error ) { window.location = `/pe/?message=${error} - ${request.responseText}&status=danger`; } }); }; when using this JSON: data = {'number': '2', 'data': {'name': 'brand new', 'price': '2.4'}} in the console I get: "GET /pe/?message=No%20conversion%20from%20text%20to%20string%20-%20%22product%20updated%22&status=danger HTTP/1.1" 200 8188 short: No conversion from text to string. -
how to save search input query from url
I'm trying to implement a way to have my url search value carried over from one view to another. For example. if I have the url http://127.0.0.1:8000/post/search_result/posts?search=harry It would use my SearchPostView view to display all filtered posts with the authors name being harry. However on that same page I want users to be able to click a button that would take them to a page where it would show all users on the site with the name harry. My problem stems from when I try to use redirect the user to the page of filtered users, I dont understand how I could carry over the ?search=harry url value to my SearchUserView view. A good visual example is how github implements this. in the url they have search?q=harry where it would show the filtered repo page with harry in the name. If I were the click on Users button on the side navbar, it would then show the url being search?q=harry&type=users with the filtered users page Although I'm not trying to completely copy github, I essentially just want to know how to keep that url query in different views. Thanks! -
How to Implement Dependent/Chained Dropdown List with Django
I followed this tutorial on [How to Implement Dependent/Chained Dropdown List with Django][1]. But for some reason it does not work. I can get to the point that the dropdown menu's show the right list that i want. But when i try to save my form it gives me an error that the fields are requiered even if i fill them in. I keep my project on [github][2] I hope someone can have a look at my code up untill now and can point me in the right direction. Tanx in advance. [1]: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html [2]: https://github.com/JeroenSchwab/Beamtime.git -
how to show useredited data in pdf using xhtml2pdf
I am making a resume builder website in Django. In which I have made an editable template in which user can edit their information. but when I generate a pdf it is not giving content that is currently added into a template by the user. Please suggest how can I show in pdf user-edited data using xhtml2pdf view.py from django.shortcuts import render import os from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO from django.views.generic import View from django.contrib.staticfiles import finders # Create your views here. def index(request): context = {'index': 'active'} return render(request,'main/index.html',context) def render_pdf_view(request): template_path = 'main/index.html' context = {'myvar': 'this is your template context'} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response index.html {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSE Template1!</title> <style type="text/css"> @page { size:A4; … -
Save file with Django Model to JSONField
I need to save files, but the number of files is uncertain, and in one request I can add a file, then in another request post, I can add one more file ... For this reason I thought that creating a JSONField type field could help me in this matter, but I don't know if it is possible and if it is possible I have no idea how to implement it in Django. Here is an example of how I currently upload a single file to Django Model: import uuid import time from users.models import User from django.db import models def upload_location(instance, filename): filebase, extension = filename.split('.') milliseconds = int(round(time.time() * 1000)) return 'events/thumbnail_images/%s__%s__%s.%s' % (instance.user_id, instance.name, milliseconds, extension) class Test(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) image_link = models.FileField(upload_to=upload_location) user = models.ForeignKey( User, null=True, blank=False, on_delete=models.CASCADE ) As I'm using Postgres relational database, and I'm not sure how many files the user will want to save, I figured using JSONField, so that as the user adds files, the 'path+filename' is also added. It's possible? How to make? -
Django using sessions and cookies in the same view function
I'm trying to set the cookies and use the sessions as well but when I set the cookies, it doesn't detect the cookies on the website. I don't know what I did wrong so help me out please. Thanks. view.py from django.http import HttpResponse def session(request): num_visits = request.session.get('num_visits', 0) + 1 request.session['num_visits'] = num_visits resp = HttpResponse('View Count=' +str(num_visits) + ' e78e39ea') resp.set_cookie('dj4e_cookie', 'e78e39ea', max_age=1000) resp.set_cookie('zap', 42) return HttpResponse(resp) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.session), ] -
Django login error, LOGIN_REDIRECT_URL is not working
When I click the login button the next page shows HTTP ERROR 405. Register works fine, but the only login doesn't work. Should I make login class and 'success_url = reverse_lazy('dashboard')'? I think LOGIN_REDIRECT_URL is the problem, but I'm not sure. Why is this happening? urls.py is from django.contrib import admin from django.shortcuts import redirect from django.urls import path from apps.common.views import HomeView, SignUpView, DashboardView from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('', HomeView.as_view(), name='home'), path('dashboard/', DashboardView.as_view(), name='dashboard'), path('register/', SignUpView.as_view(), name='register'), path('login/', auth_views.LoginView.as_view( template_name = 'common/login.html' ), name='login'), path('logout/', auth_views.LogoutView.as_view( next_page='home' ), name='logout' ), ] view.py is from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm from django.urls import reverse_lazy from django.contrib.auth import authenticate, login from django.contrib import messages from django.contrib.auth.views import LoginView class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('home') class SignUpView(CreateView): form_class = SignUpForm success_url = reverse_lazy('home') template_name = 'common/register.html' I also add LOGIN_REDIRECT_URL = 'dashboard' in settings.py -
Django model loads from one file (views) and not another app's models.py
I have a Collection model in a collection app, and it loads fine for use in views (below), but when I try to load it for use in a ManyToMany field for another model, I get the error: ImportError: cannot import name 'Collection' from 'collection.models' This project uses allauth, which uses the term collection internally, but that doesn't explain (to me) why models from the collection app would load from one file and not another. Ideas? views.py #ok from collection.models import Collection ... def get_context_data(self, *args, **kwargs): ... collection_list = Collection.objects.all().order_by('create_date') models.py #errors out from collection.models import Collection ... class Items(models.Model): ... field1 = models.CharField(null=False, max_length=255) collections = models.ManyToManyField(Collection) -
I want to call {% for element in element_object %}
I have a question in detail.html. {% for element in element_object %} {{ element.value_code }} {% endfor %}</p> It doesn't recognize this part. What's the reason? All categories and products are loaded, but the element cannot be loaded. It's been 24 hours since I didn't solve it. I feel like I'm going to die of boredom. I would be very grateful for your reply views.py from django.shortcuts import get_object_or_404 from django.shortcuts import render from zeronine.forms import ElementForm from zeronine.models import * def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category_code=current_category) return render(request, 'zeronine/list.html', {'current_category': current_category, 'categories':categories, 'products':products}) def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'element':element_object}) detail.html {% extends 'base.html' %} {% block title %} 상품 상세보기 {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-4"> <img src="{{product.image.url}}" width="190%" style="margin-top: 100px;"> </div> <div class="text-center col" style="margin-top:150px; margin-left:200px;"> <b><h4 class="content" style="margin-bottom: -5px;"><b>{{product.name}}</b></h4></b> <br> <div> <!-- <span>주최자 : <b>{{ product.username }}</b></span><br>--> <span style="color: #111111">모집기간 : <b>{{ product.start_date }} ~ {{ … -
Unable to get django-ckeditor field to load in admin when static files hosted on Digital Ocean using Django-storages
admin - richtextfield This was working when hosting my static files locally in development. Now I am hosting on my Dokku server with static and media files stored In DigitalOcean Spaces. Im using django-ckeditor in my model as a RichTextfield class Resume(models.Model): headline = models.CharField(verbose_name='Headline', max_length=120) about = RichTextField(verbose_name='About Me') user = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created At') modified_at = models.DateTimeField(auto_now=True, verbose_name='Modified At', null=True, blank=True) In my settings.py, I think i've defined more than needed for Django-storages to function. Not really sure if the AWS_QUERYSTRING_AUTH needs to be defined though. Tried both ways, then just decided to make my bucket read-able to the public AWS_ACCESS_KEY_ID = os.getenv('SPACES_ACCESS_KEY_ID') # access key AWS_SECRET_ACCESS_KEY = os.getenv('SPACES_SECRET_ACCESS_KEY') # secret AWS_STORAGE_BUCKET_NAME = os.getenv('SPACES_BUCKET_NAME') AWS_S3_REGION_NAME = 'sfo3' AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' # s3 static settings STATIC_LOCATION = 'static' STATIC_URL = f'{AWS_S3_ENDPOINT_URL}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'config.custom_storages.StaticStorage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'{AWS_S3_ENDPOINT_URL}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'config.custom_storages.MediaStorage' AWS_QUERYSTRING_AUTH = False # ckeditor with AWS In the console, I can see that 2 resources do not load when on admin page. config.js en.js Both are from ckeditor/ckeditor folder, which there are many other scripts that successfully load from this … -
In Django how to populate a form dropdown list form a column in a database
I am new to Django and python. I am attempting to populate a field in a custom user creation form with values in a separate table/column the database. Those values are created via another app and model (the Django Machina forum app). So far I have not been able to figure out how to even import the model to gain access to the values. My models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) business_location_state = models.CharField(max_length=100) views.py from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'age',) signup.html {% extends 'base.html' %} {% block title %} Sign Up {% endblock title %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock content %} The Machina github is found here: https://github.com/ellmetha/django-machina Any ideas about how to use values in … -
ImportError when using heroku for my django web
I checked django is installed properly and in my 'requirements.txt' I wrote 'Django==3.2.3'. However, I cannot use this code: heroku run python manage.py migrate So I checked this code: python manage.py migrate and found out it worked properly. I know that there are existing questions and read many of them, but I think I have tried everything I could do. I would be really grateful if someone can solve this problem. -
Reverse for 'mobile' not found. 'mobile' is not a valid view function or pattern name
urls.py from django.urls import path from app import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.ProductView.as_view(),name="home"), path('product-detail/<int:pk>', views.ProductDetailView.as_view(), name='product-detail'), path('cart/', views.add_to_cart, name='add-to-cart'), path('buy/', views.buy_now, name='buy-now'), path('profile/', views.profile, name='profile'), path('address/', views.address, name='address'), path('orders/', views.orders, name='orders'), path('changepassword/', views.change_password, name='changepassword'), path('mobile/<slug:data>', views.mobile, name='mobiledata'), path('login/', views.login, name='login'), path('registration/', views.customerregistration, name='customerregistration'), path('checkout/', views.checkout, name='checkout'), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
How do I get Django rest framework to respect the "required=false" designation in my serializer?
I'm using djangorestframework==3.12.2 . I have this Serializer. Some fields, like "desc_english" I don't want to be required ... class ValidateNewCoopSerializer(serializers.Serializer): coop_name=serializers.CharField() street=serializers.CharField() address_public=serializers.CharField() city=serializers.CharField() state=serializers.CharField() zip=serializers.CharField() county=serializers.CharField() country=serializers.CharField() websites=serializers.CharField() contact_name=serializers.CharField() contact_name_public=serializers.CharField() contact_email=serializers.CharField() contact_email_public=serializers.CharField() contact_phone=serializers.CharField() contact_phone_public=serializers.CharField() scope=serializers.CharField() tags=serializers.CharField(required=False) desc_english=serializers.CharField(required=False) desc_other=serializers.CharField(required=False) req_reason=serializers.CharField() which is used in my views.py file like so @api_view(('POST',)) def save_to_sheet_from_form(request): """ This is supposed to write to a Google sheet given a form coming from the client. """ valid_ser = ValidateNewCoopSerializer(data=request.data) if valid_ser.is_valid(): post_data = valid_ser.validated_data ... return Response(post_data, status=status.HTTP_201_CREATED) else: return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST) I notice, though, that when I submit requests, the fields are mark as not required are coming back with errors ... curl 'http://localhost:8000/save_to_sheet_from_form/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: http://localhost:3001/' -H 'Content-Type: application/json' -H 'Origin: http://localhost:3001' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data-raw '{"coop_name":"","street":"","address_public":"no","city":"","state":"IL","zip":"","county":"","country":"US","websites":"","contact_name":"","contact_name_public":"no","contact_email":"","contact_email_public":"no","contact_phone":"","contact_phone_public":"no","scope":"local","tags":"","desc_english":"","desc_other":"","req_reason":"add"}' results in {"coop_name":["This field may not be blank."],"street":["This field may not be blank."],"city":["This field may not be blank."],"zip":["This field may not be blank."],"county":["This field may not be blank."],"websites":["This field may not be blank."],"contact_name":["This field may not be blank."],"contact_email":["This field may not be blank."],"contact_phone":["This field may not be blank."],"tags":["This field may not … -
Fields Don't show in django admin
Fields Don't show in django admin While trying to add role through django admin it doesn't show the field class Role(Core): role = models.CharField(max_length=25, unique=True, editable=False) def save(self, *args, **kwargs): self.role = self.role.lower() super(Role, self).save(*args, **kwargs) def __str__(self): return self.role.capitalize() admin.site.register(Role) class Core(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True enter image description here -
How can I Connect this with django authentication
Here is the code I am using to create firebase phone authentication using JavaScript https://github.com/singh-shreya6/firebase-google-phone-signin Now, can I add additional fields such as first name and last name of django user model and create a user profile when the registration is complete? How can i do so? Any one can explain? My key purpose is logging in/signing in the user when they enter the correct otp. And with pyrebase I can authenticate using email and password. But what about a phone number? How can I connect that with the backend? -
How to use multiple storage like AWS S3 storage, Google cloud , Azure in Django as per customer request
I want to use multiple cloud storage in Django as per customer request. So if customer says he want to use AWS S3 then he should be able to configure or if he want to use Azure . My challenge is With Django's default file storage. Don't know how to set Default storage if every customer wants to use different cloud storage as per request. DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' Looking for approach to solve this problem. Little help will be appreciated. Thanks -
CSS file not found on MacOS
I am a beginner at web development. I am using Python and Django on a Mac. When I want to link CSS to HTML, this shows in the command line and on the web page is still only text from the html file. Command line: Not Found: /style.css [29/May/2021 17:37:12] "GET /style.css HTTP/1.1" 404 2095 This is my HTML file: <html> <head> <title>Webpage</title> <link rel="stylesheet" href="style.css"> </head> <body> <p>Webpage</p> </body> </html> and this is my CSS file: body { background-color: royalblue; } -
Are django abstract models really that useful?
I have recently come across this in one of django related blog post! class Client(models.Model): name = models.CharField(max_length=255, required=True) # .. other fields class Meta: abstract = True After reading the docs I couldn't understand what the purpose of "abstract = True" is. Any help will be useful. Thanks! -
django web app deployment on windows 10 using apache server(WAMP) not displaying CSS for admin site
On Windows 10 django app when run using development server by using command python manage.py runserver shows admin login page and admin site correctly. but if same django app at same path when served using apache is not displaying css correctly for admin login and other admin site pages. I have tried to follow steps at https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/modwsgi/ but some configuration/setting is missed/incorrect resulting in css not applied to admin login page and admin site. my development and deployment is on same windows 10 computer with WAMP server 3.2.3.3. I have installed mod_wsgi and following are relevent section from settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secrete key is listed here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', ] 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', … -
xlsx file not being exported django rest framework
I am calling ajax request from frontend to export data in excel sheet. js function exportData(){ create_spinner("Please wait while we export data."); var agent = $("#agent").val() var dateRange = $("#dateRangeValue").val() var queue = $("#queue").val() var direction = $("#direction").val() var department = $("#department").val() var serviceLevel = $("#sl").val() $.ajax({ type: 'POST', url: "/call-record-api/export-data/", data: { "agent": agent, "dateRange": dateRange, "queue": queue, "direction": direction, "department": department, "serviceLevel": serviceLevel, }, success: function(resultData) { console.log("success"); hide_spinner(); }, error: function (err) { console.log("AJAX error in request: " + JSON.stringify(err, null, 2)); create_spinner("Couldn't export data. Please try again"); setTimeout(function(){ hide_spinner()}, 1000); } }); } I have gone through documentation and implemented the same. urls.py url(r'^call-record-api/export-data/$', ExportCallRecordView.as_view({"post":"list"})), views.py class ExportCallRecordView(XLSXFileMixin, ReadOnlyModelViewSet): def get_queryset(self): calls = export_customized_calls(self.request) print(calls.count()) return calls serializer_class = CallRecordSerializer renderer_classes = [XLSXRenderer] filename = 'call_record_export.xlsx' But i cannot see the file getting downloaded. However i can see success in browser console. -
How to perform multiple insertion using django rest viewsets?
I'm working on this api where a user can select multiple languages and can mark the proficiency in each language. The model is as follows. class UserLanguage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) proficiency = models.DecimalField(max_digits=4, decimal_places=2) class Meta: db_table = "user_language" Serializer looks like: class UserLanguageSerializer(serializers.ModelSerializer): class Meta: model = UserLanguage fields = '__all__' I have done the views as follows class UserLanguageViewSet(viewsets.ModelViewSet): queryset = UserLanguage.objects.all() serializer_class = UserLanguageSerializer The code works fine for a request like { "proficiency": "04.00", "user": 1, "language": 1 } I want the api to accept a list like this: [ { "proficiency": "05.00", "user": 1, "language": 1 }, { "proficiency": "04.00", "user": 1, "language": 1 }] For each item in the list I want to create a new row in 'user_language' table. Am I doing it the right way? If not show me the right way. How should I modify my models, serializer or view to attain this? I don't know if the above request is in the right format. If not please let me know. Thank you. -
DRF: SearchField for custom queruset
I have get_queryset() overrited method in my ModelViewSet class - it return qureyset with filter by user. So i need implement a SearchFilter search not only in queryset, returned by get_queryset method (Follow.objects.filter(following=self.request.user)), but in all values from model - in Follow.objects.all() There is my class: class FollowViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): queryset = Follow.objects.all() serializer_class = FollowSerializer filter_backends = (filters.SearchFilter,) search_fields = ("user__username", "following__username") def perform_create(self, serializer: Serializer) -> Follow: following = self.request.data.get("following") if not following: raise ParseError( detail="following must be transfered", code=status.HTTP_400_BAD_REQUEST, ) if self.request.user.get_username() == following: raise ParseError( detail="User cant follow himself", code=status.HTTP_400_BAD_REQUEST, ) return serializer.save(user=self.request.user) def get_queryset(self) -> QuerySet: return Follow.objects.filter(following=self.request.user) -
Best way to display a field site-specific using the Django Sites framework
I'm currently using the Django Sites framework with two sites. I have a model called Product, and I only want to display the product price on one of the sites. How could i achieve this in the Django admin? I'm currently using a many-to-many relationship on the display_price field, but it feels somewhat "dodgy". My code: class Product(models.Model): name = models.CharField( _('Product name'), max_length=255, unique=True ) ... display_price = models.ManyToManyField( Site, related_name='display_price_product_site', blank=True ) ... sites = models.ManyToManyField( Site, related_name='product_site', blank=True ) objects = models.Manager() on_site = CurrentSiteManager()