Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'viewpost' with arguments '(1,)' not found. 1 pattern(s) tried: ['int:post\\.id$']. Why am I getting this error?
I am trying to learn django and while making a viewport view, I came up with this error saying Reverse for 'viewpost' with arguments '(1,)' not found. 1 pattern(s) tried: ['int:post\\.id$'] I don't understand what is the mistake I am doing Views.py from django.shortcuts import render from .models import Post # Create your views here. def main(request): return render(request, "blog/index.html", {"Posts":Post.objects.all()}) def viewpost(request): return render(request, "blog/viewpost.html") urls.py from django.urls import path, include from . import views urlpatterns = [ path('',views.main, name = 'main'), path('viewpost/int:pk/', views.viewpost, name = 'viewpost') ] index.html {% extends 'blog/layout.html' %} {% block body %} <h1>Physics Blog</h1> {% for post in Posts %} <fieldset> <a href = "{% url 'viewpost' post.id %}"><h2>{{ post.Title }}</h2></a> <a href = "{% url 'viewpost' post.id %}"><h4>{{ post.Description }}</h4></a> <a href = "{% url 'viewpost' post.id %}"><h6>{{ post.Author }}</h6></a> </fieldset> <br> {% endfor %} {% endblock %} viewpost.html {% extends 'blog/layout.html' %} {% block body %} <h1>{{ post.Title }}</h1> <h1>{{ post.Description }}</h1> <h1>{{ post.Author }}</h1> {% endblock %} -
How to save header request using REST framework
I'm using django 3.0.7 and Django Rest Framework my models.py looks like this: class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) header = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=False, blank=False) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title serializers.py: class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ['title', 'body', 'image', 'date_updated', 'username'] views.py: @api_view(['POST']) def api_create_blog_view(request): blog_post = BlogPost(author=request.user) if request.method == 'POST': serializer = BlogPostSerializer(blog_post, data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I need to save header in "header" database field, i tried to save somehow like this: serializer = BlogPostSerializer(blog_post, data=request.data, header=request.META) but it's didn't work -
Having problem with Django application using Pycharm Professional
I started a django project yesterday using pyCharm professional as text editor. Very thing was working well before I shoutdown my system. But after I restart my system, I started getting this error. Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2020.1.3\plugins\python\helpers\pycharm\django_manage.py", line 59, in <module> run_command() File "C:\Program Files\JetBrains\PyCharm 2020.1.3\plugins\python\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 207, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:/Users/OBUM/PycharmProjects/newproject\manage.py", line 21, in <module> main() File "C:/Users/OBUM/PycharmProjects/newproject\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\OBUM\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 60, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can someone help me please -
The best way to make a chat app using Django Rest Framework and Android client?
Can somebody please tell me what are the ways to develop a chat app using Django Rest Fraework and Android clients? -
django datetimefield in abstract model cannot update "auto_now_add", "auto_now"
I do a code with an abstract model for control create and update documents: class Control(models.Model): ctrl_dt_add = models.DateTimeField(auto_now_add=True, auto_now=False) ctrl_dt_mod = models.DateTimeField(auto_now_add=False, auto_now=True) ctrl_dt_del = models.DateTimeField(default=None,blank=True,null=True) ctrl_user_add = models.OneToOneField( to=User, on_delete=models.DO_NOTHING, default=None, blank=True, null=True, ) ctrl_user_mod = models.OneToOneField( to=User, on_delete=models.DO_NOTHING, default=None, blank=True, null=True, ) ctrl_user_del = models.OneToOneField( to=User, on_delete=models.DO_NOTHING, default=None, blank=True, null=True, ) ctrl_deleted = models.BooleanField(default=False) class Meta: abstract = True And my model: class MyModel(models.Model): _id = models.ObjectIdField() .......... control = models.EmbeddedField( model_container = Control, model_form_class = ControlForm ) objects = models.DjongoManager() class Meta: db_table = 'mymodel' def __str__(self): return self.value My problem is, when i create a new document with this model, control key insert in all datetime keys a null value like this: { "_id" : ObjectId("5f04a3ecc108e12ca4bf5a7f"), ............ "control" : { "ctrl_dt_add" : null, "ctrl_dt_mod" : null, "ctrlwdt_del" : null, "ctrl_user_add_id" : 1, "ctrl_user_mod_id" : null, "ctrl_user_del_id" : null, "ctrl_deleted" : false } } I need to declare values in all the actions with this model. I save it creating a save function in the model. But i would like to do not need that for work with it. def save(self, request=None, *args, **kwargs): if request: self.control.ctrl_user_mod = request.user self.control.ctrl_dt_mod = now() super().save(*args, **kwargs) Thank you!! -
Django track changes to model
I want to add a function in which I want to track and display who modified the below model and at what time.I have tried playing around with the django-simple-history package but failed to implement it. class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing') status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") order_list.html {% for Order in order %} <tbody> <tr> <td>{{ Order.id }}</td> <td><a href="{% url 'accounts:order-history' Order.user.username %}">{{ Order.name }}</a></td> <td>{{ Order.address }}</td> <td>{{ Order.phone }}</td> <td>{{ Order.shipping_method }}</td> <td>{{ Order.language }}</td> <td>{{ Order.box }}</td> <td>{{Order.print_name}}</td> <td>{{Order.date_created}}</td> <td>{{Order.status}}</td> </tr> </tbody> -
Django, annotate with prefetching
I have a Django API of a farm. class Group(models.Model): name = models.CharField() milking = models.BooleanField() sub_groups = models.ForeignKey('self', on_delete=models.DO_NOTHING) herd = models.ForeignKey(on_delete=models.CASCADE, to=Herd) def __str__(self): return self.name class Cow(models.Model): management_id = models.CharField() eid_number = models.CharField(primary_key=True, blank=False) group = models.ForeignKey(Group, on_delete=models.PROTECT) days_in_pasture = models.IntegerField() hours_in_pasture = models.IntegerField() def __str__(self): return self.eid_number I want the queryset in the view to return all the Groups and every group's cows data and annotate the number of days in the pasture for each group (annotate the sum of all the group's cows days in the pasture). So far I've got something like this: class GroupView(ModelViewSet): filter_backends = GROUP_FILTERS def get_queryset(self): query_set = Group.objects.all().prefetch_related('cow').annotate(amount_of_cows=Count('cow__days_in_pasture')) return query_set -
AssertionError: .validate() should return the validated data
I am able to get to the user_queryset of the validate() function of the PasswordChangeSerializer, however I am still receiving this error: assert value is not None, '.validate() should return the validated data'. serializers.py class PasswordChangeSerializer(serializers.ModelSerializer): old_password = serializers.CharField(write_only=True, required=True, max_length=30) new_password = serializers.CharField(write_only=True, required=True, max_length=30) confirm_password = serializers.CharField(write_only=True, required=True, max_length=30) class Meta: model = User fields = ['old_password', 'new_password', 'confirm_password'] def validate(self, data): old_password = data['old_password'] new_password = data['new_password'] confirm_password = data['confirm_password'] user_queryset = User.objects.all() if user_queryset.exists() and user_queryset.count() == 1: user_set = user_queryset.first() if not user_set.check_password(old_password): raise serializers.ValidationError({'old_password': 'Wrong password!'}) if confirm_password != new_password: raise serializers.ValidationError({'password': 'Password must be confirmed correctly!'}) return data def update(self, instance, validated_data): instance.set_password(validated_data['new_password']) instance.save() return instance views.py class PasswordChangeAPIView(APIView): permission_classes = [IsAdminUser] serializer_class = PasswordChangeSerializer def post(self, request, format=None): data = request.data password_ser = PasswordChangeSerializer(data=data) if password_ser.is_valid(): password_ser.save() new_data = password_ser.data return Response(new_data, status=HTTP_201_CREATED) else: return Response({"msg":"invalid user!"}, status=HTTP_400_BAD_REQUEST) -
How to return list or retrive object from single class in django rest?
I'm using 2 different classes to perform get and retrieve operations. class Stock(ListAPIView): serializer_class=StockSerializer queryset=Stock.objects.all() class StockView(RetrieveAPIView): serializer_class = StockSerializer lookup_field = 'slug' def get_queryset(self, slug): collection = Stock.objects.get(slug=slug) return collection def get(self, request, slug): collection = self.get_queryset(slug) serializer = CollectionSerializer(collection) return Response( serializer.data, status=status.HTTP_200_OK ) but I want to perform both operations from a single class,i.e I don't want to write 2 different classes. So how to handle both (GET & RETRIEVE ) from a single class ?. Can we do that using generic APIViews? Thankx in advance -
Is there any way to show a counter of an element in a template in DJANGO?
I'm trying to achieve something: I have a sidebar template that is always in the screen: base.html includes sidebar.html There is a menu in that sidebar and one of the elements is "Pendant consumptions". The thing is that I want some kind of badge with the number of pendant consumptions in that menu element, like this: I know I could achieve this easily with ajax but I think that there must be a better way with Django. The only way I know would be calling the same function (count_consumptions, for example) in all the views but that would be sooo weird. Can you help me guys? -
Don't Show a field drf serializer
Is there a way so that a field of serializer doesn't show in response? I know this way: extra_kwargs = { "field_name": {"write_only": True}, } But problem is someone may change this field with a PUT request. Can we don't show a field and don't accept changing it? -
Why do I get an ordering error in Django for loop template tag?
So I am uploading one article each day directly to my DB. And in the template, I have for loop to get all the data in order (reversed). But then in the page, the order is somehow unordered, as shown in the screenshot below. The red numbers on the left side represent actual order stored in DB. #1 is the oldest one and #12 is the latest one which was posted today. (It's all in Korean) Obviously, article #11 and #12 has to be placed at the top. But somehow it is ordered that way. And here are my codes. First my template {% for item in articles reversed %} <div class="row"> <a href="{{item.url}}" class="all-links" id="article#{{forloop.revcounter}}" target="_blank" rel="noopener noreferrer"> <div class="col"> <span class="title">{{item.title}}</span> <span class="subtitle"> | {{item.subtitle}}</span> </div> </a> </div> {% endfor %} models.py class Articles(models.Model): objects = models.Manager() title = models.CharField(max_length = 100) subtitle = models.CharField(max_length = 100) url = models.URLField(max_length=10000) datePosted = models.DateField(auto_now_add=False) def __str__(self): return self.title What do you think is the problem? Thank you in advance. :) -
How to double check password in serializer of django restframework?
I want to double check password and repeated_password sent from front-end. {"user_data":{"user_name":"jim", "email":"jim@google.com", "password":"ddd","repeat_password":"ssss","role_list":[1,2,3]}} And I add a validator in my serilazer as : # serilazers.py class SUser(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) repeat_password = serializers.CharField(read_only=True) role_list = serializers.SerializerMethodField(read_only=True) def get_name(self, obj): return obj.user_name def get_role_list(self, obj): role_queryset = MRole.objects.filter(group__in=obj.groups.all()) return [ { "role_id": role.id, "role_name": role.name, } for role in role_queryset ] def validate(self, attrs): print(attrs) # OrderedDict([('user_name', 'jim'), ('email', 'jim@163.com'), ('password', 'ddd')]) there's only password here , why repeat_password not appear? if value.get('password') == value.get('repeat_password'): return value raise exceptions.ValidationError('need same passwd') class Meta: model = MUser fields = ['id', 'name', 'user_name', 'email', 'password', 'repeat_password', 'groups', 'is_active', 'role_list'] # models.py class Muser(AbstractUser): user_name = models.CharField(max_length=150,unique=False) email = models.EmailField(unique=True, blank=True) class Meta: db_table = 'User' verbose_name_plural = verbose_name = 'user' to validate data user_data = request.data.get("user_data") serializer_for_user = SUser(data={ **user_data }) serializer_for_user.is_valid(raise_exception=True) But when I try to validate the data, I can't get repeat_password in my validate method of serilazer. How can I do my double check work of pwd? Thanks. -
get parameter from url into hidden parameter of form
I have a CreateView where I want to create a new price for a product. The product detail page has a button to change the price which leads to a new page like ...\partprice\X where X is the id of the product. A product can have multiple prices, which is the reason why I am using a CreateView. Is the only way to grab the part_id from the URL (like here)? In the forms.py: class PPriceFormset(ModelForm): required_css_class = "required" class Meta: model = PPrice fields = ("price", "customer", "date", "part") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout(Row(Column('price'), Column('customer')), Submit('submit', 'Save price', css_class='btn-primary'), Field("date", type="hidden"), Field("part", type="hidden")) I want to add the X from above into the hidden field "part". In the view I already have it: class PPrice(CreateView): model = PPrice template_name ="gap/pprice_update.html" form_class = PPriceFormset success_url = reverse_lazy('part-list') def get_form_kwargs(self, *args, **kwargs): kwargs = super(PPriceCreateView, self).get_form_kwargs(*args, **kwargs) kwargs['part_id'] = self.kwargs.get("part_pk") return kwargs -
How to make an inner join query with same table using Django's ORM
The query to be implemented with ORM is as follows. SELECT t2.* FROM sub_menu AS t1 INNER JOIN sub_menu AS t2 ON (t1.sub_menu_id = t2.parent_sub_menu_id) WHERE t1.sub_menu_id = 1; Not using a raw method, Is it possible to implement with Django's ORM? Thank you. -
using a list from a function in a context in django celery
i have a script (scrapt.py) that i am running frequently with celery beat. the script contains a list that stores what i scrape. how do i use this list in a context? tasks.py import time from celery import shared_task, task from .scrapt import scrape @task def scrape_dev_to(): scrape() return this scrapt.py contains the function import os os.chmod('./chromedriver', 0o755) import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By def scrape(): opt = Options() opt.add_argument("--remote-debugging-port=9222") opt.add_argument("--no-sandbox") opt.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(options=opt, executable_path='/home/maro/Desktop/crypto/chromedriver') driver.get('https://www.ig.com/en/forex/markets-forex') timeout = 10 try: WebDriverWait(driver, timeout).until( EC.visibility_of_element_located( (By.XPATH, "//div[@class='dynamic-table__cell']") ) ) except TimeoutException: print("Struggling to get the page....Have faith in this buggy script!") data = [] while not data: for elm in driver.find_elements(By.CSS_SELECTOR, "span[data-field=V2-F-BID]"): if elm.text and elm.text != '-': # Maybe check on contains digit data.append(elm.text) time.sleep(7) tet =[] while not tet: for em in driver.find_elements(By.CSS_SELECTOR, "span[data-field=OFR]"): if em.text and em.text != '-': # Maybe check on contains digit tet.append(em.text) time.sleep(7) print(data) return data This is the views function, my attempt was to import the scrape function and for a weird reason, i felt i could use the data list … -
Get path from FileInput - Django
I have a model with an array (postgresql) of images urls from my firebase storage, and what I want to do is choose images from the file system with Django's FileInput, get the path of them, and upload them to firebase storage. I can't figure how to get it. Also, I'm not sure if it's the good way of handling images, I'd like to store all the data in the postgressql db managed by Django, but I can't have an array of ImageField. -
How do I compare user uploaded file with another model's file?
I don't mean to ask this question in a spoon feeding way so I urge you to hear me out. I'm trying to build an online judge for scoring solutions to coding problems. I know how the concept would work but I'm having slight problem with implementing it in form of a correct syntax. Concept models.py : There are two models, Question and Solution. Question Model : Has two fields : text field to contain the content of the problem and a FileField for the correct answer.txt file. Answer Model : User field and a FileField along with a ForeignKey question referring to the Question model. views.py : Using class based views. A Create View will have a form valid function that will request the files and then compare the two files using a compare method and return True or False. However, the point where I'm stuck at is the implementation of that last part. I'm not sure how to request the file from the Question model by referencing the foreign key. In all, I would like to know how to compare a user uploaded file with the file present in the Question model I earlier referred to. Answers with … -
Django - Not Found The requested resource was not found on this server
I installed django and virtual env. I created a project(nandiasgarden-project) and an app(pizza). Edited pizza.views under pizza from django.shortcuts import render # Create your views here. def home(request): return render(request, 'pizza/home.html') def order(request): return render(request, 'pizza/order.html') created 2 html files under - pizza/templates/pizza/ home.html <h1>Nandia's Garden</h1> <a href="{% url 'order' %}">Order a Pizza</a> order.html <h1>Order a Pizza</h1> settings as below: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pizza', ] And finally urls as from django.contrib import admin from django.urls import path from pizza import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home name='home'), path('order',views.order name='order'), ] when run server and then fire the website, I get below: Not Found The requested resource was not found on this server How to fix this and what's the resolution ? -
why my celery task is not executing periodically?
I have a celery periodic task but the task run only once. I have specified the task to run every 20 minutes but after I check after 20 minutes it doesn't run. I run the celery worker and celery beat in two different console. tasks.py app = Celery() @app.task def schedule_task(): running_tasks = Task.objects.filter(Q(status=0) | Q(status=1)) print(running_tasks) for task in running_tasks: unique_id = task.unique_id keywords = task.keywords.all() if task.scraping_end_date > timezone.now().date(): settings = { 'spider_count': len(task.targets.all()), 'keywords': keywords, 'scraping_end': task.scraping_end_date, 'unique_id': unique_id, # unique ID for each record for DB 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } for site_url in task.targets.all(): domain = urlparse(site_url.domain).netloc spider_name = domain.replace('.com', '') task = scrapyd.schedule('default', spider_name, settings=settings, url=site_url.domain, domain=domain, keywords=keywords) else: task.status = 2 task.save() settings.py CELERY_BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' app = Celery() app.conf.beat_schedule = { 'crawl_sites': { 'task': 'crawler.tasks.schedule_task', 'schedule': crontab(minute=20), }, } -
How to write below sql query in Django with out raw execution
select date(date_time_recorded) as dt,convert(CONCAT(DATE_FORMAT(prevdatenew, '%H:%i'),'-',DATE_FORMAT(date_time_recorded, '%H:%i')),CHAR) as duration,(eb_kwh-prev_eb_kwh)*1000 as energy from (select date_time_recorded,@prevDateNew as prevdatenew,eb_kwh,@prevEBKWH as prev_eb_kwh, @prevDateNew := date_time_recorded, @prevEBKWH := eb_kwh from database1.energydata_model where (date_time_recorded BETWEEN curdate() and curdate() + interval 1 day and meter_id_id=1) order by id) as tb; -
Get concise error message from Django Rest Framework
I have a serializer that looks like this: class CreatePostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, ) topics = serializers.ListField( child=serializers.CharField( max_length=50, error_messages={'max_length': 'Each tag should be no more than 50 characters.'} ), max_length=3, write_only=True, error_messages={'required': 'You need to add at least one tag to your question.'} ) class Meta: model = Question fields = ('user', 'status', 'topics') When I exceed the amount of characters for max_length I do get the error, however, it comes out in this form: {"topics":{"0":["Each tag should be no more than 50 characters."]}} Is there a way I can make it return something like this instead: {"detail": {["Each tag should be no more than 50 characters."]} -
Django optimizing similar queries
The problem Trying to optimize similar query The case Say, I have a Vacancy Tag model like so: class VacancyTag(models.Model): TYPE_GENERAL = 1 TYPE_EDUCATION_LEVEL = 2 TYPE_LOCATION_CITY = 3 TYPE_LOCATION_PROVINCE = 4 TYPE_CONTRACT_TYPE = 5 TYPE_JOB_TYPE = 6 name = models.CharField(max_length=50) tag_type = models.SmallIntegerField(choices=( (TYPE_GENERAL, 'General'), (TYPE_EDUCATION_LEVEL, 'Education Level'), (TYPE_LOCATION_CITY, 'Location City'), (TYPE_LOCATION_PROVINCE, 'Location Province'), (TYPE_CONTRACT_TYPE, 'Contract Type'), (TYPE_JOB_TYPE, 'Job Type'), ), default=TYPE_GENERAL, db_index=True) On the view, I'm parsing several type of tag record into the context like so: context['tag_education'] = vacancy_services.get_vacancy_tag_by_type(VacancyTag.TYPE_EDUCATION_LEVEL) context['tag_job_type'] = vacancy_services.get_vacancy_tag_by_type(VacancyTag.TYPE_JOB_TYPE) context['tag_contract_type'] = vacancy_services.get_vacancy_tag_by_type(VacancyTag.TYPE_CONTRACT_TYPE) Where vacancy_services.get_vacancy_tag_by_type simply do the query like so: VacancyTag.objects.filter(tag_type=tag_type) Using Django Debug Toolbar, I noticed that those 3 contexts has similar query, because it only differ in the tag_type filter parameter. Searched about it some times and found some answer suggest to query all the tag type I need and then process the data on the view, so I tried something like this: all_tags = vacancy_services.get_vacancy_tag_by_type_in([ VacancyTag.TYPE_EDUCATION_LEVEL, VacancyTag.TYPE_JOB_TYPE, VacancyTag.TYPE_CONTRACT_TYPE, ]) context['education_tags'] = [e for e in all_tags if e.tag_type == VacancyTag.TYPE_EDUCATION_LEVEL] Where vacancy_services.get_vacancy_tag_by_type_in is simply: VacancyTag.objects.filter(tag_type__in=tag_types) However it did not optimize the query as I want. Above code results in a two different queries. (0.006) SELECT "app_vacancy_vacancytag"."id", "app_vacancy_vacancytag"."name", "app_vacancy_vacancytag"."slug", "app_vacancy_vacancytag"."tag_type" FROM "app_vacancy_vacancytag" … -
Django responsibility tracking
For my project, I need to implement a function that tracks which user deleted and updated the order. I'm really confused about how this can be implemented. Can anyone give me some suggestions? -
django form populate multiple identical field form in one submit
I don't want to use django form class as they will not give me much flexibility. I have a form where will random number field in easy request. i am trying to populate the multiple value of forms that appears. this is my models.py class Profile(models.Model): name = models.CharField(max_length=100) photo = models.FileField() and this my form.html <form method="POST" action="{% url 'form' %}"> {% csrf_token %} {% for i in range %} <input type="text" id="name" name="name"><br> <input type="file" id="photo" name="photo"><br><br> {% endfor %} <input type="submit" value="Submit"> </form> You may notice I am rendering field with for loop. that is means, there will be as much field as possible can be appear based on user request. So I want to populate these models. my view looks like def form_view(request): if request.method == 'POST': # Need to puplate the form return render(request, 'form.html', {'range': range(40)}) Can anyone please help me how can i achieve this? i am just struggling to achieve this.