Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReactJS/Django project: How to handle video uploading/viewing by users?
I don't know if this is the right place to ask but I'm building a website using ReactJS as frontend and Django REST as backend (may or may not be relevant...), and I'm looking for a way for users to upload a video and view them on my website. What's generally the way to go? Do you store it locally? Or do you use a video hosting platform? Youtube? -
Split a string in django template
I am storing tags as a string seprated by commas in a model and i am trying to print those in template but it is not working I tried Django templates - split string to array answer but it is also not working nothing is printed and the function tags_as_list is also not running model class News(models.Model): link = models.TextField() headline = models.TextField() summary = models.TextField() tags = models.TextField(blank=True) time_date = models.DateTimeField(auto_now_add=True) def tags_as_list(self): print("tagsss") return self.tags.split(',') template {% for tag in news_item.tags.tags_as_list %} {{ tag }} {% endfor %} -
How to create Django_filter in Checkbox view on my website front panel?
I am using django_fiter package for filter data, but it's displaying filter in the input box or some filter in the dropdowns, but I want all filters in the checkbox (like as Django default admin panel filter), please let me know how I can convert it in checkbox filter on my website front panel. Here is my code for filter view form... <form method="get"> {{ filter.form|bootstrap }} <input type="submit" /> </form> and here is my views.py file code... class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Product fields = ['saleprice', 'title','veg_non','brand','supplement'] it's looking like this... and I want in this format, please let me know how I can customize it. -
Django redirect to a specific page after login
I want to redirect the user every time to a specific page after login. The problem is that I also have pages that requires login and after the login was successful it does not redirect me first to that page what I have added in LOGIN_REDIRECT_URL but also redirect me to what was in the 'next'. So what I exactly want is that if the user clicked on that link witch requires login, after the login was successful firstly to redirect to a custom page and after it to be able to get the next parameter from the url to redirect to the second page if he clicks for example to an "Ok" button. -
Can I use GET request in login page
Hi i am using Django and Vue js to make a web application. I am a beginner in web dev. So in my website's login page which I am rendering through Django built loginview I am making a get request with axios to another url which I named ajax_validate_user. This url is mapped to a function which checks whether the user has provided correct credentials or not by using the Django authenticate function. If the user has not provided correct info then it returns a JSON response thus reducing page load . I wanted to know if it's the correct way to do it or not. Also if the user has provided correct info then the form submits to the login view normally. Thank you -
Cannot query "justin@gmail.com": Must be "User" instance
I am trying to save data using django rest framework, and i am having trouble on registering account, so far this is the error i've encountered Cannot query "justin@gmail.com": Must be "User" instance. what should i do to fix this ? did i miss something? here is my models.py from rest_framework.authtoken.models import Token from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from rest_framework.authtoken.models import Token class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR … -
DRF custom write field not in model used on post_save
Simply example: Let's supose that I have a field on my DB with string 'Hello' and I want to receive a name from an API call but, instead of saving that name, I want to save the full string, something like 'Hello Peter' where hello is data from DB and Peter the I string received from API. models.py: class MyModel(models.Model): regular_model_field = models.CharField(max_length=255, blank=True) field_to_populate_regular_model_field = models.CharField(max_length=100, default='Hello') serializers.py: class MyModelSerializer(serializers.ModelSerializer): write_only_serializer_field = serializers.CharField(max_length=100, write_only=True) signals.py: Note: AppConfig is ok, signal is working without this field and, of course, It's working on update. @receiver(post_save, sender=MyModel, weak=False) def generate_regular_model_field(sender, **kwargs): instance = kwargs.get('instance') generated_data = f'{instance.write_only_serializer_field} {instance.field_to_populate_regular_field}' instance.regular_model_field = generated_data post_save.disconnect(generate_regular_model_field, sender=sender) instance.save() post_save.connect(generate_regular_model_field, sender=sender, weak=False) Possible solution: Use model create on serializer and move all code from post_save to serializer create (removing post_save in process of course). Similar like this answer. Do you have another solution?. Things I saw googling: Use validated_data.pop('write_only_serializer_field', None). I need this field on post_save, I should't remove it. Move post_save to pre_save or save. I require the default value generated on DB by field_to_populate_regular_model_field, on my real app this default is dynamic but I use "Hello" for simplicity. Use SerializerMethodField. Nope, I need to write … -
Mailchimp vs in-built django mail system
From a performance point of view, is it better to use mailchimp for my marketing campaigns or creating a model, storing my email list there and sending mass mails from my django app? -
Django filter form in tab pane django table
I'm trying to apply django-filter for a django-tables2 table inside a tab-pane tab-content. The filter is displayed but not works. models.py code from django.db import models from library.models import Category class CategoryWordsSettings(models.Model): category= models.OneToOneField(Category, on_delete=models.CASCADE) words_list = models.TextField() tables.py code import django_tables2 as tables from .models import CategoryWordsSettings class CategoryWordsSettingsTable(tables.Table): action_buttons = tables.TemplateColumn(verbose_name='Actions', template_name='settings/actions.html', orderable=False) class Meta: model = CategoryWordsSettings template_name = "custom_table.html" fields = ("category", "words_list", "action_buttons") attrs = { "class": "table table-striped table-bordered", "style": "margin-top:15px;" } filters.py Code import django_filters from library.models import UserData, Category import django.forms as forms from .models import CategoryWordsSettings def categories(request): if request: if not request.user.is_superuser: catgories= UserData.objects.filter(user=request.user).select_related('category') return catgories return Category.objects.all() class CategoryWordsFilter(django_filters.FilterSet): category = django_filters.ModelChoiceFilter(field_name='category', queryset=categories, widget=forms.Select(attrs={'class': 'form-control'}),) words_list = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput(attrs={'class': 'form-control'}) ) class Meta: model = CategoryWordsSettings fields = ['category', 'words_list'] views.py code from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from library.models import UserData from .tables import CategoryWordsSettingsTable from .filters import CategoryWordsFilter from django.http import HttpResponseRedirect from django.urls import reverse from .models import CategoryWordsSettings def index(request): template_name = 'settings/index.html' data = {} data['self'] = UserData.objects.get(user=request.user) table_setting_words = CategoryWordsSettingsTable(CategoryWordsSettings.objects.all()) filter_words_setting = CategoryWordsFilter(request.GET, request=request, queryset=CategoryWordsSettings.objects.all(), ) filter_words_setting_fields = CategoryWordsFilter.get_fields() if not request.user.is_superuser: table_setting_words.exclude = 'category' filter_words_setting_fields.exclude = … -
Django's --fake-initial doesn't work while migrating with existing tables
I am migrating a project from Django 1.1 to Django 3.0 I am done with the project. When I am dumping the production dump to my local in the newly converted project I get "Table already exists". Here's what I am doing. mysql> create database xyx; docker exec -i <container-hash> mysql -u<user> -p<password> xyx < dbdump.sql then I run the migrate, as I have had to do some changes to the previously given models. ./manage.py migrate --fake-initial this is the output I get _mysql.connection.query(self, query) django.db.utils.OperationalError: (1050, "Table 'city' already exists") So, what to do ? -
Django MongoDB Migration Warnings
Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://www.patreon.com/nesdis OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "DROP CASCADE" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK I'm trying to connect Django with MongoDB database. Why am I getting these warnings while migrating? -
Change Class Base to Function Base
i am working on a project and i am following a turtorial on youtube, but it is well implemented with class base view, i am better of function base. I do not understand class base so well, i will be glad if someone here can help me change class base to function base. Please take your time. Thanks Url: path("inbox", InboxView.as_view(), name='inbox'), re_path(r"^messages/(?P<username>[\w.@+-]+)", ThreadView.as_view(), name="messages"), Views.py: class InboxView(LoginRequiredMixin, ListView): template_name = 'inbox.html' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['chat_list'] = Thread.objects.filter(Q(first=self.request.user)| Q(second=self.request.user)) #Online Users context['online_user'] = Profile.objects.filter(friends__user=self.request.user, is_online=True) return context class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'thread.html' form_class = ComposeForm success_url = './' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() context['chat_msg'] = ChatMessage.objects.all().order_by('-timestamp') context['chat_list'] = Thread.objects.filter(Q(first=self.request.user)| Q(second=self.request.user)) context['online_user'] = Profile.objects.filter(friends__user=self.request.user, is_online=True) return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") ChatMessage.objects.create(user=user, thread=thread, message=message) return super().form_valid(form) -
JSON parse error - Expecting ',' delimiter
i'm trying to post some data to the data base using django rest framework this is the user profile so the user must be able to add this informations to his profile but im getting this error when i do a post request with some dummy data: "detail": "JSON parse error - Expecting ',' delimiter: line 5 column 14 (char 86)" her is my models.py class Profile(models.Model): user_id = models.OneToOneField(Account,on_delete=models.CASCADE,null=True, blank=True) first_name = models.CharField(max_length=60,blank=False) last_name = models.CharField(max_length=60,blank=False) wilaya = models.CharField(max_length=60,blank=False) city = models.CharField(max_length=60,blank=False) address = models.CharField(max_length=200,blank=False) store_coordinates = models.CharField(max_length=60,blank=False) documents1 = models.CharField(max_length=60,blank=False) documents2 = models.CharField(max_length=60,blank=False) def __str__(self): return self.user serializer.py class ProfileSerializer (serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' exclude = ('user_id') the view.py @permission_classes([IsAuthenticated]) @api_view(['GET', 'POST']) def profile(request): user = request.user if request.method == 'GET': account = Account.objects.filter(username=user) serializer = AccountSerializer(account, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user_id = request.user serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) dummy data {"first_name":"jhone", "last_name":"mike", "wilaya":"jijel", "city":"18"; "address": "MyAdress", "store_coordinates":"87689787", "documents1":"image", "documents2":"docx",} -
Python - Graphql - forward CSRF to Django api
I have a graphql mutation which calls a django-rest-framework function. It is in another microservice so I'm using requests.post. I'm gettingg a Forbidden (CSRF cookie not set.). I added the CSRF header to the Graphql request(in the frontend) and removed csrf_exemptbut it didn't help. It seems that Graphql is not forwarding the header to DRF. Anyone has any idea? -
file upload in Django not saving file anywhere
I am really lost and I hope you guys can help me. I am trying to do a simple file upload form on Django. The form shows on screen and submitting it doesn't throw an error, but the file is not saved anywhere. What am I doing wrong? Thanks a lot VIEWS.PY from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm from .functions import handle_uploaded_file def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'enter.html', {'form': UploadFileForm}) FORMS.PY from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() FUNCTIONS.PY def handle_uploaded_file(f): with open('rrls/media/upload/name.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) -
How do I install mod_wsgi on my apache server installed from xampp package?
I downloaded the mod_wsgi package and was hit with an issue while configuring the make file. the command i used was sudo ./configure --with-apxs=/opt/lampp/bin/apxs. i got the follwing message. ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for prctl... yes checking Apache version... ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory ./configure: line 2769: /: Is a directory checking for python... /usr/bin/python ./configure: /opt/lampp/bin/apxs: /bin/perl: bad interpreter: No such file or directory configure: creating ./config.status config.status: creating Makefile so i changed the first like of the apxs file from /bin/perl to /usr/bin/perl and then i got this when i ran … -
How to add Placeholder text in fields with django crispy-forms
I'm new to django and using crispy-forms to render the form.How do i add placeholder text to a field e.g "please enter your address" In my views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['name', 'address'] In models.py class Post(models.Model): name = models.CharField(max_length=100, blank="true") address = models.CharField(max_length=100, blank="true") -
Django gives AttributeError - '_thread._local' object has no attribute 'state'
I am creating a django application which requires mathematical computation using the sympy python package. To give you an example of the kind of computation that is involved lets consider we have three equations- x+y=100 y=200 z+x=300 I calculate all possible values for x,y and z using the solve() method of sympy package. However, this gives an AttributeError - '_thread._local' object has no attribute 'state' Below is the complete traceback - Environment: Request Method: GET Request URL: http://127.0.0.1:8000/results/24/ Django Version: 3.0.3 Python Version: 3.6.10 Installed Applications: ['hlasoftware.apps.HlasoftwareConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages'] Installed 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'] Traceback (most recent call last): File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Anjali Jain\HLA\hlasoftware\views.py", line 163, in results reactive_eplets=predict.mfi_predictions(data,cutoff2) #Predict MFI of eplets File "C:\Users\Anjali Jain\HLA\hlasoftware\Predict_mfi.py", line 282, in mfi_predictions sol=solve_eq(list_of_eq,ep) File "C:\Users\Anjali Jain\HLA\hlasoftware\Predict_mfi.py", line 133, in solve_eq sol=solve((list_of_eq),(list_of_var)) File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\sympy\solvers\solvers.py", line 1096, in solve solution = _solve_system(f, symbols, **flags) File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\sympy\solvers\solvers.py", line 1763, in _solve_system result = solve_linear_system(matrix, *symbols, **flags) File "C:\Users\Anjali Jain\anaconda3\envs\hlaenv\lib\site-packages\sympy\solvers\solvers.py", line 2237, in solve_linear_system … -
Django Python: Convert price to a Stripe amount
I am using Stripe and they request the value in a cent/pence unit rather than rounded to two decimal places. I am using the below, which works great so far, I was just worried about the cast to str() and whether this will cause any unexpected problems? It passes to stripe ok, and saves in my DecimalField ok also. stripeAmount = str(int(round(plan.price, 2) * 100)) -
Decrypt encrypted files in runtime - Django
I'm actually working on a Django project and I do want to try to obfuscate it as much as possible. To do that, I thought of a way to proceed as I would encrypt my python files first before running my project, and then decrypt the encrypted files in memory while the app is running so that the files inside the project directory stay encrypted. But I don't know if it's possible to do or not, and I don't know how to do that so that's why I'm asking you guys if you have an idea of how to proceed to get the expected result. I hope someone will help me through this, I know it's a bit of a pain, but I want to try this. Thanks for the answers! NeroAdvents -
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured:
I am learning on django restframework and when i tried this AUTH_USER_MODEL = 'homepage.Account' in my settings.py I receive this error "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'homepage.Account' that has not been installed i cant makemigrations. this is my settings.py INSTALLED_APPS = [ 'homepage', 'django_tables2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } AUTH_USER_MODEL = 'homepage.Account' this is my filetree my file myproject |_homepage |_ __init__.py |_admin.py |_models.py |_apps.py --> *I also rename the Homepage to homepage* |_views.py |_schoolsite |_ __init__.py |_settings.y |_urls.py |_wsgi.py -
'NoneType' object is not subscriptable. Where is the error? Used Django App with Pipeline
**TypeError: 'NoneType' object is not subscriptable if request['user_type']=='driver' and not Driver.objects.filter(user_id = user.id): TypeError: 'NoneType' object is not subscriptable** '''python from TarFoodApp.models import Customer,Driver def create_user_by_type(backend , user , request, response , *args, **kwargs): if backend.name == 'facebook': avatar = 'http://graph.facebook.com/%s/picture?type=large' % response['id'] if request['user_type'] == 'driver' and not Driver.objects.filter(user_id = user.id): Driver.objects.create(user_id=user.id,avatar=avatar) elif not Customer.objects.filter(user_id=user.id): Customer.objects.create(user_id=user.id, avatar=avatar) ''' the error is most likely in request "['user_type'] == 'driver'" since I remove this code it works I send the request from POSTMAN enter image description here I check by parameter 'user_type' Used Pipeline from https://python-social-auth.readthedocs.io/en/latest/pipeline.html if everything is correct, where can there be a mistake? if you need to throw off more screenshots -
How to stop the influence of other people being simultaneously on a website?
I do a Django survey and everything runs fine if only one person at a time answers it. In one of my functions (when loading one URL), there is a randomizer who randomizes the order of a list. However, if another person answers the survey and opens the url, the randomizer stars working and randomizes the order of the list not only for the second person, but for the first person, too. How can I stop the effect of the second person on the first one? I dont want the first person to get a new order when another one answers the survey (and opens the url) at the same time. def RandomDCE(request): # Create independent Counters for every Choice Set, so people # can use the "Back-Button" in the Browser without increasing the counter # "count" for every website-reload in the function global count, C1, C2, C3, C4, C5, C6, C7, C8 # Randomize the order of Choice Sets for each respondent if request.session['count%d' % (user_id)] == 0: global number_list, number_list2, choiceblock number_list = [2, 3, 4, 5, 6, 7, 8, 9] number_list2 = [10, 11, 12, 13, 14, 15, 16, 17] random.shuffle(number_list) random.shuffle(number_list2) -
Why django_filter not working when i am filtering data?
I am trying to filter data from product table, but when I am submitting the values then it's showing me all the products which are already available on that page, please let me know where I am Mistaking. I want to filter saleprice and totalprice, if products saleprice=500 then those products should be displayed which has price=500 in my database. Here is my `models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True) brand=models.ForeignKey('Brand', related_name='product_brand', on_delete=models.CASCADE, blank=True, null=True) supplement= models.ForeignKey('Supplement', related_name='product_supplement', on_delete=models.CASCADE, blank=True, null=True) totalprice=models.IntegerField() saleprice = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is my views.py file... import django_filters class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Product fields = ['saleprice', 'totalprice'] this is my product page view code, where all products and filters will be display def SubCategorySlugListAPIView(request, subcat_slug): product = Product.objects.all() brands=Brand.objects.all() f = ProductFilter(request.GET, queryset=Product.objects.all()) supplement=Supplement.objects.all() if subcat_slug: subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug) productlist = product.filter(subcategory=subcategory) paginator = Paginator(productlist, 12) page_number = request.GET.get('page') product = paginator.get_page(page_number) template_name = 'mainpage/cat-products.html' context = {'product': product, 'subcategory': subcategory 'brands':brands, 'filter':f} return render(request, template_name, context) here is my cat-products.html file code... <form method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> -
Passing user to wrapped function in django-fsm
I'm using django-fsm library. In some of the methods that are wrapped using @transition() I need the user for logging purposes. I wanted to know if there is someway to pass the user instance to the wrapped function. Example of my code: @transition(field=some_field, source=SOME_SOURCE) def do_something(self): logger.info('Here I need user instance.')