Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update M2M field related data attributes in Django
I want to update the vote value of each candidate which is related with m2m field of specific Constituencies. I have Constituencies update function where user update the Constituencies but i my case i also want to update the candidates vote value which is coming from object in object.candidates.all class Candidates(models.Model): name = models.CharField(max_length=100) votes = models.PositiveBigIntegerField(default=0) class Constituencies(models.Model): candidates = models.ManyToManyField(Candidates) views.py def constituency_detail(request, pk): obj = get_object_or_404(Constituencies, id=pk) form = ConstituenciesForm(request.POST or None, instance=obj) if request.method == 'POST': pass template.html <h5>{{ object }}</h5> {% for object in object.candidates.all %} <h5>{{ object }}</h5> {{ object.votes }} as input field {% endfor %} -
Django: Prepopulate extra fields in a Formset with a ManyToMany Model
I have two models with a ManyToMany (M2M) relationship. In order to have extra fields on the M2M Model, I defined a through= model. I tried setting up a inlineformset_factory, using parent=ChildModel and model=ParentModel.parent_child.through as described in this thread pendant to inline formsets for many-to-many relations. But it did not solve my issue. How can I access (i.e. prepopulate) and update the extra fields of the M2M model, when using formsets? models.py class ParentModel(models.Model): name = model.CharField() parent_child = model.ManyToManyField(ChildModel, through='ParentChildModel') class ChildModel(models.Model): name = model.CharField() class ParentChildModel(models.Model): parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE) child = models.ForeignKey(ChildModel, on_delete=models.CASCADE) extra_field_1 = models.CharField() forms.py class ChildForm(forms.ModelForm): class Meta: model = ChildModel fields = '__all__' ChildFormset = modelformset_factory(ChildModel, form=ChildForm, extra=0, can_delete=True, can_order=True, ) -
Can't load local images with HTML
I am developing a simple site with Django, and wanted to load some images locally to some pages. But it doesn't load for some reason. I know there are similar questions, and from what i understand; a-) It can be a directory problem, html file and img file is in the same directory. Still doesn't work; directory, and the html file. I tried moving the img.jpg to the templates/images directory and try <img src="images/img.jpg" height="400" width="374"> within the html file but that didn't work either. b-) It could be a typo, but from the images up there that shouldn't be the case either. c-) Files could be corrupted, I can open the image with browsers and tried using different images too. d-) Img could be restricted, but that is not the case either. I think. Trying to fix this for two days now, thought for some reason usage of extend or block might cause some problems and tried without them, still no good. and as i said its only a problem with local files. Can use files with direct link. Thanks in advance, sorry for any problems with the format. -
Recipient variables have no value in django-anymail and Mailgun
I'm trying to add some metadata to emails, but never receive it in logs and in webhooks. Here is what I'm doing: recipient_variables = {recipient:metadata} msg.merge_metadata = recipient_variables This is how the msg.merge_metadata looks like: {'EMAIL': { 'submission_id': 'ID'}} This is what data looks like in Mailgun web logs: "user-variables": { "submission_id": "%recipient.v:submission_id%", }, And webhook just receives: {'submission_id': ''} I also tried msg.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables) It also hasn't changed anything much, but webhook now receives this instead> {'submission_id': '%recipient.v:submission_id%'} Am I doing anything wrong? The whole process seems to be pretty straightforward. — Anymail version — 8.6 ESP (Mailgun, SendGrid, etc.) — Mailgun django 4.0.4, requests 2.27.1, python 3.10 Settings: ANYMAIL = { "MAILGUN_API_KEY": "", "MAILGUN_SENDER_DOMAIN": '', "MAILGUN_API_URL": "https://api.eu.mailgun.net/v3", "WEBHOOK_SECRET" : "", "MAILGUN_WEBHOOK_SIGNING_KEY": "", } -
Pagination with ordering and other get variables
In a class based ListView, while rendering i want to dynamically change the no of items shown per page and the sorting order of those items. I referred to this question and the answer by skoval00 works for me when i change the ordering and change the pages. But as soon as i change the no of items per page, my ordering is lost. For ex: my generic view links to http://127.0.0.1:8000/marketplace/. If i set the pagination to 10 items per page. The url changes to http://127.0.0.1:8000/marketplace/?paginate_by=10 But now if i change my ordering too, i expect something like http://127.0.0.1:8000/marketplace/?paginate_by=10&ordering=end_date but i get http://127.0.0.1:8000/marketplace/?ordering=end_date And the pagination changes to the default value. Same thing happens vice-versa. If i order first and then change pagination, then i lose the ordering once the pagination changes. How do i preserve the first argument while adding the second one? Here is the relevant class in views.py class CatalogueListView(ListView): model = Catalogue context_object_name = 'catalogues' template_name = 'marketplace/catalogue_list.html' paginate_by = 5 ordering = ['end_date'] def get_queryset(self): if self.request.GET.get('ordering'): ordering = self.request.GET.get('ordering') else: ordering = 'end_date' query_set = Catalogue.objects.filter(admin_approved=True, end_date__gt=timezone.now()).order_by(ordering) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.GET.get('paginate_by'): context['paginate_by'] = self.request.GET.get('paginate_by') else: context['paginate_by'] = … -
Display 1 when no data is exist in database
I am trying to generate incremental id whenever I am adding new data in my model. here I am getting the the next number whenever I am adding new data. but If there is no any data in my table its giving me error. 'NoneType' object has no attribute 'tax_id' Here is my code views.py def tax_settings(request): latest_id = (Tax_Settings.objects.last()).tax_id+1 if request.method == 'POST': tax_id = latest_id name = request.POST['tax_name'] tax_percentage = request.POST['tax_percentage'] tax_details=Tax_Settings.objects.create(tax_id=tax_id, name=name, tax_percentage=tax_percentage) tax_details.save() next_id = (Tax_Settings.objects.last()).tax_id+1 return render(request,"settings/tax-settings.html",{"latest_id":next_id}) else: return render(request,"settings/tax-settings.html",{"latest_id":latest_id}) html <input type="text" class="form-control" placeholder="{{latest_id}}" name="tax_id" disabled> which condition I can give to my latest_id if data(tax_id) not exists? -
To manage user authentication on multiple website through SSO
Created an account on Onelogin which act like Identity Provider (IDP) Created a connector app for the website 1 Added onelogin SSO configuration for the website 1 Added the onelogin auth in the website 1 Added a link to the website 2 in the authenticated pages of the website 1 After onelogin auth in website 1, I wanted to know what are the next steps. -
Does Django Optimize the query if it gets run multiple times with the same filter?
class MyModel(models.Model): task_id = models.UUIDField() task_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='+') task = GenericForeignKey('task_type', 'task_id') ..... @property def task_description(self): if self.task_status === 'pending': return 'Pending Task' else: task = Task.objects.filter(self.task_id).first() return task.name or '' In case self.task_status is not pending, then for each task, it looks up the Task table for the name. My Question. suppose task ids [1,2,3,3,3] then what will be the queries that get run ? is this N+1 problem ? for id 1, it checks the Task table where id = 1. for 2 3 it does too. But for id == 3, does it look up the table 3 times with same filter like where id = 3 ? -
How can I deploy code to production when I am running celery, redis, django with docker compose?
I am running celery, Redis, Django, and flower containers with docker compose. The docker-compose.yml file is similar to this tutorial. The whole app can run very well. The problem is when I change the code and deploy it to production. I found that the code was often not updated and this caused errors. For example, I try to change the celery task code or add new tasks. The updated tasks cannot be deployed From restarting the workers, I tried to run the commands: celery multi start 1 -A proj -l INFO -c4 --pidfile=/var/run/celery/%n.pid celery multi restart 1 --pidfile=/var/run/celery/%n.pid kill -HUP $pid But the task is not updated after my testing. The task is still loading the old code. How can I deploy code to production? Should I restart the container with? docker-compose restart celery From the celery docs, it says that: For production deployments you should be using init-scripts or a process supervision system (see Daemonization). The Daemonization is completely not related to docker. I don't understand how Daemonization is related to deployment with docker / docker compose. Actually I don't understand why Daemonization is related to deployment from the official docs. -
Wagtail add bulk actions to ModelAdmin IndexView
I would love to add custom bulk actions to a ModelAdmin index view. Is that possible already or a feature request potentially? The ModelAdmin module’s IndexView is great to filter a larger number of pages. I would love to select a bunch of these pages and start a custom bulk action like "publish", "unpublish" or "add to another page". Alternatively I could try to add more attributes/columns to the page Explorer, which already offers these bulk actions. But the ModelAdmin module was added to Wagtail to do exactly that. So I think, that adding bulk actions to the ModelAdmin is the way to go. -
Want to show Fetched Data on Doughnut Chart with Percentage label in JavaScript
I am new at JavaScript. I want to display counts of rows on Doughnut Chart dynamically. Data is fetching dynamically in form of table. key: "results_callback", value: function results_callback(data) { data = data.tasks; if (Object.keys(data).length == 0) { $("div#no_more_results").show(); $("div#no_more_results").html("<h6 style='color: #9c0a0d;'>No More Results</h6>"); this.empty_results = true; } else { $("table#recent thead").append("<tr style='color: #840a0c!important;'> <th>H1</th> <th>H2</th> <th class='text-center'>H3</th> <th class='text-center'>H4</th> <th class='text-right'>H5</th> <th class='text-right'>H6</th> </tr>"); console.log(analysis.length) data.forEach(function (analysis, i) this is the code where data is fetching and providing the data in form of table. Now what I have done. I have used the localstorage.setItem through ID in Index.html(1) Page <script> var table = document.getElementById("recent"); //var totalRowCount = table.rows.length; // 5 var tbodyRowCount = table.tBodies[0].rows.length; // 4 alert("total no of files are:" +tbodyRowCount) console.log(tbodyRowCount) //console.log(totalRowCount) </script> <script> var x = { count: [tbodyRowCount], //count: [totalRowCount] }; localStorage.setItem("tbodyRowCount", count) //localStorage.setItem("totalRowCount", count) //localStorage.getItem("tbodyRowCount") </script> Here is the code to create a table in index.html(1) <table id="recent" class="table table-striped table-responsive recent_table"> <thead ></thead> <tbody ></tbody> <tfoot ></tfoot> </table> Here is the code to fetch data in index.html(2) where I am calling the data on Doughnut Chart <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script type="text/javascript" src="https://unpkg.com/chart.js-plugin-labels-dv/dist/chartjs- plugin-labels.min.js"></script> <!--<srcipt src = "https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin- datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></srcipt> --> <script> var tcount = … -
Organise selection from cache only (no database hit is permitted)
Django==4.0.5 django-cachalot==2.5.1 Model: class General_Paragraph(models.Model): treaty = models.ForeignKey('treaties.Treaty', on_delete=models.PROTECT, db_index=True) identifier = models.CharField(max_length=100, blank=False, null=False, db_index=True, unique=True) Cash warming: @admin.action(description='Warm cache up') def warm_up(modeladmin, request, queryset): MODELS_AND_APPS = { ... "General_Paragraph": "paragraphs_of_treaties", ... } for model_name in MODELS_AND_APPS: current_model = apps.get_model(app_label=MODELS_AND_APPS[model_name], model_name=model_name) all_instances = current_model.objects.all() list(all_instances) # The very warming the cache up. Problematic code: def get_texts_in_languages(treaty, paragraph_identifier, party): general_paragraph = General_Paragraph.objects.get(treaty=treaty, identifier=paragraph_identifier) SQL: SELECT ••• FROM "paragraphs_of_treaties_general_paragraph" WHERE ("paragraphs_of_treaties_general_paragraph"."identifier" = 'Par 1' AND "paragraphs_of_treaties_general_paragraph"."treaty_id" = 1) LIMIT 21 What I need I use Memcached. As this is reading, I don't want any reading from the database. Everything should be requested from the cache. As far as I have understood, .objects.get(treaty=treaty, identifier=paragraph_identifier) will not be covered by Django Cachalot. Could you help me write a code that will not hit the database. Any warming ups of the cache are possible. I have enough resourses at my hosting. My problem is that I can't understand what to do: whether some elegant query is possible here or I will have to loop over all the cache? -
NoReverseMatch: Reverse for '' with arguments '('',)' not found
I'm trying to pass the intern's id through the django url but this error is occurring. Internal Server Error: /partiu-estagio/dashboard Traceback (most recent call last): File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\SEC\codigoWeb\DesenvolvimentoSec\sistemaSec\home\views.py", line 61, in dashboard_partiu_estagio return render(request, 'home/PAES_dashboard.html',dados) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 312, in render return nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit … -
Django app with Memcached using Dockerfile only
I need to add memcached in my Django app, I tried the same with docker-compose but I don't want to use docker-compose, instead I need to use Dockerfile. Is there anyway for it -
Unable to create process
I updated my python version and when I try to run server on prompt for django I get this error. Unable to create process using 'C:\Users\ALFRED\AppData\Local\Programs\Python\Python311\python.exe manage.py runserver': The system cannot find the file specified. -
Activating virtual env
I made a virtual environment ,I can activate it in command prompt, but it doesn't activate with my_venv2\Scripts\activate.bat and I cant activate it in pycharm's terminal -
How to exclude drf router path from drf_spectacular SERVERS setting
I would like to verify some best practices when using drf_spectacular with a django project. I have an API in a django project where all the endpoints use the api/ prefix, i.e. in urls.py, I'm using. path('api/', include('myapp_api.urls')), The myapp_api project'ss urls.py uses the default router, so something like router = routers.DefaultRouter() router.register(r'assets', views.AssetsViewSet) By default, this means that the swagger docs will present all the endpoints as something like... /api/assets/{}/ instead of /assets{}/ This of itself isn't a big deal because the swagger UI's test calls will work just fine because it will correctly call https://example.com/api/assets{}/. It just looks a bit messy in SwaggerUI. The main problem arises when I set the OpenAPI server object, which for drf_spectacular is the SERVERS setting, e.g. SPECTACULAR_SETTINGS = { 'SERVERS': [{'url': 'https://example.com/api'}], } At which point I have failure because the Swagger test calls will try and request to https://example.com/api/api/assets/{}/ and will still show the /api/ prefix on all the endpoints. I seem to have two options: I could go to my urls.py and use path('', include('myapp_api.urls')) instead of path('api/', include('myapp_api.urls')) but that's not desirable because the prefixing seems to make sense in this context. I could use a drf_spectacular preprocessing hook … -
error ModuleNotFoundError in django for python
Why am I getting this error? I know my code has bugs So help me My error : File "C:\Users\emanull\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'current_datetime' my code : link github -
Reduce by -1 & display as new instance every time
Trying to build a member ship system where an admin clicks on the button (Reduce) and the sessions field (Reduces -1 and shows the data & date reduced) every time a swimmer comes through. Thank You VIEWS.PY @api_view(['POST']) def swimmersReduce(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) MODELS.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.IntegerField(blank=True, null=True) dateofpayment = models.CharField(max_length=200, blank=True) -
What is the use of class Meta in django?
I have been using django and used class Meta: a lot of times, actually what is the use of it? for example , In django models class Accounts(models.Model): ---some code here--- class Meta: ordering = [-1] In django forms class AccountForm(forms.ModelForm): ---some code here--- class Meta: fields = '__all__' -
Django transfer database to different Django project without messing up the logic
I built a django project with a few models. Now I created a second server with the same setup. This one is meant to be the deployment server. Databases are seperate from the dev-server. However can you tell me if I can simply copy the databases from the dev server to the deploy or will the django logic, since I also mean the user models and permissions etc. The tables wich I created myself are no problem to transfer to the new server. However I am wondering If django gets confuse when I also transfer something like the auth_user Model. Should this work since I also just copied the backend logic as well? -
How can i redirect to same page for certain routes in Django?
enter image description here i would like to restrict signup page after user is logged in so, if user is logged in then return back to same page -
GET data from database to Modal in Django
this file serivces.html has the code used to generate card elements with different id from thedb {% block content%} <div class="container-fluid p-lg-5 d-flex justify-content-lg-around flex-wrap "> {% for package in packages %} <div class="card" style="width: 18rem; "> <div> <img class="cardimg" src="{% static '/images/genomic lab final logo1 ( RGB ).png'%}" class="card-img-top" alt="..."> </div> <div class="card-body"> <h3 class="text-center">{{package.package_name}} <span class="checkup text-center">Checkup</span></h3> <button type="button" class="modalbtn btn btn-primary" data-bs-toggle="modal" data-bs-target="#cardModal"> more details </button> </div> </div> {% endfor%} </div> <<!-- Modal --> <div class="modal fade content-data" id="cardModal" data-url="{%url 'Services_data'%}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{details.pkg_name}}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <H4>{{details.content}}</H4> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endblock %} this is the view.py contain def services(request): packages = Packages.objects.all() context = {'packages':packages} return render(request, 'base/Services.html',context) class AjaxHandlerView(View): def get(self,request,*args, **kwargs): if request.is_ajax(): details = Details.object.all() details_serializers = serializers.serializer('json',details) return JsonResponse(details_serializers,safe=False) return JsonResponse({'message':'Errrorr'}) and this is the base.js contain the ajax code $(document).ready(function(){ $(".modalbtn").on('click',function(){ $.ajax({ url: "{% url 'Services_data' %}", type:'GET', datatype: 'json', success: function(){ $('#cardModal').modal("show"); }, error:function() {console.log('Errorrrr'); } }); }); }); Basically, this code generates cards with different id and when click on … -
Wagtail add thumbnail image to PageChooserPanel
How is it possible to customize the explorer/list view of the PageChooserPanel? I would love to add a thumbnail image here to make life easier for the editors. Their task is to pick out a few dozen artworks (pages) from a large archive. A preview image (and possibly a few additional columns) would greatly simplify this work. I am aware of the get_admin_display_title of a Page as mentioned here. How about a custom version of the PageChooserPanel? I found the AdminPageChooser widget in there, but did not understand how the table of the explorer view is rendered finally. Not sure if it is necessary to get into the weeds to this extend. Would love to see a simple hook like the ModelAdmin list view with its ThumbnailMixin. # wagtail/admin/panels.py from wagtail.admin.widgets import AdminPageChooser class PageChooserPanel(FieldPanel): # ... def get_form_options(self): opts = super().get_form_options() if self.page_type or self.can_choose_root: widgets = opts.setdefault("widgets", {}) widgets[self.field_name] = AdminPageChooser( target_models=self.page_type, can_choose_root=self.can_choose_root ) return opts -
Saving django data field into another field of same table
Adding + 10 to (session field) and trying to save the data into (totalsession field),So that totalsession display on a table in the frontend in a new raw everytime the button is clicked. THANK YOU VIEWS.PY @api_view(['POST']) def swimmersReduce(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) MODELS.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.IntegerField(blank=True, null=True) dateofpayment = models.CharField(max_length=200, blank=True)