Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show value from choices in react native?
I have a react native app and I am using django for the backend. And I try to display a selected dropdown choice from the django app in the reac native app. Django backend: So I have this part of model: pet_list = models.CharField(max_length=2, choices=PetChoices.choices, default=PetChoices.EMPTY, verbose_name="Huis- en Hobbydierenlijst") description = models.TextField(max_length=1000, blank=True, null=True, verbose_name="Beschrijving") and serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id', 'name',"sort", "sc_name", "uis", "cites", "pet_list", 'description', "feeding", "housing", "care", "literature", 'images', 'category'] def get_animal(self, obj): return obj.get_animal_display() and for react. I am using a accordion: <List.Accordion title="Hobbydierenlijst" expanded={LegislationExpanded} onPress={() => setLegislationExpanded(!LegislationExpanded)}> <Text>{item.pet_list}</Text> </List.Accordion> <List.Accordion title="Beschrijving" expanded={ReviewExpanded} onPress={() => setReviewExpanded(!ReviewExpanded)}> <Text>{item.description}</Text> </List.Accordion> And I am using the Accordion in this component: export const SubCategoryScreen = ({ route, navigation }) => { const [subCatgoryList, setSubCategoryList] = useState([]); const [isLoading, setLoading] = useState(true); const [searchAnimal, setSearchAnimal] = useState(""); //accordion const { toggle, showAccordion } = useContext(ToggleContext); const { accordionItems } = useContext(AccordionItemsContext); const handleSearch = (query) => { setSearchAnimal(query); }; const filteredData = subCatgoryList.filter((item) => item.name.toLowerCase().includes(searchAnimal.toLowerCase()) ); useEffect(() => { fetchSubCategoryData(route.params.subcategories).then((data) => { if (data.animals.length > 0) { setSubCategoryList(data.animals); setLoading(false); } else { setSubCategoryList(data.subcategories); setLoading(false); } }); }, [route]); return ( <SafeArea> {isLoading && ( <LoadingContainer> … -
I have renamed my csrftoken using django's CSRF_COOKIE_NAME, I made similar changes in front end. But X-CSRFToken is missing in req headers
I am using two django instances. Both of them are setting the same csrftoken variable, which is causing conflicts. One of the csrftoken cookie is overwritten by other csrftoken cookie. So I am getting CSRF Failed: CSRF token missing or incorrect.. -
Not always sometime getting the "Forbidden (403) CSRF verification failed. Request aborted." Error in Django web application
I have one login form in Django template as given below:- <form action="{% url 'doLogin' %}" class="form-group" method="post"> {% csrf_token %} <div class="row"> <input type="text" name="username" id="username" class="form__input" placeholder="Username" required> </div> <div class="row"> <!-- <span class="fa fa-lock"></span> --> <input type="password" name="password" id="password" class="form__input" placeholder="Password" required> </div> <div class="row"> <input type="submit" value="Submit" class="btn"> </div> </form> The view Functions are defined as given below:- def loginUser(request): return render(request, 'login_page.html') def doLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: messages.error(request, 'Invalid Login Credentials!! Remember Username and Password are case sensitive!!!') return render(request, 'login_page.html') In settings.py file I have included following parameters with value given below:- ALLOWED_HOSTS = ['gyanbharatimau.co.in'] 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', ] SESSION_EXPIRE_AT_BROWSER_CLOSE = True CSRF_TRUSTED_ORIGINS = ['https://gyanbharatimau.co.in'] Now its working fine in development as well as in production environment. But sometime in production environment (Not always I guess 2 or 3 times daily) login attempt is failing with following error message:- Forbidden (403) > CSRF verification failed. Request aborted. When i enabled the debug in production i am getting following details:- Help Reason given for failure: CSRF token … -
Why django cant find a photo?
i wrote in html file, django cant find a photo this is a media files structure class Recipe(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", default=None, verbose_name="Фото") ingredients = models.TextField(null=True, blank=True) directions = models.TextField(null=True, blank=True) def __str__(self): return self.title maybe problem in models On site i see img icom instead full image -
Django Validators not working in shell command
Django Validators not working in shell command, it works just on Django Forms and Django Admin but not in shell commands. I have this: Validator def validate_cuit(value): """ Must be exactly 11 numeric characters """ if len(value) != 11: raise CuitValidationException('CUIT should have 11 characters') if not value.isdigit(): raise CuitValidationException('CUIT should only contain numeric characters') return value Exception class CuitValidationException(ValidationError): pass Model class Empresa(models.Model): name = models.CharField(max_length=120, validators=[validate_name]) cuit = models.CharField(max_length=11, validators=[validate_cuit]) If I do this, I get no error e = Empresa.objects.create(name="Testing Case", cuit='1') The only way I found to solve this is by working on the save method: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = validate_name(self.name) self.cuit = validate_cuit(self.cuit) return super().save(force_insert, force_update, using, update_fields) But I'm sure it shouldn't be neccesary, can you help me with this? -
Dynamically modifying fields in django Rest Framework
Okay so I have two classes one is Book and the other one is Category. Book and Category are linked by a foreign key named category which is a Book field. See the code class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) def __str__(self): return self.category class Book(models.Model): book_title = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.book_title And below are the serializer classes class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class CategorySerializer(DynamicFieldsModelSerializer): class Meta: model = Category # only show the category field fields = ['category'] class BookSerializer(serializers.ModelSerializer): # this will show the category data which is related to this Book category = CategorySerializer() class Meta: model = Book fields = '__all__' And now I want that when I get the data of the book using @api_view, I should … -
AWS update TLS version from tls1.1 to tls1.2 in django using SES smtp
Recently I have received an email from AWS that has identified few endpoints using AWS SES for sending mails. We have identified TLS 1.0 or TLS 1.1 connections to AWS APIs from your account that must be updated for you to maintain AWS connectivity. Please update your client software as soon as possible to use TLS 1.2 or higher to avoid an availability impact. We recommend considering the time needed to verify your changes in a staging environment before introducing them into production... Now AWS has only provided me ip address (which is my server's IP), message Id, and tls version. I have multiple projects running on that server and using the same SES to send mails. Region | Event | Message ID | Source IP | TLS Version <region-of-my-aws-account> | SMTP Message | <smtp-message-id> | <ip-address> | TLSv1 | Im still unsure which ones are using which TLS version. I want to pinpoint my project which is using TLS 1.1/1.0 Is there a way maybe I can print TLS version along in my log files while sending mail? my settings are as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = '<AWS SMTP endpoint>' EMAIL_HOST_USER = os.getenv('AWS_SES_SMTP_USERNAME') EMAIL_HOST_PASSWORD = os.getenv('AWS_SES_SMTP_PASSWORD') EMAIL_USE_TLS = … -
Language selection navbar
Below is my code that works pretty fine and it changes the language of my website, but I want the navbar to change the link 'language' to 'russian' or 'spanish' and etc everytime the user chooses the language. I mean if the user chooses english, in navbar there should be 'english', not just 'language'. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Languages </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <li> <a class="dropdown-item" href="/{{ lang.code }}/"> {{ lang.name_local }} </a> </li> {% endfor %} </ul> </li> -
Passing kwargs from Resource to widget
I've been working with django import_export and I wanted to pass kwargs from the resource to the clean field of my custom widget validator. how can i do that here's my code resources.py class UserResource(ModelResource): identifier = Field( column_name="identifier", attribute="identifier", widget=RegexWidget(), ) class Meta: model=User widgets.py class RegexWidget(CharWidget): def clean(self, value, row=None, **kwargs): regex = kwargs.get("regex", None) ... In the test I've tries something like the following UserResource.import_data(dataset, regex=r"U\{4}d\Z") but the kwargs from the clean method of the widget is {} -
EC2 instance and EC2 hosted sql is crashing
I have a copied one django project and deleted the mirgation files other than init.py and deployed that to a new EC2 instance with new url.But whenever i am performing any sql operation like insertion,updation my ec2 instance is getting crashed after sometime of getting this error.Even i couldnt open the admin page med_new/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner wargs) med_new/venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection connect(**conn_params) med_new/venv/lib/python3.10/site-packages/pymysql/connections.py", line 353, in init med_new/venv/lib/python3.10/site-packages/pymysql/connections.py", line 664, in connect lError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)") After this the ec2 is crashing always.What fix i have to do for that I want the connection between the sql and ec2 to be stable -
Django model list from ManyToManyField other model
I'm looking into creating some kind of dashboard to do some easy server admin tasks online. As much as possible stored in the database, so I could configure there tasks online instead of programming them. What I'm trying to achieve in my data model is the following: I have a model for Applications: class Application(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name In my Server model I have ManyToManyField mapping to my Applications model so I could select one or more applications which run on this server: from applications.models import Application class Server(models.Model): name = models.CharField(max_length=20,blank=False, null=False) application = models.ManyToManyField(Application, blank=True, related_name='applications') ip = models.CharField(max_length=15, blank=True) dns = models.CharField(max_length=100, blank=True) To support multiple server types (web server, database), I have a Servertype model: from applications.models import Application class Servertype(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) type = models.CharField(max_length=20, blank=False, null=False) order = models.IntegerField(null=False) def __str__(self): return "%s - %s" % (self.application, self.type) class Meta: ordering = ["application", "order"] Now I want to map these last 2 together, so I could link up Server and Servertype, but limit the Servertype choices to whatever is chosen as Application in Server, and is defined for this Application in Servertype. But I'm not fully sure how … -
How to receive and send form data in Django to Javascript?
I'm trying to make Django receive data from a form, then process it and output it into JavaScript. I've tried to follow Django's tutorial on making a form and it seems to work, however when I click the submit button I simply get transfered to http://127.0.0.1:8000/your-name/. I suppose i have to do something in views but I'm not entirely sure what exactly. How do I process the data and send it to JS? HTML <form action="/your-name/" method="post"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"> Views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import NameForm def home(request): return render(request, 'index.html') def get_name(request): # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): print("yesss") # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect("/thanks/") # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, "index.html", {"form": form}) Forms.py from django import forms class NameForm(forms.Form): … -
cookiecutter-django template django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist
I generated a django app using the cookiecutter template and got an error that celery_beat_periodictask does not exist. I ran the following docker-compose command: docker-compose -f local.yml up -d --build Checked the logs for individual services (services in the docker-compose file)your text using: docker-compose -f local.yml logs I got the following error: File "/usr/local/lib/python3.11/site-packages/psycopg/cursor.py", line 723, in execute local_celerybeat | raise ex.with_traceback(None) local_celerybeat | [2023-07-26 11:46:23,580: WARNING/SpawnProcess-1] django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist local_celerybeat | LINE 1: ...ango_celery_beat_periodictask"."description" FROM "django_ce I decided to add the dynamically generated docker IP address to the settings.local file and this error disappears. Is there anyway to fix this issue before running the docker-compose command? -
Why Django migrate command not able to create tables in database for specific app
I've a model named Attendance and it contain following migrations applied in postgresql db. attendance [X] 0001_initial [X] 0002_delete_leave [X] 0003_alter_holiday_options_alter_shift_options [X] 0004_delete_holiday_alter_shift_holidays [X] 0005_delete_shift [X] 0006_initial [X] 0007_alter_leave_options [X] 0008_alter_leave_comment_alter_leave_is_regularized [X] 0009_attendance [X] 0010_alter_attendance_options_attendance_created_at_and_more [X] 0011_attendance_status [X] 0012_attendance_is_regularized [X] 0013_alter_attendance_is_regularized [X] 0014_remove_attendance_date_attendance_start_date_and_more [X] 0015_attendance_end_date [X] 0016_alter_attendance_end_date [X] 0017_alter_attendance_end_date_and_more [X] 0018_leavetype_remove_leave_half_day_and_more [X] 0019_leave_leave_type when I run python manage.py migrate with or without app label it does not create tables in db. I've not set managed=False and tried to delete all migrations from django_migrations table but no luck. -
Why doesn't Django set the cookie when the view is called
I am trying to set and unset a Django cookie based on a form with a checkbox. When the checkbox is checked I would like the cookie to be set. Passing the value of the checkbox to the view is working correctly, but setting and unsetting the cookie is not. This is the view: def filter(request): tasks = list() if request.POST.get('today') == 'yes': tasks.extend(Task.objects(when='today')) print('get tasks today') response = render(request, 'index.html', {'tasks': tasks}) if request.POST.get('today') == 'yes': response.set_cookie('today', 'yes') print('set cookie today') else: response.set_cookie('today', 'no') print('cookie not set today') return response Whether or not to set the cookie is determined by this code: {{request.COOKIES.today}} <form action="filter" method="POST"> {% csrf_token %} <input type="checkbox" name="today" value="yes" {% if request.COOKIES.today == 'yes' %}checked{% endif %}> Today</div> <input type="submit" value="Show" class="btn btn-warning col-12 btn-sm"/> </form> In my template I use {{request.COOKIES.today}} to check the value of the cookie. What's happening is strange. If I click the checkbox the cookie is not set, as I expect it to be and the checkbox is not checked when the page reloads. But if I select the checkbox again, then the cookie is set and the checkbox is selected. Am I making a mistake somewhere, or missing something. … -
Design for a Contest-Oriented Platform - Handling Shared Kernel
I'm creating a HackTheBox-like platform with Django using Domain-Driven Design. It supports both individual and enterprise users who can solve challenges and participate in contests. Enterprise members also have exclusive challenges and contests. My system is divided into four Django apps: Users, Enterprises, Challenges, and Contests, each handling related tasks. I plan to treat challenges as a shared kernel accessed by both Users and Enterprises apps. However, I'm uncertain how a user can retrieve and solve a challenge within this design. Am I structuring these Django apps effectively for my requirements? How can I manage a shared kernel for challenges to let users retrieve and solve them? Any key endpoints missing? Any advice is appreciated. Thanks! -
solr search in Django application
There are questions in database. Solr search is giving results, but I want the ranking of the questions based on the text I'm searching. But search giving results based on id's of the questions. In solr.xml file I have the schema based on that indexing is happening. What should i do the xml file to get the search results based on ranking. -
How to display filtered data in serializer's source attribute Django Rest Framework
I've added an additional action to my ModelViewSet as below. I have a manager function which it's name is related_interests and it should filter the user interests. I put source attribute to my serializer to get filtered interests however, I'm getting all of them in my response. class MyModelViewSet( viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin ): """ModelViewSet with create, list, retrieve and custom_action operations""" queryset = MyModel.objects.all() serializer_class = serializers.MyModelSerializer @action(detail=False, methods=['post']) def custom_action(self, request): queryset = MyModel.objects.related_interests() serializer = self.serializer_class(queryset, many=True) return responses.http_ok_with_dict(serializer.data) And here is my serializer; class UserWithInterestSerializer(serializers.ModelSerializer): licenses = InterestSerializer(read_only=True, source="interest_set", many=True) class Meta: model = User fields = "__all__" class MyModelSerializer(serializers.ModelSerializer): user = UserWithInterestSerializer(read_only=True) class Meta: model = MyModel fields = ["user"] How can I fix this issue? Thanks! -
How to run async tests in django?
I use async django views and async test cases accordingly. When I run tests separately by one test cases it works okay, but when I run a batch of tests I get error: RuntimeError: Task <Task pending name='Task-139' coro=<AsyncToSync.main_wrap() running at /opt/venv/lib/python3.11/site-packages/asgiref/sync.py:353> cb=[_run_until_complete_cb() at /usr/local/lib/python3.11/asyncio/base_events.py:180]> got Future attached to a different loop According to django docs "Django will automatically detect any async def tests and wrap them so they run in their own event loop." So I guess there is some loops conflict? Maybe anyone knows how to fix this error or any patch how to run many async tests in django? -
Django multiuser
this it the review model on my movie project class Parent(models.Model): title=models.CharField(max_length=50,blank=True,null=True) # slug=models.SlugField(max_length=50,unique=True,default=title) user=models.ForeignKey(User,on_delete=models.CASCADE,default='user') movie=models.ForeignKey(Movie,on_delete=models.CASCADE) date=models.DateField(auto_now_add=True) score=models.IntegerField(blank=True,null=True) review=models.TextField(max_length=5000,blank=True,null=True) class Meta: abstract=True def __str__(self): return self.title class Audience_Review(Parent): pass And this is my syntax for displaying the movie review. def view_movie(request,mslug): status='' user=request.user movie=Movie.objects.get(slug=mslug) watchlist=Watchlist.objects.all() reviews=Audience_Review.objects.filter(movie=movie) return render(request,'moviesingle.html',{'mov':movie,'watchlist':watchlist,'review':reviews}) What changes i should make for changing this as a multi user program. Example: if i post a review from user A and then logged on to user B, the review is showing as written by B (the current logged in user), I need to show it as written by A (the user who post the review) even when logged as another user.I tried to filter the syntax by user, but then it wont show while logged as another user. Also need to take personal score from each user and calculate the average score by calculating all ratings from different users for the same movie. -
I've got problems pipenv installing django
pipenv install django get erreor OSError: [WinError 1920] Systemet kan ikke få adgang til filen(System can't acces): 'C:\Users\Bruger\AppData\Local\Microsoft\WindowsApps\python.exe\Scripts. I have tryed to move Python from C: to D:, tryed to make a path to pipenv, turned of virusprogram.This is an image of windows app folder (https://i.stack.imgur.com/tOwYn.png) -
Page not found (404) error in my django site
i have created a school dashboard system site..here i have given some usrls most of them are working fine just two of them are not working. These are my urls urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_view,name=''), path('adminclick', views.adminclick_view), path('teacherclick', views.teacherclick_view), path('studentclick', views.studentclick_view), path('adminsignup', views.admin_signup_view), path('studentsignup', views.student_signup_view,name='studentsignup'), path('teachersignup', views.teacher_signup_view), path('adminlogin', LoginView.as_view(template_name='school/adminlogin.html')), path('studentlogin', LoginView.as_view(template_name='school/studentlogin.html')), path('teacherlogin', LoginView.as_view(template_name='school/teacherlogin.html')), path('afterlogin', views.afterlogin_view,name='afterlogin'), path('logout', LogoutView.as_view(template_name='school/index.html'),name='logout'), path('admin-dashboard', views.admin_dashboard_view,name='admin-dashboard'), path('admin-teacher', views.admin_teacher_view,name='admin-teacher'), path('admin-add-teacher', views.admin_add_teacher_view,name='admin-add-teacher'), path('admin-view-teacher', views.admin_view_teacher_view,name='admin-view-teacher'), path('admin-approve-teacher', views.admin_approve_teacher_view,name='admin-approve-teacher'), path('approve-teacher/<int:pk>', views.approve_teacher_view,name='approve-teacher'), path('delete-teacher/<int:pk>', views.delete_teacher_view,name='delete-teacher'), path('delete-teacher-from-school/<int:pk>', views.delete_teacher_from_school_view,name='delete-teacher-from-school'), path('update-teacher/<int:pk>', views.update_teacher_view,name='update-teacher'), path('admin-view-teacher-salary', views.admin_view_teacher_salary_view,name='admin-view-teacher-salary'), path('admin-student', views.admin_student_view,name='admin-student'), path('admin-add-student', views.admin_add_student_view,name='admin-add-student'), path('admin-view-student', views.admin_view_student_view,name='admin-view-student'), path('delete-student-from-school/<int:pk>', views.delete_student_from_school_view,name='delete-student-from-school'), path('delete-student/<int:pk>', views.delete_student_view,name='delete-student'), path('update-student/<int:pk>', views.update_student_view,name='update-student'), path('admin-approve-student', views.admin_approve_student_view,name='admin-approve-student'), path('approve-student/<int:pk>', views.approve_student_view,name='approve-student'), path('admin-view-student-fee', views.admin_view_student_fee_view,name='admin-view-student-fee'), path('admin-attendance', views.admin_attendance_view,name='admin-attendance'), path('admin-take-attendance/<str:cl>', views.admin_take_attendance_view,name='admin-take-attendance'), path('admin-view-attendance/<str:cl>', views.admin_view_attendance_view,name='admin-view-attendance'), path('admin-fee', views.admin_fee_view,name='admin-fee'), path('admin-view-fee/<str:cl>', views.admin_view_fee_view,name='admin-view-fee'), path('admin-notice', views.admin_notice_view,name='admin-notice'), path('teacher-dashboard', views.teacher_dashboard_view,name='teacher-dashboard'), path('teacher-attendance', views.teacher_attendance_view,name='teacher-attendance'), path('teacher-take-attendance/<str:cl>', views.teacher_take_attendance_view,name='teacher-take-attendance'), path('teacher-view-attendance/<str:cl>', views.teacher_view_attendance_view,name='teacher-view-attendance'), path('teacher-notice', views.teacher_notice_view,name='teacher-notice'), path('student-dashboard', views.student_dashboard_view,name='student-dashboard'), path('student-attendance', views.student_attendance_view,name='student-attendance'), path('aboutus', views.aboutus_view), path('contactus', views.contactus_view), ] These two urls are making errors- path('admin-dashboard', views.admin_dashboard_view,name='admin-dashboard'), path('admin-teacher', views.admin_teacher_view,name='admin-teacher'), this is the error m getting- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin-dashboard/ -
How to create the function and pass it into the context using extra_context in the template [closed]
I'm trying to do what this Article says, and the answer says to simply create a function to do this. How would I go about that? I have tried creating a function that gets the requests from the form and getting the foreign key with the same id but I can not seem to make it work. Thanks(: -
How to Index over Filtered set of a model through elasticsearch_dsl 's Persistence API
This is my code documents.py code class Blog(Document): title = fields.TextField() date_posted = fields.DateField() class Index: name = "blog_index" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Django: model = Blog fields = ['title','date_posted'] This is my models.py code class Blog(models.Model): """ Blog Model fields are defined here """ title = models.CharField(max_length=255, null=True) date_posted = models.DateField(blank=True, null=True) But I don't want to populate all of my objects of Blog, I only want to populate those objects who are getting passed with these filter example filter = Blog.objects.filter(title__isnull=False).distinct() -
how to make changing link upload_to imagefield in django
in my product model there is a category field, it refers to another table, in the category table there is a title field, I would like each image to be saved in a folder with the name of the corresponding category__title class ProductImage(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='...') product = models.ForeignKey(Product, on_delete=models.CASCADE) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(models.Model): title = models.CharField(max_length=150, verbose_name='title', unique=True)