Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly render a Multiplechoice ModelForm in Django
So I have two models, one to store categories and their related color and another one to store the categories selected by a user like so: # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) I now want to render out a MultipleSelectWidget so that the user can select categories to use as a filter. # Form class SelectCategoryForm(forms.ModelForm): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Category exclude = ["poller_category", "category_color"] How can I now render all of the categories and their associated color in the template? My below loop doesn't render any (Note: the form is passed to the context, if I use {{ select_form }} it renders the default one) # Template <!-- Filter form --> <div class="filter-form-wrapper"> <form method="post" action="."> {% csrf_token %} <div id="form-wrapper"> <ul> {% for item in filter_form %} <li style="color: {{ item.category_color }}">{{ item.poller_category }}</li> {% endfor %} </ul> <button class="save-button" type="submit">Save</button> </div> </form> </div> -
Django - Facebook ads (panel and targeted ads)
I would like to setup my web application so that users (businesses or other type of account) can run ads for the users (normal users) as Facebook based on user's interests, what approach should I take? Thanks! -
Django test parallel with 1 DB
I am trying to run my tests in parallel using manage.py test --parallel. By default this will use a different DB for each thread. Each process gets its own database Is it possible to only use one? Also is it a bad practice and why? -
How to loop in excel row with xlwt and django?
Here I am trying to export some report of customers in the excel format using xlwt. While exporting I am getting issue while rendering related products of customer. The current response I am getting is: The response I want is : response = HttpResponse(content_type="application/ms-excel") response["Content-Disposition"] = 'attachment; filename="report_detail.xls"' wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet(f"Report Detail", cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ "Customer ID", "Products"] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) rows = [] for obj in qs: rows.append(obj.customer_id) prods = [(p.name, p.code) for p in obj.products.all()] rows.append(", ".join(map(str, prods))) for i, e in enumerate(rows, start=2): ws.write(int(i / 2), int(i) % 2, e) wb.save(response) return response -
Setting up a Test environment
I have currently dockerised my django+springboot application(development) and deployed in a remote server(Digital ocean). For testing purposes, I have cloned the applications and deployed at different ports. But the functionalities working in development server are getting reflected in Test server. Would like to know the general practice in cloning a development server for a test server -
How to lock the default choice without giving any options in DJANGO
I've been working with a model with has one the field as a choice field and multiple choices are provided. For eg-> The gender field is a choice field where users can choose from a drop down menu. But in a certain case, I only want the form to be open to female candidates, so the choices won't be shown, and the field will automatically be set as 'female' in the backend. How can I do this? Here are the code snippets from my code -> // models.py class RegisterUser(models.Model): GENDER_CHOICES= ( ( constants.MALE, constants.MALE_STR, ), (constants.FEMALE, constants.FEMALE_STR), ( constants.OTHERS, constants.OTHERS_STR, ), ) name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) college = models.CharField(max_length=100) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=constants.MALE ) // form.py class RegsiterForm(forms.Form): gender = forms.ChoiceField( label="Select Gender (default is Male)", widget=forms.Select( attrs={"class": "form-control", "placeholder": "Select Gender"} ), choices=GENDER_CHOICES, ) // views.py @login_required def publish_app_without_apk(request, **kwargs): template_name = "registerform.html" context = {} if request.method == "POST": form = form_class(request.POST) if form.is_valid(): name = form.cleaned_data.get("name") age = request.POST.get("age") college = request.POST.get("college") gender = request.POST.get("gender") -
What is the Best Way To Sync Multiple Database Table To Online Database using rest api
I have a software which store data in local sql server in multiple tables Want To give sync button and call api and transfer the data from local to live Software are install in multiple systems so it can happen data can transfer at same time what techniques i can use . So Server will not lack -
Django - Heroku - debug error 500 when deleting an object in Prod
Problem: Server Error 500 when trying to delete a user account in Prod. Scenarios: Delete a user account in Dev - works fine Create a user account in Prod - works fine Delete a user account in Prod - error 500 view.py: @login_required def account_destroy_view(request, id=None, *args, **kwargs): try: obj = request.user except request.user.DoesNotExist: raise Http404 if request.method == "POST": try: customer = StripeRecord.objects.get(user_id=obj.id) stripe.api_key = config('STRIPE_API_KEY') stripe.Customer.delete(customer.stripe_customer_id) except StripeRecord.DoesNotExist: pass obj.delete() return redirect("/") return render(request, "accounts/delete.html", {"object": obj}) accounts model.py: class User(AbstractUser): date_time = models.DateTimeField(default=datetime.datetime.now()) stripe model.py: User = settings.AUTH_USER_MODEL class StripeRecord(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... Heroku log: Sep 23 19:37:37 weatherapp app/web.1 10.1.24.136 - - [24/Sep/2021:02:37:36 +0000] "POST /delete/ HTTP/1.1" 500 145 "https://www.weatherapp.com/delete/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52" What I've tried & questions: I've checked Stripe logs, the object has been deleted on Stripe. So the issue isn't on the Stripe env var or integration. Tried to delete a user account directly using Django admin tool in Prod - still error 500. I suspect it's because I created the model with AbstractUser and it is a foreignkey to another model? How to get more details on the … -
HTML inserting extra characters into URL
I'm creating an ebay style website that auctions off items. I have a form that takes in the values for the listing required by the model. The form renders well but when I submit the form I get the error: <class 'TypeError'> views.py 80 ("l = Listing(title=title, description=description, url=url, user=user_id, category=category)") forms.py class NewListingForm(forms.Form): title = forms.CharField(max_length=200) description = forms.CharField(max_length=500) url = forms.URLField() bid = forms.DecimalField(decimal_places=2, max_digits=10) category = forms.ModelChoiceField(queryset=Category.objects.all()) views.py ** added around line that's throwing the error def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category = newListingForm.cleaned_data['category'] current_user = request.user user_id = current_user.id **l = Listing(title=title, description=description, url=url, user=user_id, category=category)** l.save() b = Bid(price=bid, bid_count=0) b.listing.add(l) b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) newListingForm = NewListingForm() return render(request, 'auctions/newListing.html', { 'form': newListingForm }) models.py class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() user = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = … -
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?