Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filters: BaseInFilter with a different separator
I'm wanting to be able split text on a value other than a comma within django-filters. I'm currently using django-filter along with a BaseInFilter to allow searching for multiple integer values in a model. This filter separates values based on a comma, and I can't seem to override the function that splits the values. It is likely that I'm misunderstanding where this split is happening. I have tried to override this method in the class BaseCSVWidget def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if value is not None: if value == '': # empty value should parse as an empty list return [] return value.split(',') return None by placing it in my filter with a different separator: class PidnInFilter(BaseInFilter, NumberFilter): def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if value is not None: if value == '': # empty value should parse as an empty list return [] return value.split(' ') return None I've also tried creating my own widget class and overriding there: from django_filters.widgets import BaseCSVWidget class MyWidget(BaseCSVWidget): def value_from_datadict(self, data, files, name): print('value_from_datadict reached') print(data) value = super().value_from_datadict(data, files, name) print(value) if value is not None: if value == '': # empty … -
Django Office365 email Authentication unsuccessfu
I am trying to setup a Django email sending but if fires me authenication error: My mail is godaddy with office365. this is my settings: EMAIL_HOST = 'smtp.office365.com' EMAIL_USE_SSL = False EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@my.....com' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER But it fires me the following error once I try to send an email: -
check permissions before perform_create() method applied
I need to check different types of permissions for different types of actions from request user. For example get permission only need [IsAuthenticated] but when user request perform_create method. I want to implement another permission that is CanCreateProject permissions.py class CanCreateProject(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.user.is_superuser: return True else: return request.user.profile_limitation.can_create_project views.py class ProjectView(ModelViewSet): serializer_class = ProjectSerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = Project.objects.all() organization = self.request.user.organization query_set = queryset.filter(organization=organization) return query_set def perform_create(self, serializer): self.permission_classes = [CanCreateProject] ## here project = self.request.data["project_name"] path = self.request.data["project_name"] organization = self.request.data["organization"] serializer.save(project_name=project, project_path=path, organization=organization) How can I run the CanCreateProject method only for perform_create method is requested. -
Database inconsistency between Python and Apache Kafka
So I am using Apache Kafka with Python and Postgres database. I have a model named ImportResultDetail with a foreign key to another model called ImportResult. I create an ImportResult object which is saved to the database, and send its pk as part of a message to the Kafka Producer. When consuming, I try to create an ImportResultDetail object with a fk to that ImportResult object that was created before, but somehow I get an error stating that the said object doesn't exist in the database (although it is there). Below is the stack trace and database entry to better illustrate. Anyone got this kind of problem before, and is aware of said inconsistency and how to fix it? Stack trace Proof that the item exists in db -
How to make a recursive ManyToMany relationship symmetrical with Django
I have read the Django Docs regarding symmetrical=True. I have also read this question asking the same question for an older version of Django but the following code is not working as the Django docs describe. # people.models from django.db import models class Person(models.Model): name = models.CharField(max_length=255) friends = models.ManyToManyField("self", through='Friendship', symmetrical=True, ) def __str__(self): return self.name class Friendship(models.Model): personA = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personA') personB = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personB') start = models.DateField(null=True, blank=True) end = models.DateField(null=True, blank=True) def __str__(self): return ' and '.join([str(self.personA), str(self.personB)]) If bill and ted are friends, I would expect bill.friends.all() to included ted, and ted.friends.all() to include bill. This is not what happens. bill's query includes ted, but ted's query does not include bill. >>> from people.models import Person, Friendship >>> bill = Person(name='bill') >>> bill.save() >>> ted = Person(name='ted') >>> ted.save() >>> bill_and_ted = Friendship(personA=bill, personB=ted) >>> bill_and_ted.save() >>> bill.friends.all() <QuerySet [<Person: ted>]> >>> ted.friends.all() <QuerySet []> >>> ted.refresh_from_db() >>> ted.friends.all() <QuerySet []> >>> ted = Person.objects.get(name='ted') >>> ted.friends.all() <QuerySet []> Is this a bug or am I misunderstanding something? -
django how to filter import_export file
How do i filter the CustomerSectionResource models? in my case all data save in the database export in the excel, I just want to select certain data to export in excel. i want to filter just like this Ex. company = FmCustomerUsers.objects.filter(user=request.user.id) obj = FmCustomerSection.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) how? help me guys.... resources.py class FmCustomerSectionResource(resources.ModelResource): fmCustomerID = fields.Field(attribute='customer', column_name='customer', widget=ForeignKeyWidget(FmCustomer)) class Meta: model = FmCustomerSection fields = ('fmCustomerID', 'section', 'inputdate', 'inputBy', 'modifyDate', 'modifyBy', 'status') views.py from tablib import Dataset from .resources import FmCustomerSectionResource def import_Section(request): if request.method == 'POST': file_format = request.POST['file-format'] company = FmCustomerUsers.objects.filter(user=request.user.id) product_resource = FmCustomerSectionResource.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) dataset = Dataset() new_city = request.FILES['importData'] if file_format == 'XLS': imported_data = dataset.load(new_city.read(), format='xls') result = product_resource.import_data(dataset, dry_run=True) elif file_format == 'CSV': imported_data = dataset.load(new_city.read(), format='csv') # Testing data import result = product_resource.import_data(dataset, dry_run=True) if not result.has_errors(): # Import now product_resource.import_data(dataset, dry_run=False) return redirect('Section') def export_Section(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['importData'] product_resource = FmCustomerSectionResource() dataset = product_resource.export() if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'XLS': response = HttpResponse(dataset.xls, content_type='application/xls') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return redirect('Section') -
Pagination in django API
I need help I am fetching movie data from the movie database so far everything good with the responses. But I am stack on the pagination Because it only returns 20 objects. And I want to return the other results when clicking on pagination buttons. I have tried many ways But the only thing I can achieve is to return the results by passing the parameters in the URL ej. ?page=2 returns another 20 objects ?page=3 returns 20 more objects.And I want to do that but with pagination buttons. I tried using Django pagination but it does not work as it only returns objects from my database and not API. Here is my code in views. Also I am using a small library that I found on github but it does not have a documentation. My code Here: def peliculasPopulares(request): tmdb = TMDb() tmdb.language = 'es' tmdb.api_key = 'my-api' movie = Movie() page = request.GET.get('page') popular = movie.popular(page) return render(request, 'peliculas/populares.html', { 'title': 'populares', 'populares': popular }) -
Page Not Found/No Comment Matches The Given Query
Hi guys i'm a beginner and creating a blog site with comments but after i hit submit it says "No Comment Matches The Given Query" pagenotfound post_create.html views.py post_detail.html urls.py models.py -
Django, How to close DB connection manually to avoid resource occupancy
My Django command has the following features: First, get 1 MyItem from DB. Some processes take a very long time. Finally, save the result in the DB. from django.core.management.base import BaseCommand from my_app.models import MyItem, Result class Command(BaseCommand): def handle(self, id, *args, **kwargs): # Step1. my_item = MyItem.objects.get(id) ## TODO: close DB connection manually. # Step2. # Some processes take a very long time. # Step3. ## TODO: open DB connection manually if needed. Result.objects.bulk_create(results, batch_size=1000) Therefore, I want to release DB Connection after getting MyItem in step 1 for other processing. And I want to open the DB again in step 3. How do I explicitly close the DB Connection? -
How can I use django translation for ES6 template literals?
Is there a way to use the translation for template literals. Here is my code: var x = `<div>Are you sure you want to download ${post_or_comment}?</div>`; I know I could do: var x = '<div>'+gettext('Are you sure you want to download ')+post_or_comment+'?</div>'; But, I think its not the way because, it will be messy for lots of similar situation. -
Custom Template tag setvar scope issue
I created an custom_template_tag.py as this: from django import template register = template.Library() @register.simple_tag def setvar(val=None): return val now in my template I am looping through db and getting the correct data, but when I am trying to use my set variable outside of for loop I get nothing {% for personLiked in Post.likes.filter %} {% if request.user.id == personLiked.id %} {% setvar "True" as is_liked %} {{is_liked}} <--------GETTING VALUE HERE {% endif %} {% endfor %} {{is_liked}} <--------NOT GETTING VALUE HERE Not sure what I am missing since I believe this should be available to the rest of the page. Any suggestions? -
How to solve NOT NULL constraint with django ForeignKey?
As I am new to django I am getting this NOT NULL constraint with django's model ForeignKey. I am trying to add the User as a foreign key to the table Offer my models.py from django.conf import settings class Offer(models.Model): item = models.CharField(max_length=100) stock = models.IntegerField() discount = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) this is how I save it in views.py offer = Offer(item=item,stock=stock,discount=discount) offer.save() How do I solve this -
how i do a filter by url in django in a View and Urls ? similar to this "my_url/sales?filter=date_sale eq 2020-06-20"
I need to filter by date Ex:2020-06-20 or this 2020-06-20 until 2020-06-20 or any date of the user put in request by url and try View class AllMayerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Vendas.objects.filter(cod_cliente=541) serializer_class = VendasSerializer Urls router = routers.SimpleRouter() router.register(r'541/dsadasdas', AllMayerViewSet) urlpatterns = [ url(r'', include(router.urls)), ] Model class Vendas(models.Model): data_venda = models.DateField(db_column='DATA_VENDA') First post!!! -
I have a question about django models. I was creating a django model in visual studio code. It suggested me below code when I type charfield
class message(medels.Model): messageBody= models.CharField(_(""), max_length=1000) In this code what is _("") this? My IDE suggested me that. Please help me to understand it. -
Can I create an (Java/PHP) application that can connect to sqlite3 in django?
Can I create an application (Java/PHP) that can connect to sqlite3 in django? -
Remove anchor name from Django HttpResponseRedirect or redirect
I don't know if it's a bug or a feature, but when I'm on my home page with the contact form anchor (url = http://localhost:8000/#contact) After submitting the form, all of these will redirect including the #contact anchor name and I cannot get rid of it: from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import redirect # Following 3 lines all send back to http://localhost:8000/#contact return HttpResponseRedirect(reverse('homepage')) return redirect(reverse('homepage')) return redirect('/') # As a test, the following line redirects to http://localhost:8000/account/email/#contact return HttpResponseRedirect(reverse('account:email')) I found some people with the opposite issue, trying to add the anchor name, but can't find a related question with my issue -
How to add a Context `OrderItem` to appear in PDF file from Django Admin
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} I even tried removing the forloop but still nothing happened Ordered on: {{order.ordered_date}} <----------Showing {{ order_item.item.title }} <----------Not Showing -
How to multiply fields in Django ModelForm?
I am trying to multiply the price and quantity fields from my modelForm to create a total_value field. I would like the value to populate after the user inputs a value for price and quantity. I have tried creating functions in the model to carry out the multiplication, however, I do not understand how to post the data in the template. Sorry I am very new to programming. Below are the links to my code. forms.py models.py views.py template.html -
filtering relational models inside django forms
i have a model which has a foreign key relation with two oder models one of them is 'level'. the view knows in which level you are based on a session variable, and then filter the lessons this is the lesson model: class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) now this is my cbv to create a new lesson: class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') and this is the form: class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set one of the main conditions is to filter level by a session variable but the form does not accept request.session so is there any way … -
Downloading PDF files from Django Admin returning UnboundLocalError at /admin/order/(48\d+)/pdf/
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that when I have click on the PDF link in the Admin it returns UnboundLocalError at /admin/order/(48\d+)/pdf/ local variable 'Order' referenced before assignment It is the first time to face this error and I am trying to figure out how to fix it, however know exactly where to look. Here is the views which is the reason for the error @staff_member_required def admin_order_pdf(request, order_id): Order = get_object_or_404(order, id=order_id)<-------------- the order model is showing error html = render_to_string('order/pdf.html', {'order': Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is the admin def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('core:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', 'user', ........, order_pdf] Here is the urls.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Would really appreciate help in figuring this one out. -
Django : Several paths, one ListView, different templates?
Please help me. I want to have multiple path in urls.py (lets say a, and b). But I want to ONLY have one ListView, and this ListView need to channel me to different html file when I access the url (a.html when access 'a/', b.html when access 'b/'). Currently I use different ListView for each path (aListView and bListView), even though the model is the same. But it seems that it violate the Don't Repeat Yourself rule. And the code looks bad. So the question is how can I define several different templates in one ListView? Below is my current mind map. Thank you My mind route -
Sending .py -> .html value to .js (Django, Mapbox)
Below is my code in my main.html file: <body> <h1>mappymappy</h1> <div id='map'></div> <script> mapboxgl.accessToken = '{{ mapbox_access_token }}' var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [-73.9911, 40.7051], zoom: 9.5 }) </script> {% for center in drop_in_centers %} <script> new mapboxgl.Marker({ "color": 'red' }) .setLngLat([{{ center.longitude }}, {{ center.latitude }}]) .setPopup(new mapboxgl.Popup({ offset: 25 }) .setHTML("<h2>Drop-in Center</h2><h3>{{center.center_name}}</h3>")) .addTo(map) </script> {% endfor %} I want to move the scripts to a separate .js file. However, in order to do that I have to figure out a way to send the values mapbox_access_token and drop_in_centers to .js file and make the values able to be used in the .js file. How can I do this? +) both mapbox_access_token and drop_in_centers are from views.py file. -
Extending path name in urls.py
Supposed my views.py contain multiple views that are meant to go deeper in the url path. urlpatterns = [ path('<int:table_pk>/order/', views.menu_category_view, name='menu_category_view'), path('<str:menu_category>/', views.menu_item_view, name='menu_item_view'), ] The first view has the path generated as <int:table_pk>/order/. If I want the second view to have a path as following <int:table_pk>/order/<str:menu_category>/, how should i go about passing the variables (in the view and/or template) in DRY manner? What if I have more path levels that need to extend the path above it in this same manner? -
How can I return display values for all selected fields and field names in QuerySet?
I have a Django view that passes templated data to an html page as json. The issue I am having is that the actual database fields and fieldnames are passed instead of the human-readable name and result of get_FOO_display(), respectively. For clarity, here is what my model looks like: class FooBar(models.Model): name = models.CharField('Name', max_length=255) AWAITING_CLASSIFICATION_STATUS = 1 IN_PROGRESS_STATUS = 2 AWAITING_REVIEW_STATUS = 3 CLOSED_STATUS = 4 STATUS_CHOICES = [ (AWAITING_CLASSIFICATION_STATUS, 'Awaiting Classification'), (IN_PROGRESS_STATUS, 'In Progress'), (AWAITING_REVIEW_STATUS, 'Awaiting Review'), (CLOSED_STATUS, 'Closed') ] status = models.IntegerField('Status', choices=STATUS_CHOICES, default=AWAITING_CLASSIFICATION_STATUS) And my view currently: def IndexView(request): foo_list = FooBar.objects.all().values() json_list = json.dumps(list(foo_list)) context = {'foo_list': json_list} return render(request, 'foo-app/index.html', context) And what my data should look like: [ {'Name': "name1", "Status": "Awaiting Classification"}, {'Name': "name2", "Status": "In Progress"}, ] Some ideas I have explored: Iterating over the list and looking up each based on the model (sounds like a lot of extra processing server side). Sending the QuerySet in its entirety and processing it client side (I think this would include more data than I would like to reveal to the client). Storing the data in the database in human readable form (nope). What is the most Pythonic/Djangonic way of doing this? -
User authorization via login does not work
I try to log in, but I get the error: "'str' object is not callable". What can happen? from django.contrib.auth import login, authenticate login="eeiguomfug" pas="B6AFQJTK" user = authenticate(username=login, password=pas) login(request, user)