Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need to upload templates through django admin panel which contain index file along with static files
Let me explain it more clearly. I am trying to make a portal where I take landing page template from different users and check manually that template is working file or not. If everything looks good then I want to upload that theme from my django admin panel which create a new folder for every template like in this case its template1, template/theme/template1/index.html folder and also same with static files I want to upload zip file for all folders of static file and what will happen in backend is it go to folder static/template1/(unzipped static files) where unzipped static files is the location where all the static file will unzip itself so that my index.html and static files can communicate with each other. Please I am stuck here and I an mot able to find any solution for this. Also let me know how can we make a model for uploading file like this to make a new folder everytime from django.db import models from django.contrib.auth.models import User from django.db import models class themes(models.Model): index_file = models.filefield(upload_to=???????) static_files = models.filefield(upload_to =?????) Also I don't want to do collect static every time i upload a new template design. please help me … -
Too Many Values To Unpack While Rendering Data On A Template (Django)
VIEWS def Aeging(request): current_date_thirty = date.today().isoformat() days_before_thirty = (date.today() - timedelta(days=30)).isoformat() thirty = journalVoucher.objects.values('account_name_one').order_by('account_name_one').filter(voucher_date_one__range=[days_before_thirty,current_date_thirty]).annotate(outstanding=(Sum('credit_amount_one')-Sum('debit_amount_one'))) for item in thirty: item['account_name_one'] = CreateLedger.objects.get(id=item['account_name_one']) return thirty context ={'thirty':thirty} return render(request,'report/aeging/aeging_analysis.html',context) ## TEMPLATE <div class="row"> <div class="table-responsive col-md-6"> <table id="example" class="table table-bordered"> <caption style="caption-side:top; text-align: center;"><h3>0-30 Days</h3></caption> <thead class="thead-dark"> <tr> {# <th>S No.</th>#} <th>Party Name</th> <th>Total Amount</th> </tr> </thead> <tbody> {% for item in thirty %} <tr class="table-success"> {# <td>{{ }}&nbsp;</td>#} <td>{{item.account_name_one}}</td> <td>{{ item.outstanding }}&nbsp;</td> </tr> {% endfor %} </tbody> <tfoot> <tr class="totalColumn"> <td style="visibility:hidden;"></td> <td>Total:</td> </tr> </tfoot> </table> </div> </div> </div> Hi The Query Is perfectly Run on python shell but when i render the data on a template it shows too many values to unpack (expected 2). Any Solution Of This?? ERROR IMAGE -
Does vue contain blocks funcionality like in djagno
I'm working on new web project. Previously I was keeping everything in one project (django). This time I decided to split it on two separate projects - backend (django) and frontend vue. I haven't worked with raw vue project so here is my question - Can I use blocks in vue ? My goal is to create one main template with nav bar, footer and the middle div for other views, just like in django blocks. I could import these components in each view but it is not elegant and I bet there must be some other solution. -
Using Single JQuery File For Multiple Pages Causing 'Uncaught TypeError'
In my project each app has a single static file containing that app's JQuery. I get the following error printed to console: Uncaught TypeError: Cannot read property 'checked' of null I understand why I am getting this error, it's saying that it cannot find the element on the page. This is because I have this one JQuery file for multiple webpages and each contain different elements. I know I could just create a different JQuery file for every webpage, but this doesn't seem right. I feel I should be able to have a single JQuery file per app. How can I have a single JQuery file which is used by multiple webpages, each of which contain different elements, without having this error thrown? Thank you. -
Two or more unique Foreign keys from same model (dependent chain)
So i have a model like this class ExaminationCenter(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name And another model like this class ExamForm(models.Model): exam_centre_1 = models.ForeignKey(ExaminationCenter, on_delete=models.cascade) exam_centre_2 = models.ForeignKey(ExaminationCenter, on_delete=models.cascade) exam_centre_3 = models.ForeignKey(ExaminationCenter, on_delete=models.cascade) Is there any way to make these three fields to hold the unique item from the same foreign key model. For example if user choose a exam center in exam_center_1 then that examination center should not be available for exam_center_2 and exam_center_3 -
TypeError at / 'str' object is not callable
I'm using django_rest_framework and i'm getting this error when i add the @api_view decorator TypeError at / 'str' object is not callable -
trying to get a value from drop down of html and using that value as key to query a database and display results on same page in django
I have created a form drop down in html and am trying to get the value from it then i have to query the database on that value and display the result on the same page how do i do this ,please help, Currently i am just printing the value, but am getting false in console. Views.py def AdvicePathsExperienceResourcesView(request): a = request.POST.get('field', False) print (a) return render(request,'FirstApp/AdvicePathsExperienceResources.html') Template <form method="POST"> {%csrf_token%} <select name="field" method="post"> <option selected="selected" disabled>Objects on page:</option> <option value="Backup">Backup</option> <option value="Bank_Po">Bank_Po</option> <option value="Business">Business</option> <option value="CAT">CAT</option> <option value="IAS">IAS</option> <option value="GMAT">GMAT</option> <option value="Linux">Linux</option> <option value="Medical">Medical</option> <option value="Networking">Networking</option> <option value="Software Development">SoftwareDevelopmen</option> <option value="SSC_CGL">SSC_CGL</option> <option value="Storage">Storage</option> <option value="Wintel">Wintel</option> </select> <input type="submit" value="Select"> </select> </form> -
Motion JPG images on Django template
I came across a requirement in Django, where I need to display group of JPG images in a series where it looks like streaming images. I found there is a solution in Flask, Reference url: https://blog.miguelgrinberg.com/post/video-streaming-with-flask . However, when I try to implement the same using Django, I am ending up with errors. Does any one help me in implementing this solution. Thanks in advance. -
_meta.get_field() 'method' object is not subscriptable
When trying to access the _meta api in a class based view, I get: 'method' object is not subscriptable For example, this occurs when trying to get a verbose_name for a field using _meta.get_field in a ListView CBV: def get_context_data(self, **kwargs): print(self.model._meta.get_field['email'].verbose_name) Where am I going wrong? -
im not able to edit or save the file,exiting or new one
Im trying to to edit and save markdown file but im not able to save it. here my views.py: def modify(request,selectedit): if request.method == 'POST'or 'GET': editead = request.POST.get('editead') editbody = request.POST.get('editbody') else: return render(request, "ent/edit.html",{ "content": content }) editead="" editbody="" content = util.get_entry(selectedit) return render(request, "ent/edit.html",{ "entries":util.save_entry_edited(editead,editbody), "content": content, "entries":util.save_entry_edited(editead,editbody), "page_title":selectedit }) Where my save function is saved util.py: def save_entry_edited(title, content): filename = f"entries/{title}.md" default_storage.save(filename, ContentFile(content)) -
wagtail - page for showing categories; how?
I wouldl like to implement categories page using wagtail but it is quite difficult to understand for a novice programmer. When just following the tutorial of wagtail(getting started), the categories field is implemented in their official tutorial but I don't know how to get an access For instance, in Django, If I define two models like Categories, and Posts, I can access articles that fall under a specific category using Foreign key and making a view using something like Category.posts_set.all() But how can I do it in wagtail? Thanks for your help in advance -
Is there a way in Django Admin, without custom HTML, to add a custom autocomplete_field that upon save provides a queryset to a model field?
Currently, in one of my Django admin model views, I am able to individually select multiple available countries (Applicant countries) as is available in my database: But this is very tiresome when actually I only really work with a handful of country groupings. But I do have a need to add or subtract the odd country without being required to manage and think of category names for each group of countries. The idea I had was to use keywords (also serves other purposes in the application): What I want to do is add a custom field via admin.ModelAdmin that is also an autocomplete_field, showing the keywords associated with countries in a dropdown. If an item on this dropdown is selected, it would return a queryset of countries with selected keyword to the model field (Applicant countries). Nothing else would need to be saved, don't need to keep track of which country associated keywords were used in the past. It is just a shortcut to bulk selecting many countries at once (so upon add/edit, the custom field would always appear empty). I want as far as possible to do things the Django admin way, without touching custom HTML and things like … -
How to access model field verbose name in a template?
This question has an answer here, but it is outdated and incorrect as it does not work in a template. I am using a standard ListView to access objects in a template. I want to display my objects in a table with field names in the header and field values in the table body. To do this, is fairly straightforward, but I am not sure how to access the object field name. You can't use {{ object._meta.get_field[field].verbose_name }} as _meta is not available in templates. For example: First I add a list of the fields I want to render to the context: def get_context_data(self, **kwargs): context['fields'] = ['id', 'email', 'name'] Then I loop them in the template: <table> <thead> {% for object in object_list %} {% if loop.first %} <tr> {% for field in fields %} // MISSING CODE // {% endfor %} </tr> {% endif %} {% endfor %} </thead> <tbody> {% for object in object_list %} <tr> {% for field in fields %} <td>{{ object[field] }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> This works well in that it displays just the fields I want in the body, but somehow I need to access the field … -
Django channels rest framework websocket work in production bat i don't receive variations of the models
Hi everyone I deployed django with channels via daphne with reverse proxy nginx, I have a problem that has no answer, it works correctly locally. I used the django library "djangochannelsrestframework" [djangochannelsrestframework][1] to receive variations on ORM models via websocket I use this version of django,channels. django==3.0.8 djangochannelsrestframework==0.1.0 channels==2.4.0 daphne==2.5.0 gunicorn==20.0.4 consumer.py import json from channels.generic.websocket import WebsocketConsumer from djangochannelsrestframework.observer.generics import ObserverModelInstanceMixin from app_mobile.API.Client.Utente.serializer import UserSerializer from app_mobile.API.Client.Azienda.serializer import AziendaObserverSerializer from app_mobile.API.Client.Ordini.serializer import OrdineConsumerSerializer from app_mobile.models import Azienda, Ordine, User from djangochannelsrestframework import permissions from djangochannelsrestframework.generics import GenericAsyncAPIConsumer class AziendaObserver(ObserverModelInstanceMixin, GenericAsyncAPIConsumer): queryset = Azienda.objects.all() serializer_class = AziendaObserverSerializer permission_classes = (permissions.AllowAny,) routing.py application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path("ws/observer/azienda/", AziendaObserver) ]), ), }) nginx # Enable upgrading of connection (and websocket proxying) depending on the # presence of the upgrade field in the client request header map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen xx.it:80; server_name xx.it www.xx.it; return 301 https://xx.it$request_uri; } server { listen xx.it:443 ssl http2; server_name asap24.it www.xx.it; charset utf-8; access_log /var/log/nginx/xx.it.access.log; error_log /var/log/nginx/xx.it.com.error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/xx/; expires 1M; access_log off; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } location / { … -
Django, why would I need nginx and uWSGI during hosting?
I have experience in hosting simple Django projects in Pythonanywhere platform(I did't have to install nginx and uWSGI ). Many people use nginx+Uwsgi with Django, why would that required ? I hope nginx is a web server, load balancer, mail proxy and HTTP cache. Uwsgi is a webs server gateway interface. Does all those things are being included default in Heroku / Pythonanywhere platforms ? -
Django: How to work with radio button in Django?
I am creating a MCQ web application in which user will select an answer and application will return the answer is correct or not on the spot. views.py: def practice(request): questions = Question.objects.all() return render(request,"practice.html",{'questions':questions}) practice.html: {% for i in questions %} <div class="container border"><br /> <h2>{{ i.question }} : </h2> <b> <hr></b> <div class="form-check p-2 "> <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt1 }}" value="{{ i.opt1 }}"> <label class="form-check-label" for="{{ i.opt1 }}"> {{ i.opt1 }} </label> </div> <hr> <div class="form-check p-2 "> <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt2 }}" value="{{ i.opt2 }}"> <label class="form-check-label" for="{{ i.opt2 }}"> {{ i.opt2 }} </label> </div> <hr> <div class="form-check p-2 "> <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt3 }}" value="{{ i.opt3 }}" > <label class="form-check-label" for="{{ i.opt3 }}"> {{ i.opt3 }} </label> </div> <hr> <div class="form-check p-2 "> <input class="form-check-input" type="radio" name="{{ i.id }}" id="{{ i.opt4 }}" value="{{ i.opt4 }}"> <label class="form-check-label" for="{{ i.opt4 }}"> {{ i.opt4 }} </label> </div> </div> <label hidden>{{ i.correct_answer }}</label> <br /> {% endfor %} Output: Now I want to show user that he has selected correct answer or incorrect, correct answer is saved in {{ i.correct_answer }}. Can anyone help me how to … -
How do you link 2 apps within django?
Basically I have built the basics of a website. I am now wanting to implement a blog on the website as another app. How do I go about linking the URLs, views, models within these apps? Also, with the templating do I have to insert the blog webpage to the blog app or keep it on the main website app? -
Django - how to render a file structure beautifully?
using the function below in views.py, i can generate the contents/structure of a folder, given a file_path: [the function basically returns a list that contains strings, if you don't wanna read the code and want to see what the strings look like check the next 2 images] def XML_files_structure(startpath): lst = [] for root, dirs, files in os.walk(startpath): level = root.replace(startpath, '').count(os.sep) indent = ' ' * 4 * (level) lst.append(indent + os.path.basename(root) + '/') subindent = ' ' * 4 * (level + 1) for f in files: lst.append(subindent + f) return lst In my template, i have the HTML code: <ul> {% for str in data.file_structure %} <pre> {{str}} </pre> {% endfor %} </ul> which generates the following on my webpage This kind of structure is indeed what I'd like. But i feel like I'm doing it in a very inefficient way, and also the final result is ugly and not very user friendly. I'd like to add the functionality you have in the windows explorer - the ability to open and close up the contents of a folder. How would you do this in Django? -
Python get hours min and days from the seconds
In python using my code i am getting min from the seconds . but i also want Hours after 60 min and days after 24 hours how can i make this possible can anyone have any idea. My code is given below : time = int(booking[index]['fields']['google_time']) time_in_min = time / 60 booking[index]['fields']['google_time_in_min'] = round(time_in_min) -
Django order_by price field with linked currency field
I have real estate model. There are two fields price and currency. People can enter real estate's price in two currency only. However as price field is just numbers and prices are linked to currency, I can not order prices with different currency. Only ordering with the same currency is possible. Only two currency options are available: UZS = 'UZS' USD = 'USD' CURRENCY_TYPES = ( (UZS, 'sum'), (USD, 'y.e.') ) class Property(BaseModel): price = models.PositiveIntegerField() currency = models.CharField(max_length=255, choices=CURRENCY_TYPES) I tried to change prices to the same currency but then I don't know how to order them. Property.objects.filter(currency='UZS').annotate(divided_price=F('price') / 10000).values('divided_price') So rate is 1 USD = 10 000 UZS 10 000 UZS = 1 USD How to order prices with different currencies? -
Textarea not showing in django User change form
I have a django app with the user creation form having a textarea for input. This part is working fine. But the user change form is outputting the textarea as a simple regular input field as well. Following is the code for user change form <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="form-group"> <strong><label class="control-label" for="town-city">About Me</label></strong> {{form.bio|add_class:"form-control"}} {% if form.bio.value == None %} <strong style="color:red;">{{form.bio.errors}}Empty field</strong> {% endif %} <strong style="color:red;">{{form.bio.errors}}</strong> </div> </div> </div> -
Django, select_related or prefetch_related when updating
Suppose you have a shopping cart and cart has many item lines. For retrieving data, you could use select_related or prefetch_related fine. However there are apis which update lines (you might want to change quantity for an item). When you update a line, the prefetched lines would be invalid. How do you manage update and still get the benefit of select_related / prefetch_related? Is there a better way than manually tracking the code where update might occur and re-valuate the select_related / prefetch_related everytime when data changes ? -
Menu and submenu in Django Models
Am new to Django, i want to create a Menu with Sub menu (like Drill Down) to show some respective Html Pages. 1.Master a.Customer b.Product c.Supplier 2.Production a.Daily Entry b.Report C. Production View -
Custom UUID field PK returns wrong type when accessed as a foreign key
I need a UUID pk and due to some serialization issues I was thinking about making it a UUID only in the DB and a string outside of it. I've created this custom field that allows exactly that. import uuid from typing import Union from django.db import models class CustomUUIDField(models.UUIDField): """ In database: uuid Outside of a database: str """ description = "Custom UUID field which is an UUID only in DB and a string outside of it" @staticmethod def _serialize_value(value: Union[str, uuid.UUID]) -> str: return str(value) @staticmethod def _deserialize_value(value: Union[str, uuid.UUID]) -> uuid.UUID: if isinstance(value, str): value = uuid.UUID(value, version=4) return value def to_python(self, value) -> str: return self._serialize_value(value) def from_db_value(self, value, expression, connection) -> str: return self._serialize_value(value) def get_prep_value(self, value) -> str: return self._serialize_value(value) def value_to_string(self, obj): value = self.value_from_object(obj) return self.get_prep_value(value) def get_db_prep_value(self, value, connection, prepared=False) -> uuid.UUID: return self._deserialize_value(value) class UUIDMixin(models.Model): id = CustomUUIDField(default=uuid.uuid4, primary_key=True, editable=False) class Meta: abstract = True def is_new(self) -> bool: return self._state.adding def __str__(self): return f"<{self.__class__.__qualname__}: {self.id}>" Now I have these two fellas class A(UUIDMixin): pass class B(UUIDMixin): a = models.ForeignKey(A, on_delete=models.CASCADE) What is inconsistent is that: a.id returns a string. b.id returns a string. b.a.id returns a UUID Did I … -
Why does AJAX not stop page refresh?
Can someone please help me out with AJAX in Django. I'm trying to create a simple form with 2 inputs and send it to my python backend without a page refresh. Here's my AJAX code: <script type="text/javascript"> $(document).ready(function(){ $("#seearch").submit(function(e){ e.preventDefault() $.ajax({ type:'POST', url:'/some/', data:{ origin:$('#origin').val(), destination:$('#destination').val(), }, success:function(){ document.write("HelloWorld") } }); return false; }); }); </script> Here's the code I used for my form: <div style = " width:0.01px; height:0.01px; position:relative; top:-700px; left:0px;"> <div class="container px-5 py-24 mx-auto flex flex-wrap items-center" > <form id="seearch"> <input id="origin" class="button" name="origin" placeholder="Where from?" type="text"><div></div> <input id="destination" class="button" name="destination" placeholder="Where to?" type="text"> <input class="button" name="navigate" type="submit" placeholder="navigate"> </form> </div> </div> The request sent to backend should be an AJAX request but it is almost as if the AJAX code is ignored by the form. When I click submit, it just simply submits the form and refreshes the page. I've been struggling with this for almost 2 days, and it'd be a great help if something could help me figure where I've gone wrong. Thanks!