Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pip hangs on installing packages
I'm using django in a virtual environment. I'm using powershell and trying to install pyopenssl. I try pip install pyopenssl: (bookmarks) bookmarks> pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting six>=1.5.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/d9/5a/e7c31adbe875f2abbb91bd84cf2dc52d792b5a01506781dbcf25c91daf11/six-1.16.0-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... it hangs on Installing build dependencies .... I've waited 30mins but nothing happened. I've also tried python -m pip install pyopenssl (bookmarks) bookmarks> python -m pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... \ And when I try pip -v install pyopenssl: (Since the ouput is large, i'm only showing the last part.) Added semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) to build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Removed semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) from build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Installing collected packages: setuptools, wheel, pycparser, cffi, toml, semantic-version, setuptools-rust Creating C:\Users\Suhail\AppData\Local\Temp\pip-build-env-fwbrqqmx\overlay\Scripts Successfully installed cffi-1.14.6 pycparser-2.20 semantic-version-2.8.5 setuptools-58.1.0 setuptools-rust-0.12.1 toml-0.10.2 wheel-0.37.0 Cleaning up... Cleaned build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' 1 location(s) to search for versions of pip: * https://pypi.org/simple/pip/ Getting page https://pypi.org/simple/pip/ Found index url https://pypi.org/simple Looking up "https://pypi.org/simple/pip/" in the cache Request header has "max_age" as 0, cache bypassed Starting new HTTPS connection (1): pypi.org:443 https://pypi.org:443 "GET /simple/pip/ HTTP/1.1" … -
Django: How to add DeleteView and UpdateView
Hi I'm Student in django, i want to add UpdateView and DeleteView, can someone expert guys can help me to figure out (Forum website) :D i provide some of my views.py code class TopicView(View): def get(self, request, *args, **kwargs): tid = request.GET.get('id') print(tid) topic = Topic.objects.filter(id=tid).first() print(topic) # topic.clicks += 1 topic.save() username = check_result(request, topic) print(username) comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) @check_login def post(self, request, *args, **kwargs): topic_id = request.POST.get('topic', '') content = request.POST.get('content') topic = Topic.objects.filter(id=topic_id).first() username = check_result(request, topic) if content: user = UserInfo.objects.filter(username=username).first() comment = Comment(user=user, topic_id=topic_id, content=content) comment.save() comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic print(Form.errors) return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) tid = Topic_id of post_id .. content = the content inside the topic class PublicView(View): @check_login def get(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() # semester = subject.semester username = request.session.get('name') return render( request, 'public.html', context={'username': username, 'form': Form, 'content': {'subject': subject}} ) @check_login def post(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() username = request.session.get('name') print(username,'asdasd') user = UserInfo.objects.filter(username=username).first() name = request.POST.get('title') content = request.POST.get('content') … -
Django: unable to make a calculation inside a template
I've created a e-commerce Django application and in the back office of this application, I have a page that is supposed to show some statisctics. I'm trying to display benefits or losses. For the costs, I've created a @property in the model as following: class Statistics(models.Model): """ The Statistics model represents the statistics that can be calculated """ costs_infra = models.FloatField(verbose_name="Costs Infrastructure") costs_salary = models.FloatField(verbose_name="Costs Salary") class Meta: verbose_name_plural = "Statistics" def __str__(self): """Unicode representation of Statistics""" return " Infra costs: {}, Salary costs: {}".format( self.costs_infra, self.costs_salary ) @property def calculate_costs(self): return self.costs_infra + self.costs_salary For the total income, I've calculated it inside a view as following: @group_required('Administrator', 'Manager') def stats_home(request): total_users = User.objects.all().count() costs = Statistics.objects.all() subscriptions_1month = Subscription.objects.get(plan_name='1 Month') subscriptions_1year = Subscription.objects.get(plan_name='1 Year') subscriptions_3year = Subscription.objects.get(plan_name='3 Years') user_subscriptions_1month = UserSubscription.objects.filter(subscription=subscriptions_1month).annotate(Count('user', distinct=True)).count() user_subscriptions_1year = UserSubscription.objects.filter(subscription=subscriptions_1year).annotate(Count('user', distinct=True)).count() user_subscriptions_3years = UserSubscription.objects.filter(subscription=subscriptions_3year).annotate(Count('user', distinct=True)).count() income_per_subscription_1month = Subscription.objects.get(plan_name='1 Month').price * UserSubscription.objects.filter(subscription=subscriptions_1month).count() income_per_subscription_1year = Subscription.objects.get(plan_name='1 Year').price * UserSubscription.objects.filter(subscription=subscriptions_1year).count() income_per_subscription_3years = Subscription.objects.get(plan_name='3 Years').price * UserSubscription.objects.filter(subscription=subscriptions_3year).count() total_income = income_per_subscription_1month + income_per_subscription_1year + income_per_subscription_3years return render (request, "stats_home.html", locals()) An finally, I'm trying to make a simple calculation (total income - total costs) but I'm unable to do this inside the template, as far as I could see … -
how to use external webcam as an image scanner to save into the database?
I'm trying to use an external webcam as an image scanner, is'nt there a way to achieve that please , im using django as backend **3.2 version ** this is my models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) i have to instead of scan documents , just capture a picture of them from my web browser and upload them ? i know i have to use js to access webcam , but i dont know how to save it into the database thank you in advance .. -
custom message in raise PermissionDenied not working in Django rest
I tried raise PermissionDenied("Anonymous user") inside a custom permission function but the message I wrote is not showing in the api response. Instead, it is showing the default forbidden message that says you dont have permission to perform this action My snippet is here: class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request,view): slug = request.resolver_match.kwargs["slug"] if slug is not None and request.method == 'POST': if slug == "abc": user = request.user if user.is_staff: return True if user.is_anonymous: print("iam here") raise PermissionDenied("Anonymous user") elif slug == "mnp": return True else: return True Here in the above code I reached to ("iam here") but anonymous user is not printing instead showing the default message. -
Django QuerySet from one-to-many and from many-to-one
working on a project, where i came to a small problem with QuerySets. (Look at the bottom to see a short diagram of my model structure.) I tried to query some information of a BLOG-Model starting from the Collection-Model. Now is it better to query first the Entrie-Model and find somehow the Collection to afterwards find the Blog-Model and add the information in the end to the Collection? Or is there a better / faster way to get information directly from the parent Model? Normaly it is easy if you just have 1:n->1:n Relations because you can easily follow the foreignkey, but this confuses me. Here a short overview of my model structure: <--------------- QUERY DIRECTION ---------------- (BLOG) --(1:N)--> (ENTRIE) <--(N:1)-- (COLLECTION) BR, Felix -
How to store the path of a media file in Cassandra when using django-cassandra-engine?
Hey guys I am learning to implement Cassandra db with Django. In SQL db's we can store the path of a file in FileField, but how to do the same with Cassandra? Can anyone give some insights? Thanks in advance. -
send a specific queryset to all templates
I have a Django application which has notification.It uses Django channels this way that it takes user id in view and then at templates uses json_script to make the id a JS object. So i have to write the bellow code every where user=user.id context={....,"user":user} How can i write it one instead of every where? -
try and except not working in Django Rest Framework
I have written custom permission based on the http method and the user that is requesting. I have to use try and except at one point. But seems like it is not working properly. The snippet is here: class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request,view): slug = request.resolver_match.kwargs["slug"] print(slug) if slug is not None: if slug == "abc": try: user = request.user if user.is_staff: return True else: print("yes object") raise PermissionDenied("You need to be an admin to perform this action") except ObjectDoesNotExist: print("no object") raise PermissionDenied("Anonymous user") elif slug == "xyz": print("iam xyz") print(slug) return True else: print("nothing") return True Here the issue is when the request has a slug in its url and it is "abc", but no any user credentials is provided( no token in the headers), then the code of except ObjectDoesNotExist: should have worked, however, the print("yes object") is printing. It should only print yes object if there is user and it is not staff. The print I should be getting is ("no object"), because there is no user since the object doesn't exist. Also, I am getting permissiondenied message, instead the default 403 forbidden message. What … -
Prevent the release of the download file link
Hello to all Django lovers I have a question that I have not received an answer for a month. My question is: How to write a model and view in Django that only users who are registered in the site are allowed to download the file. That is, how can I prevent the publication of links to our files. Please suggest a way. -
how to call back tenant schema name django
im trying to return back tenant schema names in one of my tables data , im using django-tenant this is what im trying to achieve class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,default=1) full_name = models.CharField(max_length=150) @login_required def daily_vistors_detail_html(request,day): lists = BookingVisitor.objects.annotate(day=TruncDay('date')).filter(day=day).order_by('-pk') context = { 'lists':lists } sometimes i have to return back data's with its tenant domain ! <table class="w-full text-center table-auto display nowrap" style="width:100%" id="vistors"> <thead> <tr> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "admin" %}</th> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "full name" %}</th> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "tenant name" %}</th> </tr> </thead> <tbody id="list_vistors_daily" class="w-full"> {% for i in lists %} <tr> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{i.admin}}</td> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{i.visitor.full_name}}</td> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{tenant name}}</td><!-- this is should return the current tenant name --> is there any way to return current tenant name from a view?!thank you in advance -
Without passing Request parameter How Can i get the Logged in Username in django
i make a class in a py file in my django project. In this i need the logged in person's username. in views.py file, every function i pass request perameter, so that i could easily get the logged username. but in other py file i make a class, and there how can i get the logged user??? Thanks. in class, i can not pass the request perametar. so i can not call requset.user. how can i get the logged user??? -
Django project - Scape the data using selenium and then save the data into live server database without using form
I have a website for which data is being displayed in real-time. To enter data into the database, currently, I am using selenium to extract the data from other sites and then putting those data into forms and save. This includes various steps and hence delays the process. My question: Is there any process to scrape the data using selenium externally and directly save those data into my live domain sqlite database? -
Random '>' not supported between instances of 'NoneType' and 'float' with xhtml2pdf
I'm using xhtml2pdf in a Django application to generate PDF files from Pandas html output. I'm having this error that raise randomly (not all times): Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python37\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\DEV\webdeploy\django_proj\django_app\views.py", line 171, in post return pdfDownload(pivot, data_stock, data_ecarts,annee_,request) File "D:\DEV\webdeploy\django_proj\django_app\views.py", line 310, in pdfDownload pdf = pisa.pisaDocument(BytesIO(html_styled.encode("ISO-8859-1")), result) File "C:\Python37\lib\site-packages\xhtml2pdf\document.py", line 144, in pisaDocument doc.build(context.story) File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 1079, in build self.handle_flowable(flowables) File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 955, in handle_flowable (self._fIdent(f,60,frame),_fSizeString(f),self.page, self.frame.id, File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 890, in _fIdent return f.identity(maxLen) File "C:\Python37\lib\site-packages\reportlab\platypus\tables.py", line 421, in identity tallest = '(tallest row %d)' % int(max(rh)) Exception Type: TypeError at /iw/dataload/ Exception Value: '>' not supported between instances of 'NoneType' and 'float' It seems the error come from the ReportLab library where it is trying to get the max … -
Exclude if any of statement is true
I am building a Simple Blog Post web app, And I am trying to exclude items if any of items is true, But it is checking for all statements, I mean it is checking if all the statements are true which i don't expect. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) body = models.CharField(max_length=30) class Rate(models.Model): by_user = models.ForeignKey(User, on_delete = models.CASCADE) blog_of = models.ForeignKey(BlogPost, on_delete = models.CASCADE) rated_1 = models.BooleanField(default=False) rated_2 = models.BooleanField(default=False) completed = models.BooleanField(default=False) views.py def page(request): queryset = Rate.objects.filter(completed=False).exclude(rated_1=False, rated_2=False) context = {'queryset':queryset} return render(request, 'page.html', context) What's the Output ? It is showing queryset which is completed=False but not excluding if one of the exclude items is true. I have tried many times but it is still not working. Any help would be much appreciated. Thank You in Advance. -
Django CustomUser permissions: Add User & Can add user
I'm using Django 2.2.5. We have just transitioned our application to a CustomUser model. This appears to have changed the permission string for non-superusers. For example: with a CustomUser model, the superuser has these two permissions; Can add User and also Add User. I have an "admin" user role with a subset of the superuser permissions. I'm using the django-role-permissions package to define these roles. For this "admin" role I don't get both of these permissions, the default django user has the permission "Add User", and the CustomUser user has the permission "Can add user". The django-role-permission package can create the "Add User" permission, but not the "Can add user". Is there any way I can configure this behavior in Django 2.2.5? Where could I read up on these two sets of closely related permission names. -
Locking Failed! pipenv install requests
So i am trying to learn python and we were told that we will be using Django. As an advance, I tried setting up the environment, I ran into this problem right after typing in pipenv install requests The result is as follows Installing requests… Adding requests to Pipfile's [packages]… Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Locking Failed! Unable to create process using 'c:\.......\python\python39\python.exe"c:/....../python/python39/lib/site- packages/pipenv/resolver.py"' Can anyone help me with this problem please. -
How to POST multiple rows in django using ajax
how can i save multiple rows when click on save button. this is django framework. i have submitted my model and template file. but please help me to find out how to post multiple rows when click on save button this is my model class class Items(models.Model): item_name=models.CharField(max_length=50) item_code=models.CharField(max_length=50) desc=models.CharField(max_length=50) price=models.IntegerField() this is my template class <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AddBills</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <br /> <h2 align="center">Add Items</h2> <br /> <div class="table-responsive"> <form> {% csrf_token %} <table class="table table-bordered" id="crud_table"> <tr> <th width="30%">Item Name</th> <th width="10%">Item Code</th> <th width="45%">Description</th> <th width="10%">Price</th> <th width="5%"></th> </tr> <tr> <td contenteditable="true" class="item_name"></td> <td contenteditable="true" class="item_code"></td> <td contenteditable="true" class="item_desc"></td> <td contenteditable="true" class="item_price"></td> <td></td> </tr> </table> <div align="right"> <button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button> </div> <div align="center"> <button type="button" name="save" id="save" class="btn btn-info">Save</button> </div> </form> <br /> <div id="inserted_item_data"></div> </div> </div> </body> </html> <script> $(document).ready(function(){ var count=1; $('#add').click(function(){ count=count+1; var html_code="<tr id='row"+count+"'>"; html_code+="<td contenteditable='true' class='item_name'></td>"; html_code+="<td contenteditable='true' class='item_code'></td>"; html_code+="<td contenteditable='true' class='item_desc'></td>"; html_code+="<td contenteditable='true' class='item_price'></td>"; html_code+="<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>"; html_code+="</tr>"; $('#crud_table').append(html_code); }); $(document).on ('click','.remove',function(){ var delete_row=$(this).data("row"); $('#'+delete_row).remove(); }); $('#save').click(function(){ var item_name=[]; var item_code=[]; var item_desc=[]; var item_price=[]; $.ajax({ url:"", … -
"def save" - Detect if a field is completely blank - Django
In my Django models, I have a def save function. I need this function to see if a field is left blank completely. I need it to see if a field has been left blank every single entry and then return something to an HTML file. I'll attach my code below but I'm really stumped. I'm not sure how I can set a value in that function and get it all the way to my HTML. Is there an easier way? models.py class Data_Repo1(models.Model): user = models.ForeignKey(User, default=True, related_name="Data_Repo1", on_delete=models.PROTECT) date1 = models.DateField(blank=True, null=True) date2 = models.DateField(blank=True, null=True) class Meta: ordering = ['-pk'] def __str__(self): return self.date1 or 'None' def get_absolute_url(self): return reverse('repo1') def save(self, *args, **kwargs): if self.date1 is None: #Something Here - "self.date1 = NONE" else: return if self.date2 is None: #Something Here - "self.date2 = NONE" else: return super().save(*args, **kwargs) # Call the "real" save() method. views.py def repo1(request): context = {} context['Add_Repo'] = Add_Repo.objects.filter(user=request.user) context['Data_Repo1'] = Data_Repo1.objects.filter(user=request.user) context['Field_Repo1'] = Field_Repo1.objects.filter(user=request.user) if self.date1 is None: #NOT WORKING print('TEST') #NOT WORKING return render(request, 'sheets/list_repo/repo1.html', context) HTML {% for post in Data_Repo1 %} {% if date1 == 'NONE' %} <h1>ITS HERE</h1> {% endif %} <tr> <td><div><a href="{% url 'update_extinguisher' … -
How to place captcha on Django CreateView
I'm working in an existing codebase that uses Django Material. There is a CreateView defined as: class OurModelCreateView(LayoutMixin, CreateView): model = OurModel This view is getting lots of spam signups and so needs to have a captcha. I use Django Recaptcha, and I've set up a number of captchas in the past. However, I've never set one up on a generic view. If I create a Django form and define the captcha field in the form as always done in the past: from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 class OurModelForm(ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV3) class Meta: model = OurModel exclude = () and then specify form_class = OurModelForm on the CreateView, then I get an error stating that fields and the form_class can't both be specified at the same time. This is happening because Django Material's LayoutMixin defines fields: https://github.com/viewflow/django-material/blob/294129f7b01a99832a91c48f129cefd02f2fe35f/material/base.py (bottom of the page) So I think that the only way to do what I need is to dynamically insert the captcha field into the form. The following two attempts do not work: On the CreateView: def get_form(self, form_class=None): form = super(OurModelCreate, self).get_form(form_class) form.fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3) return form def fields(self): fields = [super().fields(*args, **kwargs)] fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3) return [field.field_name … -
Django throws `column does not exist Error` for only 1 model class out of multiple classes with same structure
I am running into this problem whenever I am trying to fetch data from a specific model class. The database used here is Postgres and I am using django.db.backends.postgresql_psycopg2 engine. This is my models.py file : class level1(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) class level2(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) class level3(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) class level4(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) class level5(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) class level6(models.Model): id = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True) data = models.JSONField(null=True) Whenever I am trying to fetch the data I am met with this error : Environment: Request Method: GET Request URL: http://127.0.0.1:8000/level/1/edit Django Version: 3.2.7 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'formdata'] 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\royim\Desktop\Intern@VakilDesk\Codes\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (column formdata_level1.data does not exist LINE 1: SELECT "formdata_level1"."id_id", "formdata_level1"."data" F... ^ ) was the direct cause of the following exception: File "C:\Users\royim\Desktop\Intern@VakilDesk\Codes\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\royim\Desktop\Intern@VakilDesk\Codes\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\royim\Desktop\Intern@VakilDesk\Codes\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\royim\Desktop\Intern@VakilDesk\Codes\Starter … -
Django - I need the total sum displayed after a filtered search
I am hoping to get an answer to what I believe is probably a simple solution, but my current Python/Django knowledge is limited, and I cannot seem find anything when I Google it. I have column in a table that has decimal values and linked to that table is a filter which is searching by date and site code. I want the total sum of the column to be displayed after I perform the search. I have an aggregation setup on that column, which is working but it is not dynamic and when I perform a search it just keeps the value of the total to be the unfiltered result. The desired response would be for the total to change with each search result. Models.py class expense(models.Model): ExcludeTax = models.DecimalField('Exclude Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) IncludeTax = models.DecimalField('Include Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) user = models.ManyToManyField(dbmobile, blank=True) Date = models.DateField(default=now) Views.py def expense_table(request): item = expense.objects.all().order_by('IncludeTax') add = expense.objects.all().aggregate(Sum('IncludeTax'))['IncludeTax__sum'] search_list = expense.objects.all().order_by('user__Site_Code', 'Date') search_filter = expenseFilter(request.GET, queryset=search_list) return render(request, 'expense/MExpense.html', {'item': item, 'filter': search_filter, 'add': add}) filters.py class expenseFilter(django_filters.FilterSet): Date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = expense fields = ['Date', 'user__Site_Code'] html <tfoot> <tr> <td><b>Total</b></td> <td><b>{{add}}</b></td> </tfoot> -
Dockerfile commands not running on compose but working in the CLI after the container is built
I'm currently learning docker and trying to deploy my django project to a local container with postgres and redis. When I run docker compose the container builds and lets me connect to the django server but it is missing some of the pip requirements and libraries specified in the Dockerfile. If I run the commands from the Dockerfile in the CLI of the container they all work correctly. The Dockerfile used in the docker compose, gcc library installs correctly but g++ and any of the other unixodbc libraries don't exist in the container when checking from the CLI interface. Here is the docker compose file, version: '3.8' services: dashboard-server: build: context: ./ command: python manage.py runserver 0.0.0.0:8000 container_name: dashboard-server depends_on: - dashboard-redis - dashboard-database environment: - PGDATABASE=django - PGUSER=django - PGPASSWORD=2bi3f23f2938f2gdq - PGHOST=dashboard-database - PGPORT=5432 - REDIS_URL=redis://dashboard-redis:6379/0 ports: - "80:8000" volumes: - ./:/usr/src/app dashboard-redis: container_name: dashboard-redis image: redis:6-alpine dashboard-database: container_name: dashboard-database image: postgres:13-alpine environment: - POSTGRES_USER=django - POSTGRES_PASSWORD=2bi3f23f2938f2gdq ports: - "5433:5432" expose: - 5432 volumes: - dashboard-database:/var/lib/postgresql/data volumes: dashboard-database: The Dockerfile in the same directory, # pull official base image FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install … -
Django Manager and QuerySets: How may I set up my manager and query to retrieve Parent ForeignKey ID in models.Queryset to build a folder directory?
How can I extract Parent ForeignKey IDs of ManyToManyFields by a Manager to build a path that i may a build Folder Directory? I can query in the shell to retrieve the parent ID. Output is Board.id = 1 which is correct In [37]: _id = Column.objects.all() In [38]: _id[0].board.id Out[38]: 1 if i try to reproduce in Manager i return with error TypeError: 'ForeignKeyDeferredAttribute' object is not callable So as soon as a board is initiated a folder is created as you can see in the Board Model. Now i have a child model called Column that has a ForeignKey field from Board. Objective is create child sub-folder in the directory as soon as Column model saves. So the model needs to lookup the parent ID and add Column.id to a relative path Therefore i believe logically i should query the Foreign key in the Column model and build a relative path as described in ColumnQuerySet. In short, how can i create a subdirectory folder? Any Ideas? Thank you for any help. Model.py class Board(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey( User, on_delete=models.PROTECT, related_name="owned_boards" ) members = models.ManyToManyField(User, related_name="boards") class Meta: ordering = ["id"] def __str__(self): return self.name def … -
Django Templates - Best Practice in Avoiding Repeating Code that Require Different For Loops?
I'm creating a blog and have numerous pages that will display a list of articles. So, to avoid repeating that code, I'm trying to place it within a parent template that I can extend where needed. The problem is I'll need a different for loop to display the article lists on each page/view. I figure the easiest approach would be to simply create blocks where I want the loop to start and close within the parent, then alter accordingly within each child. However, Django doesn't allow you to close blocks that have an open for loop, despite closing the loop later in a different block. My initial approach, in the parent, article_list.html: <div class="row"> {% block loop_start %} {% endblock loop_start %} <div class="col-xs-12 col-sm-4"> <div class="card"> <a class="img-card"> <img class="img-fluid"src="../../static/{{ post.featured_image }}" /> </a>.... etc I know I have to fix my src code. Extends to child as: {% block loop_start %} {% for post in recent_articles %} {% endblock loop_start %} However, that doesn't work as noted above. I've also tried wrapping the entire code for the article list in a block, extending it and performing the following within the child: {% for post in recent_articles %} {% …