Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically access modules in django
I'm trying to dynamically access modules in django apps. I'm expecting that some apps contains the file foobar.py or a folder called foobar which contains more files. I've tried to access modules the following way. python manage.py shell from django import apps # accessing an app called account config = apps.app_configs['account'] module = config.module dir(module) But when I'm trying to do it that way only admin, forms and models are visible. No other modules inside the account app is visible. Is there a better way? -
Trouble With Django Bootstrap Modals
I am using django-bootstrap-modal-forms in order to implement modal forms in my project. I have implemented them in such a way that launching the modals can be done from my base.html, and therefore can be done from every different page in my app. The modal successfully launches on all pages, posts on all pages, but on a few pages it returns the form with validation messages even though it did post successfully and there are no issues. This package does use two post requests in order to make the messages framework operate, but I don't understand how it could work on some pages and not on other when I seemingly have done the same exact thing. For example, I have a modal to Create Shipment. This displays validation errors (despite successfully posting) on the home screen of the app, but does work perfectly on the View Shipments page. If anyone could please help this is driving me insane. I notice that on the pages where it does not work, I get a broken pipe error in my terminal. I also notice that it seems it is attempting to post 3 times on pages that it does not work. Please see … -
How to use column name dynamically inside insert query in djnago
cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data) in above query I want to pass column name dynamically and %s which is inside values also not predefine that how many times it need to write so, how can I write my sql query according to my data which comes from html table in 2d array from?? -
Django DateTimeField no seconds
I'm struggling with one case - i would like to have a field in my datatimefield model, but without seconds etc. just YYYY-MM-DD HH:MM, I've been trying to do like this, but it doesn't work: schedule_time = models.DateTimeField(format(['%Y-%m-%d %H:%M']), auto_now_add=True) Could someone provide me solution on any example? I've also been looking for solutions there, but i haven't found anything that would help me. Regards. -
Django form selecting from another view
I currently have a model, 'Organisation' with a class based list view and detail view for the organisations. I'm now creating a form for a different model which has a foreign key of Organisation and currently a select box to choose the organisation. Rather than the select box however, I'd like to be able to click a link to the list view and then select an organisation's detail view and from here click a select button to add the specific organisation to the form. What's the best way to do this in Django? -
My Django-ajax Like Button is not working..?
I had tried several times to fix this but not successfull, likes count are all updating when I use the admin panel but not in html template.. views.py from common.decorators import ajax_required @ajax_required @login_required @require_POST def like_post(request): # image_id = get_object_or_404(Post, id=request.POST.get('id')) image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Post.objects.get(id=post_id) if action == 'like': image.likes.add(request.user) else: image.likes.remove(request.user) return JsonResponse({'status':'ok'}) except: pass return JsonResponse({'status':'error'}) post_view.html {% extends 'base.html' %} {% load static %} {% block title %}Users Posts{% endblock %} {% block content %} <div class="container-fluid"> <form method="post" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Post"> </form> </div> {% for post in posts %} <div class="w3-container w3-card w3-white w3-round w3-margin"><br> <img src="{% if post.user.profile.photo %} {{post.user.profile.photo.url}} {% else %}{% static 'img/user.png' %}{% endif %}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"> <span class="w3-right w3-opacity">{{ post.created }}</span> <h4>{{ post.user|title }}</h4><br> <hr class="w3-clear"> <p>{{ post.title }}</p> {% if post.image %} <div style="max-width:100%;height:auto;object-fit: cover;" class="img-fluid"> <img src="{{ post.image.url }}" class="img-fluid" style="max-width:100%;height:auto;object-fit: cover;"> </div> <p>{{ post.description }}</p> {% endif %} {% with total_likes=post.likes.count users_like=post.likes.all %} <div class="image-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_like %}un{% … -
Django: Filter querys using checkboxes
hello everybody in my django website I've got an HTML page where are listed the results based on the input of a User in the search form (that is located in the homepage). Then when I've got all of them listed I'd like the user to be able to add one more filter, that's why I added two checkbox in that page. Anyway I don't know how to make the page reload and show the results based on the checked box. I added some comment to the code in order to make you understand what I was trying to do. Hope someone could really help me, I don't know where to go Here is the HTML template of the reuslt page: {% if sp %} <div class="filtro"> <h3 style=text-align:center> FILTRI RICERCA </h3> <div class="form-check"> <label class="form-check-label" for="grid-check"> Band </label> <input class="form-check-input" type="checkbox" id="grid-check" name="band"><br/> <label class="form-check-label" for="grid-check"> Album </label> <input class="form-check-input" type="checkbox" id="grid2-check" name="album"> <input type="submit" name="try"> filtra </input> </div> </div> {% for k in sp %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if k.cover%} <img src= "{{k.cover.url}}" width="100%"> {%else%} <img src="static/search/images/no.jpg" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th colspan=2><h3>{{k.band}}</h3></th></tr> <tr><td> Disco: … -
Django: Bootstrap input group not rendering desired HTML/CSS with form
I'm relatively new to Django and having an issue with rendering a form as an input group in Bootstrap. The form is to add a message to a model for a chat. Here is what I am aiming for as an input group: Expected input group This can be achieved with the below HTML: <div class="input-group"> <div class="input-group-append"> <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span> </div> <textarea name="" class="form-control type_msg" placeholder="Type your message..."></textarea> <div class="input-group-append"> <span class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></span> </div> </div> Now using Django to include the form within the input group I am using the below: <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span> </div> <form method="post" action="."> {% csrf_token %} {{ form.content }} <div class="input-group-append"> <button class="send_btn" type="submit"><i class="fas fa-location-arrow"></i></button> </div> </form> </div> This is using the below forms.py: class JobMessageForm(ModelForm): content = forms.CharField(required=True, widget=forms.Textarea(attrs={ 'class': 'form-control type_msg', 'placeholder': 'Type your message...'}), label=False) class Meta: model = JobMessage fields = ('content',) This is giving me the below: Current input group Any help in achieving the expected output would be greatly appreciated! Let me know if any further info would help. -
Django ORM - Join many-to-many with through table
I have 3 models: Task: A task, can be assigned to many employees. AssignedUser: (Bridge table) Store employees assigned to tasks completed: Indicate whether the employee has done the assigned task yet. Employee: An employee, can work on many tasks. (Extends from Django's user model) class Task(models.Model): name = models.CharField(max_length=50) detail = models.TextField() employees = models.ManyToManyField('Employee', through='AssignedUser', related_name='tasks') class AssignedUser(models.Model): task = models.ForeignKey(task, on_delete=models.CASCADE) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) completed = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=False) If I want to select a task name and the assigned employee's username who hasn't done the task yet (completed=False) how can I do that with Django's ORM? Here's the equivalent SQL I wrote for the desired result which I have no idea how to achieve that with Django's ORM. SELECT t.name, u.username FROM appname_task t JOIN appname_assigneduser au ON (t.id = au.work_id AND au.completed = false) JOIN appname_employee ae ON (au.employee_id = ae.id) JOIN auth_user u ON (ae.user_id = u.id) -
Vega visualization - how to enable actions when using vega view
I am using vega charts in my django project. Until now I have uset the vegaEmbaded to show chart's on web page but now I would like to switch to vega view and I can't found anywhere how to enable actions when using vega view. This is my code with vegaEmbaded: `<script> var {{ c.ident }} = {{ c.jSon|safe }} var {{ c.ident }}_opt = { actions: true } vegaEmbed('#{{ c.ident }}', {{ c.ident }}, {{ c.ident }}_opt); vegaEmbed('#{{ c.ident }}', {{ c.ident }}); </script>` And this code with vega view: `<script> var vegaJson = {{ jSon|safe }}; var view = new vega.View(vega.parse(vegaJson)) .renderer('svg') .initialize('#chartDiv') .hover() .run(); window.onresize = function (event) { view.signal('width', event.target.innerWidth - 200) .signal('height', event.target.innerHeight - 450) .run('enter'); } </script>` Any idea how to enable actions when using vega view? actions in vegaEmbaded -
Django - how do I close a modal post pagination?
I have a page using Django pagination which is taking some time to load. I want to add a modal which pops up with a spinning icon to demonstrate something is happening while the next page is loaded. I am popping this modal using $(document).on('click','.page-link', function(){ $("#waitingSearchModal").modal('show'); }); This pops the modal fine. When I the results I loaded I want to close the modal which I'm trying to do using $(document).ready(function () { $("#waitingSearchModal").modal('hide'); }); This is generating the following error in the browser console TypeError: $(...).modal is not a function This also leaves the modal-backdrop in place which I've tried removing using $('div.modal-backdrop').removeClass('show') But this hasn't done anything. What have I got wrong? -
Django , admin css and js don't work , static point in wrong path
the css on my admin django app does not work , I am not sure what is the problem. Tried some fixes , they didn't help server { listen 80; server_name spartron.agency; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/romanhrybinchuk/telegram-messenger/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/home/romanhrybinchuk/telegram-messenger/MessageSEnder.sock; } } Settings : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I think that my nginx is not pointing to collect static files for some reason -
Django: Problems related Many-to-many relationships
code of models.py from django.db import models class a(models.Model): name=models.CharField(max_length=20) class b(models.Model): roll=models.IntegerField() a=models.ManyToManyField(a) Actually i'm learning Django.As i have defined a many-to-many relationship in b model with a model.I'm trying to do some experiment with these models so that i can get better understanding of many-to-many relationship. doing some experiments with my models in Django shell. In [1]: from payment.models import a,b In [2]: x=a(name="test") In [3]: x.save() In [4]: y=b(roll=4) In [5]: y.save() In [6]: y.a.add(x) In [13]: x=b.objects.filter(a__id=4) In [14]: x[0].a Out[14]: <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager at 0x6a833a60f0> In [15]: x[0].a.name In [16]: When i run x[0].a.name in shell it does not return anything why?Do we cannot access name attribute like this.How to know which objects of a model are in relation with y object of b model. -
Django Variables on HTML and Javascript with Serializers
The following code work fine for display Django variable on HTML. objectA is model objectBs is queryset VIEW context = { 'objectA': objectA, 'objectBs': objectBs, } HTML <table id="table1"> <thead> <tr> <th>Field1</th> <th>Field2</th> </tr> </thead> <tbody> {% for objectB in objectBs%} <tr> <td> {{ objectA.field1 }} </td> <td> {{ objectB.sub.field2 }} </td> </tr> {% endfor %} </tbody> I want to use the data on javascript then I change the code to following. VIEW context = { 'objectA': json.dumps(model_to_dict(objectA), 'objectBs': serializers.serialize('json', objectBs), } JAVASCRIPT var objectA_ = JSON.parse("{{objectA|escapejs}}") var objectBs_ = JSON.parse("{{objectBs|escapejs}}") After changed, the javascript variable work fine but the html not able to display using original django variable. Please advise the solution. Thanks. -
Show month name instead of month number in django model choice field
Column acct in table Adjustment contains month number. The following code gives a dropdown with month number (1,2,3) but I want month name (January, February, March) instead. month = forms.ModelChoiceField(queryset=Adjustment.objects.values_list('acct',flat=True).distinct(), empty_label=None) -
How to make SELECT from subquiry and JOIN with other table in Django ORM?
I'm trying to use the Django ORM for a task that need SELECT from subquiry and JOIN with other table. Models and SQL-query see below. Models class MonWork(models.Model): name = models.TextField('Monwork', null=True, blank=True) app_version = models.ForeignKey(AppVersion, verbose_name='Application version', on_delete=models.CASCADE, null=False, blank=False) class MonWorkCheck(models.Model): monwork = models.ForeignKey(MonWork, verbose_name='Monwork', on_delete=models.CASCADE) class MonWorkCheckProvider(models.Model): monworkcheck = models.ForeignKey(MonWorkCheck, verbose_name='Monwork check', on_delete=models.CASCADE) provider = models.ForeignKey(Provider, verbose_name='Provider', on_delete=models.CASCADE) status = models.SmallIntegerField('Work capacity', choices=STATUS_CHOICES, blank=True, default=STATUSES['up']) error_text = models.TextField('Error text', null=True, blank=True) SQL query SELECT monworks.id AS monwork_id, monworks.app_version_id, monworkcheck_id_latest, arm_monworkcheckprovider.provider_id, arm_monworkcheckprovider.status, arm_monworkcheckprovider.error_text FROM (SELECT arm_monwork.id, arm_monwork.app_version_id, MAX(arm_monworkcheck.id) AS monworkcheck_id_latest FROM arm_monwork LEFT JOIN arm_monworkcheck ON (arm_monwork.id = arm_monworkcheck.monwork_id) GROUP BY arm_monwork.id, arm_monwork.app_version_id) AS monworks LEFT JOIN arm_monworkcheckprovider ON (monworks.monworkcheck_id_latest = arm_monworkcheckprovider.monworkcheck_id) How to make this SQL in Django ORM? Interesting only one query to database without lists, chain() and etc. -
Django rest serializer last
this is my rest response: "srf": "1010-000-0275", "letturesrf": [ { "reading_date": "2019-12-13T17:27:53Z", "reading_value": "829621" }, { "reading_date": "2019-12-13T17:33:01Z", "reading_value": "829621" }, ] }, i want to have only the last reading and for srf and not all readings. my serializer: class LettureSerializer(serializers.ModelSerializer): class Meta: model = Letture fields = ('reading_date','reading_value') class LettureTabelle(serializers.ModelSerializer): letturesrf = LettureSerializer(many=True, read_only=True) class Meta: model = Contatore fields = ['srf','letturesrf'] view: class DateLettureViewSet(viewsets.ModelViewSet): serializer_class = LettureTabelle queryset = Contatore.objects.all() -
Flutter and django nested object problem in http post method
I follow below link to send nested object to django https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/ My classes are given: ''' class Chef(models.Model): address = models.CharField(max_length=200,default='SOME STRING') name = models.CharField(max_length=100,default='SOME STRING') email = models.CharField(max_length=100,default='SOME STRING') phoneNo = models.IntegerField(default=0) password = models.CharField(max_length=100,default='SOME STRING') class Package(models.Model): price = models.IntegerField(default=0) chef = models.ForeignKey(Chef, on_delete=models.CASCADE,related_name='package_set', null=True, blank=True) package_no=models.IntegerField(default=0) ''' The serializers are: ''' class Package_Serializer(serializers.ModelSerializer): class Meta: depth = 1 model = Package fields = '__all__' class chef_package_Serializer(serializers.ModelSerializer): package_set = Package_Serializer(many=True) class Meta: model = Chef fields = ('address', 'name', 'email', 'phoneNo', 'password', 'package_set') def create(self, validated_data): package_data = validated_data.pop('package_set') musician = Chef.objects.create(**validated_data) for album_data in package_data: Package.objects.create(chef=musician, **album_data) return musician ''' I use "Postman" to send data . { "address": "gg", "name": "dff", "email": "ggg", "phoneNo": 234, "password": "234", "package_set": [ { "price": 1500, "package_no": 1, "chef": { "address": "gg", "name": "dff", "email": "ggg", "phoneNo": 234, "password": "234" } } ] } The data saved but when I use flutter application ,the following error occurs E/flutter (21201): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List' is not a subtype of type 'String' in type cast The json serializable classes of flutter are @JsonSerializable() class Chef{ Chef( this.address, this.name, this.email, this.phoneNo, this.password, this.package_set ); final String address ; final String name ; … -
What is the cause of duplicate for forloop
I implemented a queryset that outputed friends of friend, in my template I used forloop to display the friends of friend of a user. My else tag "No friends" duplicate if there are two friends of friend of a user. I attached an image for a better understanding. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) friends = models.ManyToManyField('Profile', related_name='my_friends') all_friends = request.user.profile.friends.values_list('pk', flat=True) friends_of_friend = Profile.objects.filter(pk__in=all_friends) {% for data in profile_and_button_status %} #other codes here #Result of first template image {% for friend in data.0.friends.all %} {% if friend in friends_of_friend %} {{ friend }} {% else %} No friend {% endif %} {% endfor %} #Result of second template image {% for friend in friends_of_friend %} {% if friend in data.0.friends.all %} {{ friend }} {% else %} No friend {% endif %} {% endfor %} {% endfor %} -
RadioButton in django
I don't understand how to implement django interaction with RadioButton. In the file models.py I have the "room_status" object attribute. I want the browser page to display the rooms that will be selected in RadioButton. html <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary "> <input type="radio" name="options" id="option1" autocomplete="off" checked> All rooms! </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Men's rooms! </label> </div> How do I link my html to django? -
Django link table row to view
new to coding. I'm creating an inventory table'with the django framework. I'd like to be able to click on a table row (which is a part) that will then parse that row/part information to a detail view. from what I understand table rows are inline elements and inline elements are psuedo code which current HTML does not allow for an anchor tag to be thrown in (bad practice?) so I need to use some javascript. Currently, the inventory view shows when I use runserver (http://127.0.0.1:8000/inventory/) but clicking on any row does nothing. Here is what I have so far; inventory.html {% extends "base.html" %} {% block body %} <br> <table class="table table-hover"> <thead> <tr> <th>Part Number</th> <th>Description</th> <th>Location</th> <th>Supplier</th> <th>S.O.H</th> </tr> </thead> <tbody> {% for part in parts %} <!-- need to make these table rows link to their respective parts class="table_row" href="{{ selected_part.partnumber }}/detail">{{ selected_part.partnumber }}--> <tr data-href="{% url 'detail' part.pk %}"> <td>{{ part.pk }}</td> <td>{{ part.partnumber }}</td> <td>{{ part.description }}</td> <td>{{ part.location }}</td> <td>{{ part.supplier }}</td> <td>{{ part.stockonhand }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} urls.py from django.urls import path from .views import * urlpatterns = [ path('inventory/', inventory_list, name='inventory'), # URL path for inventory_list … -
ProgrammingError django postgresql on hosting
I installed postgresql on hosting and it gives an error although everything works fine on the local server -
Django unittest cases
I am trying to run all the management commands for test_db for static details. Have to run just before the test cases. Have to be run only once for all test cases. I've used setUpTestData but did not help me. Basically I wanna reduce the running time of all test cases. Thanks -
Calculating the 'most recently used' of a django ManyToMany relation
I have a simple Tag model that many other models have a ManyToMany relationship to. The requirement has come up to be able to query/show the most recently used Tags in the system, across all entities that have Tags. I can add a used_at attribute to the Tag model, and I could order on that. But obviously, the Tag model doesn't get modified when something else just references it, so an auto_now on that attribute won't help me. Without the use of a through model (which could have an auto_now_add on it), and without performing any invisible (non-django) magic directly in the DB with triggers, is there a sensible way to update the Tag's timestamp whenever a model is saved that references it? -
Django checkout form not valid, Page not found (404)
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, but when I try to proceed to checkout, for some reason, my checkout form is not displayed rather, it says: Page not found (404), i.e my form is not valid. I made sure that I have registered my models, and ran migrations. I printed out form.errors and it says: Not Found: /checkout/. What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): address_form = UserAddressForm(request.POST or None) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return HttpResponseRedirect('/') else: raise Http404 print(form.errors) context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My ursl.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'),