Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add a Progress Bar on a Django Application
I am currently building a web application using Django, and I need to add a page that shows progress bars for several different processes. For each of the processes, I need the progress bar to update 1% after 1,000 (the number is arbitrary) iterations. I have never used AJAX before, and I am not sure where to look or if there is even a way to implement what I am trying to do. My thought process is that the best way to go about this is to run an asynchronous function in Python and then communicate the progress somehow to the JavaScript which will then update the progress bars. Are there any good resources to figure out something like this? -
Django API After login get information about user
class LoginAPI(KnoxLoginView): permission_classes = [permissions.IsAuthenticated,] def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] Organizationss=Organization.objects.filter(owner_id__exact=request.user.id).values('UserInformation') Organizationss_name=[Organization.objects.filter(id=a['UserInformation']).values('name','type') for a in Organizationss] login(request, user) temp_list=super(LoginAPI, self).post(request, format=None) # print([a for a in projects]) temp_list.data["Organization"]=Organizationss_name # print(temp_list.data return Response({"data":temp_list.data}) This is my serializer , when i login it's return this information every users , i want to return only this users which is in Test Organization. i try Organizationss=Organization.objects.filter(owner_id__exact=request.user.id).values('UserInformation') but not working , what is best idea ? "data": { "expiry": "2022-02-24T01:01:07.773585Z", "token": "a6c19c30569a69a42a7cfae665123a4399c09710879d470b0a1f7440f8864691", "Organization": [ [ { "name": "Test", "type": "Test" } ] ] } -
Using same modal to Add/Edit DataTable row content
I've been struggling to get this code working I hope you can help me! I basically have a Django website in which in the page I'm doing right now I have a DataTable with my customers information. I have a button on the top to Add a new Customer and the table rows can be clicked to edit the corresponding customer data. In both cases a modal (#clientModal), the same one, is shown. I have almost everything working, since it was working fine when I used multiple pages insted of in-page modals. Everything works as it should, when I click a table row to edit some customer's info the modal form is populated but when I click the form's save button it creates a new object instead of updating the corresponding one. Any help will be appreciated, thanks! -- customerList.html <!-- Clients DataTable --> <div class="card shadow mb-4"> <div class="card-body"> <form action="{% url 'CustomerBulkAction'%}" method="POST">{% csrf_token %} <div class="table-responsive"> <table class="table table-bordered" id="customerTable" width="100%" cellspacing="0"> <thead> <tr> <th data-orderable="false"> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="checkAll" value="option1"> <label class="form-check-label" for="checkAll">Selecionar Todos</label> </div> </th> <th>Nome</th> <th>NIF</th> <th>Por pagar</th> <th>Pago</th> </tr> </thead> <tbody> {% for c in customers %} <tr class='clickable-row' data-pid='{{c.id}}'> … -
Passing "context" back to view Django
I'm using an API (Spotify) to receive search results (Playlists and their data....Name,Url,Owner,Description) and displaying them on my website. I could just directly print out the results to the website in an HTML table, however I need to perform Regex to get values out of the description(Email or Instagram if provided). I created a PlaylistObject class to store each returned playlist result, as well as my regexs to find an email and username. I do not store this value in the database because it's temporary and doesn't need to be saved for long term. The problem I am having is with Pagination. The way I have the program set up, it has to recall the Spotify API function call that gets the search and assigns it to my list of PlaylistObjects every single time the page reloads. Because of pagination, it reloads every time the page is changed. The pagination is working and the program functions "as intended", but I know there has to be a better approach. I send the list of playlists through context dictionary and then read them in the html to a table, if the was a way to send that same exact playlist list back … -
django anchor app based html to project based html
I have a base.html file in my project/templates file and I try to anchor link an app based html file to it. I get the following error: Reverse for 'tcm_home' not found. 'tcm:tcm_home' is not a valid view function or pattern name. The tcm_home.html file is my "tcm" app html and inherits from base.html file What I did/tried: named my_app = 'tcm' in my urls.py file in tcm app linked my project based templates directory to BASE_DIR checked if the tcm-home.html (app based) inherits from base.html (project based) {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/png" href="{% static 'tcm/cover.png' %}" /> <title>HEAT TRANSFER SITE</title> </head> <body style="background-color: aqua;"> <h1 style=" color:darkblue">THIS IS IT!</h1> <h1><a href="{% url 'tcm:tcm_home' %}"></a>goto TCM</h1> {% block content %} {% endblock %} </body> </html> -
Django does not run when the django-admin code is entered
When I try to run the program, the following code runs: DNS server not authoritative for zone. -
Prevent django from replacing quote marks with html
I have a django form like which displays a number of radiobuttons and I need to submit a request on click. The needs to be submited on click, but since there is a second jQuery widget, I'm trying to extract its current value on submit to package along with the request. When trying to extract the value from the additional widget django replaces quote marks in attrs with html characters which prevents it from working. I have tried enclosing the form and additional widget in {% autoescape off %} tags, as well as rendering the form manually and using safe i.e. {{ field|safe }}. However django continues to automatically replace quotes. How can I stop this from happening? class ChloroplethIonSelectForm(forms.Form): choices = [ (str(i)+'_'+str(j),'mz ='+ str(i)+ 'rt = '+str(j)) for i, j in Data.objects.all().distinct('mz').values_list('mz',"rt_min" )] ion = forms.CharField(label = "Select an ion and a date", widget=forms.RadioSelect( choices = choices,attrs={'onclick': "$('#id_date') = $('#amount').val(); this.form.submit();"} )) date = forms.CharField(max_length=10, widget = forms.HiddenInput()) formtype = forms.CharField(initial = 'chloroplethion', widget=forms.HiddenInput()) <form action="" method="post"> {% autoescape off %} {% csrf_token %} <p> <label for="amount">Date range:</label> <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" size="10" /> </p> {% block choropleth_sliders %} {% endblock choropleth_sliders %} … -
Django Como gerar Lorem Ipsum por view [Dica]
Como gerar Lorem Ipsum por View no Django Tutorial de como gerar Lorem Ipsum por View no Django -
DjangoModelPermissions ignore my added permissions
I have a problem with DjangoModelPermissions. It works fine with standard permissions but not with permissions I added to the Meta of my model. Example: class MarketingImage(MarketingMediaAbstract): image = models.ImageField(_('Marketing image'), upload_to="marketing/images/") machine = models.ForeignKey("machine.Machine", verbose_name = _("machine"), related_name="marketing_image_machine", on_delete=models.CASCADE) class Meta: verbose_name = _("Marketing Image") verbose_name_plural = _("Marketing Images") permissions = [('change_marketingmedia', 'Can change Marketing Media'), ('delete_marketingmedia', 'Can delete Marketing Media'), ('add_marketingmedia', 'Can add Marketing Media'), ('view_marketingmedia', 'Can view Marketing Media')] When I migrated this object, 4 permissions were created: view_marketingimage add_marketingimage change_marketingimage delete_marketingimage When I use permission_classes = [DjangoModelPermission], it's works with *_marketingimage but not with *_marketingmedia *_marketingmedia are ignored. How do I get DjangoModelPermission to work with the permissions I added? -
Django template detailed view of object
I am wondering how to do so that after creating a new object, a page with the details of the given object is automatically created. Of course, the page according to the template. I have a list of objects owned by the user and a "details" button next to each object. I would like this button to take you to the details page of this object. -
Django show table and/or download file with one api call
I have a function that take user input, make an API call and then show a table. I also manage to make the same function that take user input, make an API call and let the user download the data. Separately, it does work. How can I make both available at the same time. If button "show data", -> show data. If data already shown, and if "download button", -> download the file. If data not yet shown and if "download button", -> show the data and download the file. Can I do that with only one API call per user input? here is view.py def data(request): if request.method == "POST": address = request.POST["adresse"] ... (go get some data) (df = data) geek = df.to_html() context = {'loaded_data': geek} #DOWNLOAD DATA import csv from django.http import HttpResponse if 'btnform2' in request.POST: response = HttpResponse( content_type='text/csv' ) df.to_csv(path_or_buf=response,sep=';',float_format='%.2f',index=True,decimal=",") #return response #return HttpResponse(geek) return render(request, "data.html", context) Can I do that without redundant api call? -
Django filter based on SerializerMethodField
I have a similar type of code provided below. serializer.py class FooSerailizer(BaseModelSerializer): value = serializers.SerializerMethodField(read_only=True) def get_value(self,obj): # some statement of code # return statement class meta: model = Foo fields = '__all__' filters.py class FooFilter(filters.FilterSet): class meta: model = models.Foo fields = '__all__' The API request is http://127.0.0.1:8000/api/?value=some_value. The response I am getting when I am calling the above API: { "value": [ "Select a valid choice. That choice is not one of the available choices." ] } How to get the JSON response correctly? -
Django, propagate exceptions to DjangoRestFramework
I'm using Django and DjangoRestFramework for my project and I'm facing some kind of "issue". While DRF exceptions are properly returned through the response of the HTTP request, Django ones aren't. For instance if I raise an IntegrityError from the Django part with, for instance, a duplicate key error (let's say I create 2 records with same unique primary key), I only get a "500 Server Error" in the response of my HTTP request. How can we propagate exceptions from Django to DRF by default ? With an appropriate HTTP status code ? The only way I found is to write a custom exception handler for DRF which tests the exception type like so : if isinstance(my_exception, IntegrityError): # Do some custom thing on the Response object before returning it -
Unable to use Case, When, Then in django queryset
my models are as follows class Loan(models.Model): loan_value = models.IntegerField() channel_seller = models.ForeignKey(ChannelSeller, on_delete=models.CASCADE) class ChannelSeller(models.Model): LEVEL_CHOICES = ( ('1','Business Consultants'), ('2','Unit Managers'), ('3','Account Managers'), ('4','Branch Managers'), ) level = models.CharField(max_length=2, choices = LEVEL_CHOICES, null = True, blank = True) pin_no = models.CharField(max_length=255) unit_manager = models.ForeignKey('self', limit_choices_to = {"level": '2'}, on_delete=models.DO_NOTHING, null = True, blank = True, related_name='unit_manager_2') Loan can be created by business_consultant or unit_manager. Each business_consultant will have a unit_manager, however, unit_manager will have unit_manager as blank with that said, I'm trying to sort my query by unit_manager field using case, when, then as follows transactions = Loan.objects.annotate(unit_manager_pin = Case(When('channel_seller__level' == '2', then='channel_seller_pin_no'), When('channel_seller__level' == '1', then='channel_seller__unit_manager__pin_no'))).filter(channel_seller__level__in = ['1','2']).order_by('channel_seller__level') This query however throws me error __init__() takes either a Q object or lookups as keyword arguments -
Django views and template tags
I have an app that request an input from a user and after the validation it's querying the database for a match, i did it in my html using if and for loop to match the string, but now i did a function to generate a pdf in my views. The question is how can i access my results from html and get it in my pdf instead of query again to match the results? def getting_games(request): form = GamesForm(request.POST or None) queryset = Games.objects.all() if form.is_valid(): searched = request.POST['game_number'] queryset = Games.objects.filter(game_number__iexact=searched).values() ctx = {'form': form, 'queryset': queryset } return render(request, 'results.html', ctx) context = { 'form': form } return render(request, "base.html", context) -
How to render specific json response data fields on frontend web using django
I am using django with templates and trying to send my json response data to the frontend web page. But in the frontend ui i want to show only specific fields of the json response data which i am unable to figure out. Right now i can send the complete json response data and show it in the frontend web page. Here is my code details - This function connects to my backend index and gets each document from index and appends it to jsonitems dictionary. def sampledata(request): samplecount = requests.get(sampleindex + "/_count", auth=auth, verify=sslcheck) print(samplecount.json()['count']) count = samplecount.json()['count'] jsonitems = {} for item in range(count): data = requests.get(sampleindex + "/_doc/" + str(item), auth=auth, verify=sslcheck) jsondata = data.json() jsonitems[item] = jsondata print(jsonitems) context = {'jsonitems': jsonitems} return render(request, 'samplewebapp/sampledata.html', context) This is the template view which i am using to render on the frontend web ui. {% if jsonitems %} <ul> {% for k, v in jsonitems.items %} <table> <tr><th> Sample data Item </th></tr> <tr> <td>{{ v }}</td> </tr> </table> {% endfor %} </ul> {% else %} <p>No CVE data available</p> {% endif %} Currently table data 'v' (ie value) shows the complete json data. But i want to show … -
How can I show quiz questions one by one using Django and HTML?
I have a set of quiz questions on my database. and I have created a html page. I want to show the quiz taker questions one by one. After s/he clicks next only then the next question should be shown.How can I do that only using HTML and Django? -
django views many-to-many relationship field problem
During work on my 1st app(kind of cookery book where it will be possible also to create meal plans) i have a problem to addapt one field from many-to-many(through) model to my html template. Field name is 'meal' in RecipeMealPlan model. Here are my models: class Recipe(models.Model): title = models.CharField(max_length=50) cooking_time = models.IntegerField(help_text='in minutes', validators=[MinValueValidator(1), MaxValueValidator(5000)]) difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') meal_plan = models.ManyToManyField('MealPlan', through='RecipeMealPlan') class RecipeMealPlan(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) meal_plan = models.ForeignKey('MealPlan', on_delete=models.CASCADE) meal = models.IntegerField(choices=MEALS) MEALS = ( (1, 'Breakfast'), (2, '2nd breakfast'), (3, 'Lunch'), (4, 'Snack'), (5, 'Dinner') ) class MealPlan(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(validators=[MinValueValidator(4), MaxValueValidator(6)]) Here is my view created to show mealplan details on my app: class MealPlanDetailsView(View): def get(self, request, id): mealplan = MealPlan.objects.get(id=id) recipes = mealplan.recipe_set.all() return render(request, 'diet_app/mealplan_details.html', {'mealplan': mealplan, 'recipes': recipes}) And html template: {% extends 'diet_app/base.html' %} {% block title %}{{ mealplan|upper }}{% endblock %} {% block content %} <h2>{{ mealplan|upper }}</h2> <ul> <p>Posiłki:</p> {% for recipe in mealplan.recipemealplan_set.all %} <li>{{ recipe.get_meal_display}}: <a href="/recipe/{{recipe.id}}/">{{ recipe }}</a></li> {% endfor %} </ul> {% endblock %} Everything looks fine but link to receipe details doestnt work: … -
Get timezones with utc offset
is there a module or public API that given the UTC offset returns a list of all timezones in that offset ? For example given UTC+2 it returns the following list: Africa/Blantyre Africa/Bujumbura Africa/Cairo Africa/Gaborone Africa/Harare Africa/Johannesburg Africa/Juba Africa/Khartoum Africa/Kigali Africa/Lubumbashi Africa/Lusaka Africa/Maputo Africa/Maseru Africa/Mbabane Africa/Tripoli Africa/Windhoek Asia/Amman Asia/Beirut Asia/Damascus Asia/Famagusta Asia/Gaza Asia/Hebron Asia/Jerusalem Asia/Nicosia Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kaliningrad Europe/Kiev Europe/Mariehamn Europe/Riga Europe/Sofia Europe/Tallinn Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye -
What should happen to the data when disabling an app in django?
I have a django app "my_debug" that contains a model like this: class MyDebugEntry(Model): user = ForeignKey(User, on_delete=CASCADE) data = TextField() This app is only for debugging purposes, so I add it to INSTALLED_APPS when I need it and remove it afterwards. This works fine for the most part. However, when I try to remove a user I get the following error message: IntegrityError at /some/path/ update or delete on table "auth_users" violates foreign key constraint "mydebug_mydebugentry_user_id_d738bc03_fk_users_" on table "mydebug_mydebugentry" DETAIL: Key (id)=(5) is still referenced from table "mydebug_mydebugentry". This is because on_delete=CASCADE is implemented in python, not in the database itself. So when the "my_debug" app is disabled, the on_deleted behavior is disabled along with it. So what is the proper way to do this? Should I drop all of the app's tables when removing it from INSTALLED_APPS? -
What will Max return from an empty record?
what will the max return if particular customer has no order__id, below is the code in views.py in django, queryset = Customer.objects.annotate(last_order_id=Max('order__id')) screenshot of the table -
Django-fsm, what am I missing?
I'm starting to wonder what is the point of django-fsm? I am working on a production management system. As an example, a transition from state INCEPTED (details being entered) to states IN_PRODUCTION (being manufactured) or RESOURCE_WAIT (some necessary input entity is not yet available). Establishing the details involves querying a considerable number of different models, and might come to involve asking questions of the user. It seems unnatural to attempt to put querysets on other models into the model containing the state field. (It's causing me a circular import problem as well, which I don't know how to resolve). So, I have written this transaction as a view instead, which also means that I can display a list of checks which were made, and their success/fail status. The issue of making sure that the transition is fully committed or not committed is easily handled via with transaction.atomic() so if anything goes wrong, nothing is committed to the DB. Which leaves me wondering what I am missing. Why does django-fsm exist? It doesn't seem to fit into what I am trying to accomplish. Too low-level, or .... -
Send missed notifications to a client when webscoket connection is made
I am developing a chat application with django channels. But I have a problem. How can I make client application sync with the server. If the client application disconnect and reconnect it will lose the changes. How can I make the client application synced with the server. Sorry for bad english. -
How to use django-filter and django-mptt in template?
I want to use these third apps together in my template. But it doesn't work. I don't know why it is. Individually they work well, but when I tried to build its together it doesn't work. I tried to use recursetree and |tree_info but it also doen't work. I will be happy if you help me. It took a long time to me. template.html <form method="get"> <label for="{{ filter.form.subject.id_for_label }}" class="form-label">Subject:</label> {% for su,structure in subject|tree_info %} {% if structure.new_level %}<ul> <li>{% else %}</li> <li>{% endif %} {{filter.form.su }} {% for level in structure.closed_levels %}</li> </ul>{% endfor %} {% if filter.form.su.errors %} <div class="alert alert-warning" role="alert"> {% for error in filter.form.su.errors %} {{error}} {% endfor %} </div> {% endif %} {% if filter.form.su.help_text%} <div class="form-text ms-2">{{filter.form.su.help_text}}</div> {% endif %} {% endfor %} </div> <button type="submit">Search</button> </form> {% for article in filter.qs %} <div class="bg-light d-flex flex-column flex-wrap"> <a href="{{ article.get_absolute_url }}">{{ article.title|safe }}</a> <a href="{{ article.author.profile.get_absolute_url }}">{{ article.author.get_full_name|default:article.author.username }}</a> <p><strong>Abstract:</strong> {{ article.abstract|safe|truncatewords_html:25 }}</p> <p class="align-self-end"><i class="fas fa-eye"></i> {% get_hit_count for article %}<br> <i class="far fa-arrow-alt-circle-down"></i>500 </p> </div> {% endfor %} models.py class Subject(MPTTModel): name = models.CharField( max_length=100, unique=True, verbose_name=_("category name"), help_text=_("format: required, max-100"), ) slug = models.SlugField( max_length=150, null=False, unique=False, … -
Connection timed out when trying to send an email using the send_mail method
I am having trouble when it comes to sending emails using the send_mail method from the django.core.mail module. The contents of the project email settings are as follows. # --snip-- # Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mukukachilu@gmail.com' EMAIL_HOST_PASSWORD = 'myfakepassword' EMAIL_PORT = 587 EMAIL_USE_TLS = False EMAIL_USE_SSL = False # --snip-- This is what I am doing in the Django shell. Python 3.9.7 (default, Sep 10 2021, 14:59:43) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> from django.congf import settings >>> send_mail('Test Subject', 'Test message', settings.EMAIL_HOST_USER, ['c.mukuka@makeitworkds.com'], fail_silently=False) After the send_mail method hangs for a long time, I am getting this Traceback below. Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.9/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.9/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.9/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File …