Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do three functions by one submit button with only one form document?
I'm having a problem to call multiple functions on one click submit button. I have one form which user need to attach one file (exls document), and I need one document to use for 3 functions. I need to save document, do some pandas stuff and I need to show it in html. Can I do this by putting it in class or something? I really need help for this, thanks in advance. def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff for … -
Use a queryset to display two filtered data in django?
I have a table Documents and it has a field named type and the type has two data's namely - type1 & type2 Now my requirements is - i have a bootstrap tabs type1 & type2, and i need to display data accordingly on the template Which is efficient way to do this ? Using two variables data = Documents.objects.filter(id=pk) type1 = data.filter(type="type1") type2 = data.filter(type="type2") and then pass it to context context = { "type1":type1,"type2":type2 } Is there any other best way to do this ? -
How to add an event with JavaScript when a button is clicked
I've uploaded a similar question in a previous post, but I'm re-posting because what I'm trying to achieve is a little clearer. We are outputting the list of students as a table. If we check the checkbox and click the Add Teacher button, we want the name of the currently logged in teacher to be added to the teacher field of the selected row. You can get the name of the currently logged in account with {{request.user.name}} . And I want it to be saved in DB by sending it to the server. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Techer" class="addtecher"> urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) edited_student, errors = Student.student_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) student.name= edited_student.name student.age = edited_student.age student.register_date … -
Django queryset group by and count for related fields
I have this models with this relations class Product(models.Model): code = models.CharField( _("Code"), max_length=50, unique=True ) name = models.CharField( _("Name"), max_length=150 ) class ProductOption(models.Model): product = models.ForeignKey(Product, verbose_name=_("Product"), on_delete=models.CASCADE, related_name='options') vtype = models.CharField(_("Type"), max_length=50) text = models.CharField(_("Text"), max_length=50) With this example data prod1 = Product(code='1', name='Name 1') ProductOption(product=prod1, vtype='Color', text='Blue') ProductOption(product=prod1, vtype='Size', text='M') ProductOption(product=prod1, vtype='Material', text='Cotton') prod2 = Product(code='2', name='Name 2') ProductOption(product=prod2, vtype='Color', text='Red') ProductOption(product=prod2, vtype='Size', text='X') ProductOption(product=prod2, vtype='Material', text='Cotton') prod3 = Product(code='3', name='Name 3') ProductOption(product=prod3, vtype='Color', text='Red') ProductOption(product=prod3, vtype='Size', text='L') ProductOption(product=prod3, vtype='Material', text='Cotton') How can I build a query with the ORM with this result [ {'vtype': 'Color', 'text': 'Blue', 'count': 1}, {'vtype': 'Color', 'text': 'Red', 'count': 2}, {'vtype': 'Size', 'text': 'M', 'count': 1}, {'vtype': 'Size', 'text': 'X', 'count': 1}, {'vtype': 'Size', 'text': 'L', 'count': 1}, {'vtype': 'Material', 'text': 'Cotton', 'count': 3}, ] I test a lot of options like using Concat, and Count but I fail. -
Upload contacts from my phone into a Django app
I am creating a django app and one of the functionalities I would like to add is that, if I want, I can upload into my app contacts that I have on my iphone. Basically the flow I would like to create is that if a user lands on the page on it's mobile phone and click on "upload", the app opens the user's contact list and the use can select the contact or contacts he would like to upload. How can I do it? -
How to connect Django Api with iOS (Swift) app?
I have tried researching how to connect my Django API in my ios swift app. My goal is to create a web app and an ios app in order to do it I have created an API with Django but I'm totally new to ios development and I'm trying to connect and authenticate users with my API, I'm trying to use Alamofire in swift. Any books or references ? or examples of functions, Thanks a million. -
DRF Sum values in a JSONFIELD field
I need to return totals from a table (Mysql), but one of the fields is JSONFIELD, with the key value to be added. Testing as below I get the following error: the JSON object must be str, bytes or bytearray, not float JSONFIELD { "repasse_descontos": [ { "nome": "Taxa Administrativa 1º Aluguel", "valor": 175 }, { "nome": "pintura", "valor": 200 } ] } VIEWSET def get_queryset(self): _qs = (Alugueis.objects .filter(ver='s') .values('proprietario') .annotate( total_vcto = Sum('vcto_valor'), total_pagto = Sum('pagto_valor'), total_repasse = Sum('repasse_pagto_valor'), total_descontos = Sum('repasse_descontos__valor') ) .order_by('proprietario') ) return _qs -
How to prevent query >>> on table being loaded? Django Table
I have the current code in my django app to populate a Table with data from a postgres db. It is populating correctly with the following code but seems to be putting > for each item from the table above like a query. Any assistance to get this resolved would be greatly appreciated. Here is the image as well Screenshot of table being displayed with >>>> Thank you in advance for any assistance to get this resolved. All other parts of the DTL is working as designed. <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Call Time</th> <th>Reservation Number</th> <th>Stage Name</th> <th>Update Call</th> </tr> </thead> {% for Call_Note in object_list %} <tr> <th>{{ Call_Note.id }}</th>> <td>{{ Call_Note.call_time }}</td> <td>{{ Call_Note.reservation_number }}</td> <td>{{ Call_Note.stage_name }}</td> <td><a href="/calls/{{ Call_Note.id }}">Modify Call</a></td> </tr> {% endfor %} </tbody> </table> -
django import excel file with multi sheets
hello everyone please I have a concern for using Django’s Tablib module to load an excel file that contains multiple sheets. I don’t know how to retrieve a specific sheet -
Updating Django packages conflict?
I am trying to update my Django from 3.1.12 to 3.2.7 , I have other packages in my projects, Now on updating to the newer versions some of packages starting giving error. Also not sure which one is giving error -
Django or Firebase for a small project
I am a beginner and looking forward to start freelancing with flutter. And I am wondering whether or not is Firebase better than Django for small projects that doesn't require alot of users concerning the price as firebase is alot easier than django -
Best way to connect Django Query results to Chart.js charts?
Can someone advise what is the cleanest/easyest way to connect my query to the Data/Label part of chart.js script? Thank you in advance. -
How to update a single item in a list from the template in Django?
I am looking for the best way to make an updateable list from model objects in Django. Let's say that I have a models.py: class Foo(models.Model): bar = models.CharField(max_length=10, blank=True) foo = models.CharField(max_length=30, blank=True) and I have a views.py that shows the objects from that model: def my_view(request): person_list = Person.objects.all() ctx= {'person_list': person_list} return render(request, 'my_app/my_view.html', ctx) Then I have a template, my_view.html: ... <table> <tr> <th>bar</th> <th>foo</th> <th></th> </tr> {% for item in person_list %} <tr> <td>{{item.bar}}</td> <td>{{item.foo}}</td> <td style="width: 5%;"><button type="submit" name="button">Change</button></td> </tr> {% endfor %} </table> ... So, I would like to add a form and make one of those fields changeable from within this template. I would like users to be able to change item.foo and then click the change button and it sends the update to the model. I tried making it a form, and using forms.py to create a form where users can put an input, and then submit the form, and that looked like this, my_view.html: ... ... <table> <tr> <th>bar</th> <th>foo</th> <th></th> </tr> {% for item in person_list %} <form method="post"> {% csrf_token %} <tr> <td>{{item.bar}}</td> <td>{{item.foo}}</td> <td>{{form.foo}}</td> <td style="width: 5%;"><button type="submit" name="button">Change</button></td> </tr> </form> {% endfor %} </table> ... ... … -
Filter foreign key objects in django template
I have the following model which is used to "archive" a post (i.e if it is created for a post by a user, that post is now hidden from that user) models.py class ArchivedFlag(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='archived_commits') post = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name='archived_flag') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='archives') In a particular template, I want logic based on whether an ArchivedFlag exists for both the current user's group and the current post being examined. template.html {% for p in posts %} <form action="{% url 'archive_commit' c.oid %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.get_full_path }}"> {% if <...an archived flag exists with post==post and group==user.group...> %} <...Do stuff for archived post...> <button type="submit", name="c_oid", value="{{ c.oid }}", class="btn btn-primary btn-sm">Restore</button> {% else %} <...do stuff for unarchived post...> <button type="submit", name="c_oid", value="{{ c.oid }}", class="btn btn-primary btn-sm">Archive</button> {% endif %} </form> {% endfor %} Is there any way to do this in a django template? I can't find any information on filtering in a template so perhaps this is not possible. -
include more than one image inside a TextField
How can I include more than one image inside a TextField in blog posts ? like that : main article_title : article_name 1 article_picture 1 article_desc 1 article_name 2 article_picture 2 article_desc 2 article_name 3 article_picture 3 article_desc 3 All in one article . this is my models: class Categorie (models.Model): class Meta : verbose_name_plural = 'Categorie' title = models.CharField(max_length=50) def __str__(self): return self.title class blog (models.Model): class Meta : verbose_name_plural = 'blog' ordering = ['article_created_at'] category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True) article_slug = models.SlugField(blank=True,allow_unicode=True,editable=True) article_title = models.CharField(max_length=200 , null=True) article_name = models.CharField(max_length=200 , null=True ) article_picture = models.ImageField(upload_to='img_post' , null=True) article_desc = models.TextField(null=True) article_created_at = models.DateField(auto_now_add=True) article_updated_at = models.DateField(auto_now=True) article_auther = models.CharField(max_length=200 , null=True) def save(self , *args , **kwargs): if not self.article_slug: self.article_slug = slugify(self.article_name) super(blog , self).save( *args , **kwargs) def __str__(self): return self.article_title this is my views : from django.shortcuts import render from . import models from .models import blog , Categorie def blog_index(requset): posts = blog.objects.all().order_by('-article_updated_at') context = { 'posts':posts, } return render( requset , 'blog/blog.html' , context) -
How can I build a query that will return objects that hold more than one specific foreign key?
class People(models.Model); name = models.CharField() surname = models.CharField() class Votes(models.Model): value = models.CharField() people = models.ForeignKey(People) I would like to write a query that will return a queryset of people who have more than one vote(how many foreign keys of Votes has People) . how can I achieve this? -
How to store Persian character using Jesanfield in dajngo?
I tried to store Persian characters with Jesanfield, but I had the following problem when displaying characters in the database. "{'\u0628\u0631\u0646\u062f}" models: from django.contrib.postgres.fields import JSONField class example(models.Model): spec_json = JSONField(null=True, blank=True) enter image description here -
How to combine the Django WebSockets "websocket_urlpatterns" (path) of multiple apps in the Project URLRouter?
I have multiple apps and they all are using the "WebSockets (routing.py)", and I have routing.py in my project and apps. I can only add the "websocket_urlpatterns" of single app in my URLRouter, if I try to add the other "websocket_urlpatterns" in the URLRouter, it didn't worked and I get the error. Project routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import django_chatter.routing import app1.routing import os from time import sleep os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( app1.routing.websocket_urlpatterns # send request to chatter's urls ) ) }) App1 routing.py from django.urls import path from django_chatter import consumers import app1.consumers websocket_urlpatterns = [ path('ws/route1/' , app1.consumers.Consumer1.as_asgi()), path('ws/route2/' , app2.consumers.Consumer2.as_asgi()), path('ws/route3/' , app3.consumers.Consumer3.as_asgi()), ] App2 routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chatter/chatrooms/<str:room_uuid>/', consumers.ChatConsumer.as_asgi()), path('ws/chatter/users/<str:username>/', consumers.AlertConsumer.as_asgi()) ] -
How to get an input field in javascript by rendering a form using django render to string?
Here is my issue and I have been trying for 2 days to understand what is my code doing? I have a django model form which is rendered to a modal an ajax call. Here is the model and the form. class CreateSagaForm(forms.ModelForm): class Meta: model = Saga fields = "__all__" widgets = { "end_date": forms.DateInput(attrs={"class": "datepicker"}), "start_date": forms.DateInput(attrs={"class": "datepicker"}), } def __init__(self, *args, disabled_field=True, **kwargs): super(CreateSagaForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "CreateSagaForm" self.helper.layout = Layout( "epic_key", Row( Column("epic_status", css_class="form-group col-md-3 mb-0"), Column( "start_date", HTML("""<i class="fa fa-calendar" ></i>"""), css_class="form-group col-md-4 mb-0", ), Column( "end_date", HTML("""<i class="fa fa-calendar" ></i>"""), css_class="form-group col-md-4 mb-0 text-center", ), ), the models.py class Saga(models.Model): start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) the view that render the data of the modal through the ajax. def get_form(request, key_epic): instance = get_object_or_404(Saga, epic_key=key_epic) JsonInstance = serializers.serialize( "json", [ instance, ], use_natural_foreign_keys=True, use_natural_primary_keys=True, ) form = CreateSagaForm(request.POST or None, instance=instance) context = {"form": form} template = render_to_string("tracking/get-form.html", context, request=request) return JsonResponse( { "sagaForm": template, "instance": JsonInstance, } ) the ajax call epic_keys.forEach(epic => { epic.addEventListener('click', () => { var epicKey = epic.textContent; url = `/api-sagaForm/${epicKey}/` var formLocal = document.querySelector(".sagaFormLocal"); $.ajax({ url: … -
Is it possible to input data into another table using the create function within the classview(django crv)?
Is it possible to input data into another table using the create function within the classview? A unique failed error occurred when using the create function for this part class createSkilNoteForInsertMode(LoginRequiredMixin,CreateView): model = MyShortCut form_class = SkilNoteForm def get_template_names(self): return ['skilnote1/myshortcut_summernote_form.html'] def form_valid(self, form): type_list = Type.objects.all() if not type_list: Type.objects.create(type_name="summer_note") Type.objects.create(type_name="textarea") Type.objects.create(type_name="input") Type.objects.create(type_name="image") else: ty = type_list.get(type_name="summer_note") ms = form.save(commit=False) ms.author = self.request.user ms.type= ty ms.created = timezone.now() category_id = self.request.user.profile.selected_category_id ca = Category.objects.get(id=category_id) ms.category = ca profile = Profile.objects.filter(Q(user=self.request.user)).update(last_updated = datetime.now(), last_updated_category = ca.name) # In this part, how do I add data to the HistoryForUpdate model of the accounts2 app? # A unique failed error occurred when using the create function for this part return super().form_valid(form) -
Django search query in JSON data
If the searched query is in my JSON data, I want to show that product. views.py query = request.GET.get('search') if query: product_list = product_list.filter( Q(product_name__icontains=query) | Q(brand__brand_name__icontains=query) | Q(model__name__icontains=query) | Q(gtin_no__icontains=query) | Q(oem_no__icontains=query) | Q(tag__icontains=query) ) models.py product_name = models.CharField(max_length=300) slug = models.SlugField(unique=True, editable=False, max_length=300) category = models.ForeignKey('ProductCategory', null=False, on_delete=models.CASCADE, max_length=100) brand = models.ManyToManyField('Brand', null=True, max_length=100) model = JSONField(null=True, max_length=10000) product_code = models.CharField(blank=True, max_length=20) gtin_no = JSONField(blank=True, max_length=10000) oem_no = JSONField(blank=True, null=True, max_length=10000) tag = JSONField(blank=True, null=True, max_length=10000, default=None) Example model JSON data: { "data": "[['Car Parts', 'Ssangyong'], ['Industrial Parts', 'Lombardini'], ['Mercedes-Benz Sprinter', 'Sprinter OM 601, OM 602 DE LA']]" } Example GTIN JSON data: { "data": [ "4047755219970" ] } Example OEM JSON data: { "data": [ "624 320 0028", "625 320 0028" ] } Sometimes this JSON data can be empty. { "data": [ "None" ] } -
Django - How to get image field of ForeignKey query elements?
I have the following code at views.py to sort TvShows by there latest released episode (release_date) within 90 days: def tv_show_by_set_just_released(request): latest_episodes = TvShows.objects.filter(episode_show_relation__release_date__gte=now() - datetime.timedelta(days=90)) ... For each element found, I now also want to display a cover. But the cover is located at a different table and I don't really know how to pull it out probably in this query context. In the end I want to display the very first TvShowSeasons.cover for each element of my query from above. Is it somehow possible to marry these two elements, latest_episodes and TvShowSeasons.cover to display them properly at a template? Please also see models.py class TvShows(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre') date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) class TvShowSeasons(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='season_show_relation') season_number = models.IntegerField(verbose_name=_("Season Number"), blank=True, null=True, editable=False) cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images) total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True) rating = models.CharField(verbose_name=_("Rating"), blank=True, null=True, editable=False, max_length=255) copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) Thanks in advance -
Problem with Django Tests and Trigram Similarity
I have a Django application that executes a full-text-search on a database. The view that executes this query is my search_view (I'm ommiting some parts for the sake of simplicity). It just retrieve the results of the search on my Post model and send to the template: def search_view(request): posts = m.Post.objects.all() query = request.GET.get('q') search_query = SearchQuery(query, config='english') qs = Post.objects.annotate( rank=SearchRank(F('vector_column'), search_query) + TrigramSimilarity('post_title', query) ).filter(rank__gte=0.15).order_by('-rank'), 15 ) context = { results = qs } return render(request, 'core/search.html', context) The application is working just fine. The problem is with a test I created. Here is my tests.py: class SearchViewTests(TestCase): def test_search_without_results(self): """ If the user's query did not retrieve anything show him a message informing that """ response = self.client.get(reverse('core:search') + '?q=eksjeispowjskdjies') self.assertEqual(response.status_code, 200) self.assertContains(response.content, "We didn\'t find anything on our database. We\'re sorry") This test raises an ProgrammingError exception: django.db.utils.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...plainto_tsquery('english'::regconfig, 'eksjeispowjskdjies')) + SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I understand very well this exception, 'cause I got it sometimes. The SIMILARITY function in Postgres accepts two arguments, and both need to be of … -
How to generate dynamic rows in page based on the response of the js request? (Django Template / HTML)
Is this possible to append the rows with data in an HTML table as a response of the JavaScript request without doing a page postback? Django: 3.1.7 I want to write a seprate HTML file (Like a file we can use with include tag) for the code so I don't have to append the html of entire table in the HTML string. For now I am appending the HTML by converting to the string concatination. Note: Need a solution without page postback. function GetCollection(myId) { var Urlgetallcom = "/sc/GetCollection/" + myId ; // alert(Urlgetallcom); $.ajax({ url: Urlgetallcom, // the endpoint type: "GET", // http method data: { Id: myId }, // handle a successful response success: function (json1) { var Collection = json1; console.log(Collection); for (var i = 0; i < Collection.length; i++) { $('#Comments_Div').append( '<div class="mt-comments" style="border-bottom: 1px solid #eef1f5">' + '<div class="mt-comment">' + '<div class="mt-comment-info">' + '<div class="mt-list-item done mt-comment-info" onclick="ShowCommentInfoWindow(' + Collection[i].f.latitude + ',' + Collection[i].f.longitude + ',\'' + Collection[i].f.commentDetails + '\')">' + '<div id="' + Collection[i].pk + '" class="mt-comment-details" style="display:block">' + '<span>' + Collection[i].f.commentDetails + ' </span>' + '<div class="mt-comment-actions ">' + '</div>' + '<br />' + '</div>' + '<div class="mt-comment-body">' + '<div class="mt-comment-details">' + '<span … -
Django form how do I make 2 drop box search result depending on how first one is selected?
I am trying to make form consist of two dropbox using query from model. so first dropbox get all distinct store name from Menu table and that part, I got it working. However, how do I make second dropbox filter result depending on what I pick on first dropbox? For example, If I pick store A for first dropbox, it shows sa, sb, sc as menu name and if I pick store B for first dropbox, it shows ma, mb, mc as menu name and so on. Also, second dropbox can have 2 filter condition like storename + day. How can I accomplish this? forms.py class MenuForm(forms.ModelForm): store_name = forms.ModelChoiceField(queryset=Menu.objects.distinct('store_name')) menu_name = forms.ModelChoiceField(queryset=Menu.objects.filter(??)) class Meta: model = Menu fields = {'store_name', 'menu_name'}