Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model filters method finder
I would like to know if there is any way to do dynamically regroup a model by all available columns. models.py class ProductionPlan(models.Model): status_choices = ( ('READY TO START', 'Ready To Start'), ('IN PROGRESS', 'In Progress'), ('PROGRESS STOPPED', 'Progress Stopped'), ('MAINTENANCE STOPPED', 'Maintenance Stopped'), ('QUALITY STOPPED', 'Quality Stopped'), ) id = models.CharField(max_length=15, primary_key=True) first_start_date = models.DateTimeField(null=True, blank=True, default=None) bills_of_material = models.ForeignKey(BillsOfMaterial, on_delete=models.CASCADE) quantity = models.IntegerField() scheduled_date = models.DateTimeField() real_duration = models.DurationField() expected_duration = models.DurationField(default=None) start_date = models.DateTimeField(default=None, null=True) status = models.CharField(max_length=50, default='Ready To Start', choices=status_choices) now if i want to filter model i would use ProductionPlan.objects.filter(status__icontains = '') Then my question is this method of searching status__icontains or any other (start_date_contains, expected_duration__startswith) how can i get these methods. my end point is something like this: def get_methods_for_filter(model): do something here return ((**start_date_contains**, **expected_duration__startswith**) -
Django Override the Default success_url in contrib.auth.views
I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function. Now I need to change all the class details of the success_url, for instance from: reverse_lazy('login') to: reverse_lazy('accounts:login') but overwriting the original urls.py is not a good practice. I'm a python beginner and struggling with this problem already for a month.. how can I achieve this? What I attemptd was making subclasses in my views inherent from each of the class in django.contrib.auth.views. I even tried putting try/except method with except 'NoReverseMatch:' but the function itself did not exist. -
Does django-cachalot lib support Django version 4.0?
Currently, the new django.core.cache.backends.redis.RedisCache cache backend provides built-in support for caching with Redis and I used it in my application. I've used the latest version django-cachalot and get this warning: Cache backend 'django.core.cache.backends.redis.RedisCache' is not supported by django-cachalot. It's so weird! Please help me to clear my question. I'm using Python 3.9, and MySQL 5.7. I applied the latest version of django-cachalot into Django app version 4.0.8, but get this warning: Cache backend 'django.core.cache.backends.redis.RedisCache' is not supported by django-cachalot -
How to confirm from user if he wants to leave the page while filling form?
I am creating a form where user can fill data. Based upon the user's input and selected options I'm showing the next data to fill using js which works totally fine. Now what I want is if the user presses the back or exit button accidentally. I want to confirm with the user if he really wants to exit from the current page. -
How to write an image attribute file in django (The 'image' attribute has no file associated with it)
I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says " The 'image' attribute has no file associated with it. This my code for the model class article(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(null=True, blank=True, upload_to='static/media/article') date = models.DateTimeField(default=timezone.now) def __str__ (self): return self.title def get_absolute_url(self): return reverse('article-detail', kwargs= {'pk':self.pk}) This is my views code class ArticleCreateView(LoginRequiredMixin, CreateView): model = article fields= ['title', 'content', 'image'] def ArticleCreateView(request): if request.method == "POST": form = ArticleForm(request.POST, request.FILES) if form.is_valid(): article = form.save(commit=False) article.author = request.user.id article.save() return HttpResponse this is the blog template code {% extends "agri_tourism/base.html" %} {% load crispy_forms_tags %} {% block content %} <section class="flex-container"> <div> {% for article in articles %} <article class="media content-section"> {% load static %} <div class="media-body"> <div style="text-decoration:none; display: inline-block;" class="article-metadata"> <img class="rounded-circle article-img" src="{{user.profile.image.url}}"> <a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a> <small class="article-date">{{ article.date|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="">{{ article.title }}</a></h2> <p class="article-content">{{ article.content }}</p> <img class="image-content" id="image-el" src = … -
Gunicorn ModuleNotFound : No module named 'core' when Deployment Django
I try to deployment my apps. So when i try to run this command gunicorn -c conf/gunicorn_config.py core.wsgi Error : ModuleNotFound : No module named 'core' This is my directory home/uletin --- conf --------- ... --------- gunicorn_config.py --- env --- graduates ------... ------core ------------ ... ------------ settings.py ------------ wsgi.py ------------ ... ------manage.py ------static in gunicorn_config.py like this command = '/home/uletin/env/bin/gunicorn' pythonpath = 'home/uletin/graduates' bind = '165.22.98.56:8000' workers = 3 -
AttributeError: 'dict' object has no attribute 'id'
I'm trying to access the dictonary inside the jsonfield serializer "assigned_facilities". But i'm receiving the following error: AttributeError: 'dict' object has no attribute 'facility_id' I'm basically trying to create a "LeadFacilityAssign" object for each item inside my json so i can have a "LeadFacilityAssign" object for each facility i want to add to a lead. json { "facilities": [{ "facility_id": "1", "datetime": "2018-12-19 09:26:03.478039" }, { "facility_id": "1", "datetime": "2018-12-19 09:26:03.478039" } ] } serializers.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True) class Meta: model = Lead fields = ( "id", "first_name", "last_name", "PrimaryAddress", "City", "PostalCode", "RegionOrState", "pc_email", "Cell", "secphone", "client_cell", "client_secphone", "birthday", "curr_client_address", "curr_client_city", "curr_client_zip", "ideal_address", "ideal_city", "ideal_zip", "ideal_state", "budget", "client_email", "client_first_name", "client_last_name", "lead_status", "created_at", "agent", "is_owner", "relationship", "marital_status", "gender", "pets", "assigned_facilities", ) read_only_fields = ("id", "created_at", "agent", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") instance = Lead.objects.create(**validated_data) for facilities in assigned_facilities: instance.leadfacility.create(assigned_facilities_id=assigned_facilities.facility_id,datetime=assigned_facilities.datetime) return instance models.py class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility') lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility') … -
How to add a XML file to postgreSQL table using python in Django
I have initially connected to postgreSQL in settings.py and added my app in the INSTALLED_APPS. Then I created my table in models.py models.py: class Activity(models.Model): date = models.DateField(default=None) time = models.TimeField(default=None) function = models.CharField(max_length=10, default = None) status = models.CharField(max_length=10,default=None, blank=True, null=True) logfilename = models.CharField(max_length=128) after that I migrated my table and the table was created in postgreSQL. currently I added the XML data to postgreSQL Table by adding a code in the command shell command shell code: from oapp.models import Activity import os import xml.etree.ElementTree as ET from xmldiff import main, formatting file_1 = 'sample.xml' def xmlparse(): data = ET.parse(file_1) root = data.findall("record") for i in root: date = i.find('date').text time = i.find('time').text function = i.find('function').text status = i.find('status').text logfilename = i.find('logfilename').text x = Activity.objects.create(date=date, time=time, function=function, status=status, logfilename=logfilename) x.save xmlparse() But I wanted to run it as a python code. When I run it as python code it shows module not found error. It only works in command shell. What I want is to run t as a python code. error when run as python: Traceback (most recent call last): File "c:\Users\ostin\Desktop\nohope\projectq\qapp\qcode.py", line 1, in <module> from qapp.models import newrecord ModuleNotFoundError: No module named 'qapp' -
Django Group By like in SQL
I have following model class Product(models.Model): name = models.CharField(max_length=20) class FAQ(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) title = models.CharField(max_length=500) description = models.TextField(max_length=2000) order = models.IntegerField(validators=[MinValueValidator(0)], default=0) column = models.IntegerField(validators=[MinValueValidator(0)], default=0) def __str__(self): return f'{self.product.name}->{self.title}->{self.column}' class Meta: ordering = ('column', 'order') I want to group all result where column is same i.e IF column have value 1 in my model all data is enclosed inside one list I tried looking for annotate but could not figure out how i use in my code expected response [ [## this have column value 1 { "product": 1, "title": "Test 1", "description": "Description 1", "order": 0, }, { "product": 1, "title": "Test 2", "description": "Description 2", "order": 1, } ], [ ## this have column value 2 { "product": 1, "title": "Test3", "description": "Description 3", "order": 0, }, { "product": 1, "title": "Test 4", "description": "Description 4", "order": 1, } ] ] Here is my overall code any class FAQView(APIView): def list(self, request): queryset = FAQ.objects.values('product', 'title', 'description', 'order').annotate("?") serializer = FAQSerializer(queryset, many=True) return Response(serializer.data) -
Access blocked: django-oauth’s request is invalid
Sign in with Google Access blocked: django-oauth's request is invalid a avinash.sharma@technogetic.com You can't sign in because django-oauth sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error If you are a developer of django-oauth, see error details. Error 400: redirect_uri_mismatch i am trying to use google oauth(social-auth) in django.i followed these steps given in this link="https://www.section.io/engineering-education/django-google-oauth/" but keep getting this error in browser.please help -
`SynchronousOnlyOperation` error while trying to run Playwright automation triggered django admin action
This is the error: SynchronousOnlyOperation at /admin/app/modelA/ You cannot call this from an async context - use a thread or sync_to_async. What I'm trying to do is: I have an action in django-admin that intends to run an automated task with Playwright. The action in admin.py looks like this: @admin.action(description="Do task") def run_task(modeladmin, request, queryset): for obj in queryset: task = Task(obj) task.run() And the Task class looks like this: class Task: def __init__(self, task: Task) -> None: self.task = task def run(self): with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page() page.go_to("www.google.com") # DO SOME STUFF browser.close() And when I run the action the error shows as soon as chromium gets ready. Thank you beforehand. I expect it to do the stuff without running at least get the title of the page. I tried using sync_to_async as these docs suggest, implemented it in two ways (which I believe are wrong) First way I tried: Is by trying to use sync async in the admin.py file when the function Task.run is called: @admin.action(description="Do task") def run_test(modeladmin, request, queryset): for obj in queryset: task = Task(obj) sync_to_async(task.run, thread_sensitive=True) It didn't work 2. Second way I tried: Is by adding the … -
what are the different ways to login and authenticate user (like using OAuth2 ,jwt ,okta ) in Django application
I want to know what are the different ways by which live applications built on Django framework Authenticate users while login. what all ways are used apart from Django inbuilt authentication for user login . I found all these tutorials using Django's inbuilt authentication from Django.contrib library. I want to know what methods are used in real world live Django applications. -
Django Q and reduce doesn`t work as expected
I'm newly in Django. Don't understand where I'm going wrong. When I use this code it will work as expected. def filter_qs(self, qs): if self.filter == {}: return qs else: q_objects = [models.Q()] if self.filter['vendor']: q_objects.append(Q(vendor__in=self.filter['vendor'])) if self.filter['start_date']: q_objects.append(Q(date__gte=self.filter['start_date'])) if self.filter['end_date']: q_objects.append(Q(date__lte=self.filter['end_date'])) if self.filter['product']: product_list = (Q(product_type__contains=product) for product in self.filter['product']) if product_list: q_objects.append(reduce(operator.or_, product_list)) if len(q_objects) > 1: qs = qs.filter(reduce(operator.and_, q_objects)) However, when I use the query filter, filter_query = Result.objects.filter( Q(vendor__in=vendor) if vendor else Q() & Q(date__gte=start_date) if start_date else Q() & Q(date__lte=end_date) if end_date else Q() & Q(reduce(operator.or_, (Q(product_type__contains=product) for product in products)))) this part of the query does not work in filter_query: Q(reduce(operator.or_, (Q(product_type__contains=product) for product in products))) I don't get a query filter per product. Don't understand where I'm going wrong. Look for the query to work properly. -
hello can I make several genlist on the same model with different forms [closed]
I create a model and i do a genlist,gencreate,genupdate .... and now i need another genlist on the same model. I do it but on the menu the first genlist is always affiched. What can i do to display the second genlist or the second forms on the edit mode. -
NoReverseMatch at /question/1 Reverse for 'upvote' with arguments '('',)' not found. 1 pattern(s) tried: ['answers/(?P<id>[0-9]+)/upvote\\Z']
Can some one help me,Iam trying to get a details view page and i got this error No reverse match.Im sharing my view page,urls, and models down here .please find a solution guys!!!! https://hastebin.com/ogogofawag.typescript i tried to change the url names and didnt get rid of that error the url link is ` <a href="{%url 'upvote' ans.id %}">upvote<span>{{ans.upvote.all.count}}</span></a> ` -
How to customise task context (process_data cards) in django-viewflow
What I want I'm building an approval workflow using django-viewflow and django-material. The individual tasks are rendered as a main form with context on a very narrow column on the right hand side. I want to change the layout so that the task context (the detail views of all involved model instances) is better readable to the user, and also customise which fields are shown (eg. exclude a user's password hash). Where I'm stuck Is there a way to override which data is available as process_data short of overriding viewflow's get_model_display_data and include_process_data? E.g. I'd like to have the related instance's __str__() as title. Does viewflow have any canonical way to provide individual detail card templates? My alternative would be to completely re-work the contents of the process_data sidebar using context['process'] as the central instance, but that would tie the templates to the data model. I'd be grateful on any pointers here. What I've tried I'm overriding/extending the viewflow templates. As per templatetag include_process_data, the template process_data.html supplies the column of model instance detail cards, fed by data from get_model_display_data. It's e.g. easy to override process_data.html to change the cards into a MaterializeCSS collapsible list: {% load i18n viewflow material_frontend … -
Date Converter app in django views.py is running same time, i would like post method to run after user click only
I have created views.py for BS to AD date converter but my views will run only the UserInputForm() get loaded first, i have to comment post method then input data from frontend then again uncomment my post method views to get converted data. Please help me to fix by running first UserInputForm() then after click need to go thought the post method views.py from django.shortcuts import render from pyBSDate import convert_BS_to_AD from . forms import UserInputForms # Create your views here. def neview(request): # todays's date fm = UserInputForms() if request.method == 'POST': data = request.POST.get('date') up = data.replace('-',',') y = up[0:4] m = up[6:7] d = up[8:10] ad_data = convert_BS_to_AD(y, m, d) return render(request, 'NEC/NepaliToEnglish.html', {'fmr': fm, 'dt': ad_data}) html page {% extends 'NEC/base.html' %} {% block title %} Mid-West University Date Conveter App {% endblock title %} {% block content %} <h1>Welcome to Mid-West University Date Converter Application</h1> <h1>BS to AD Date Converter YYYY-MM-DD</h1> <form action="" method="post"> {% csrf_token %} {{fmr}} <br /> <br /> <input type="submit" /> </form> {{dt}} {% endblock content %} -
Subquery a Parent Model returning Error in Django
class Customer(models.Model): pass class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') total_amount = models.DecimalField() As you can see, a customer can have many orders. What I want to know, how much amount one customer has spent so far. qs = Customer.objects.get(pk=OuterRef('customer').orders.all().aggregate(total=Sum('total_amount)) Order.objects.annotate(customer_total=Subquery(qs.values('total')[:1])) But I am getting error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. My question is, can we Subquery a parent Model ? or i am doing something wrong ? -
Is it possible for Django to sum non numetric field?
I have learned we can sum all(or filtered) columns like price from this question. ItemPrice.objects.aggregate(Sum('price')) But is it possible for Django to sum non numetric field's length, such as CharField or JSONField? A pseudocode is like following. User.objects.aggregate(Sum(len('username'))) -
Please configure the inventory detail for item
I am trying to create an item fulfillment for an item , the on hand quantity on item fulfillment record is showing as X for that item at that location , but when it says configure inventory details for line X i am not able to see available under the status column I tried creating a saved search and getting the item's on hand greater than zero and location in the results but got as empty I also checked previous item fulfillments for that item they are created successfully with on hand quantity but now i am getting error as - Please configure the inventory detail for item -
Should i use different servers for backend and api provider?
I'm building an app in which I'm using react as frontend. And now I need to provide data from APIs, now my question is should I create a new server for APIs? Can anybody suggest to me how can I do this? BTW I'm using Django-restframework to interact with React. -
set optional parameter in a django url how can do this
I have write down this code in a url path('list/<str:name>', GetList.as_view(), name = "getList" ) now i want to set name as optional parameter with list it show show all and with name i will implement query -
Django manage stream response from StreamingHttpResponse
I met a problem when create stream video from Django server. generator_list = [] @gzip.gzip_page def get_stream_video(request, stream_link): if len(generator_list) == 2: generator_list[1].close() del(generator_list[1]) try: generator = detect_stream(stream_link) generator_list.append(generator) stream = StreamingHttpResponse(, content_type="multipart/x-mixed-replace;boundary=frame") return stream except: pass Everytime I call this controller from client, it will create new instance of connection. Then I found that if those streaming response not closed, CPU will load more and more. I try to save stream generator and close but it did not work. -
Could I make a Django project in ubuntu by Java?
Well... In my toy project, I want to make a Django project in ubuntu server by java ` ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} ` I check process builder activate command such as touch, ls, cd etc... But django-admin never activate ever. I check django is installed on my server How can I make a django project? Sorry for my fool English expected ProcessBuilder builder = new ProcessBuilder(); builer.command("sh","-c","django-admin startproject helloWorld"); builder.directory(/home/ubuntu/toy_service); try { builder.start(); } catch(IOException e) {e.getMessage();} happen nothing -
python django intercepting an sql query before it is executed
I have a library that natively crashes into django and works with django Admin and knows how to use objects.all() and so on. The QuerySet goes instead of to the database location in another api project. I need to intercept an sql query before executing which django does so that I can do even more magic with queries. maybe someone knows how to do it in theory ? well, or there is an example I will be glad to see. у меня есть библиотека которая нативно врезается в django и работает с django Admin и умеет использовать objects.all() и тд. Сам QuerySet в место базы данных ходит в другой проект по api. мне нужно перехватить sql запрос до выполнения который делает django что бы я мог делать еще больше магии с запросами. может кто то знает как это в теории сделать ? ну или есть пример буду рад увидеть. I tried to look for something similar on the Internet, but everywhere there is information only for outputting information to the logs about executed requests through Middleware я пробовал искать что то подобное в интернете но везде есть информация только на вывод в логи информацию о выполненных запросах через Middleware