Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a nested object in separate models in Django?
I'm trying to save a nested object into two different tables in my Django app. I'm missing something because I get validation errors from the sub Model. The data in my events is not recognized and the serializer validation fails. Do I need to modify my serializer somehow or is there something wrong with my Models? I have these two Models: class Plan(models.Model): name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) Then I have these serializers for my Models: class PlanEventSerializer(serializers.ModelSerializer): class Meta: model = PlanEvent fields = '__all__' class PlanSerializer(serializers.ModelSerializer): events = PlanEventSerializer(many=True) class Meta: model = Plan fields = ('name', 'events') def create(self, validated_data): events_validated_data = validated_data.pop('events') plan = Plan.objects.create(**validated_data) plan_event_serializer = self.fields['events'] for p in events_validated_data: p['plan'] = plan events = plan_event_serializer.create(events_validated_data) return plan In my views.py I do this: class PlanView(APIView): permission_classes = [AllowAny,] serializer_class = PlanSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I try to save a Plan and the PlanEvent into their own table with this payload: { "name": "some name", "events": [ { "done": false, "title": "some title" }, { "done": true, "title": "some title" … -
Correct way to use URL Patterns, Views & Templates when using the Django Abstract base classes for my models
Are there better approaches to this problem? This model structure is what I am after for my database. So I am feeling like I am breaking the DRY rule with my learning project. Using Django 3.2.9 & Python 3.9.6 I have looked around the internet on how to get this more dynamic in the views, urls & templates but I have not had any luck. I have the following model structure for my models/contact.py class BaseContact(AbstractUser): other_name = models.CharField(max_length=50, null=True, blank=True) contact_number = models.CharField(max_length=10, null=True, blank=True) email = models.EmailField(unique=True) postal_address = models.ForeignKey(location.Address, on_delete=models.CASCADE, null=True, blank=True) tax_id = models.CharField(max_length=11, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] class Meta: default_related_name = 'base' verbose_name = 'Contact' verbose_name_plural = 'Contacts' def get_absolute_url(self): return reverse("%s:detail-%s" % (str(type(self).__name__.lower()), str(type(self).__name__.lower())), kwargs={"pk": self.pk}) class Customer(BaseContact): class Meta: default_related_name = 'customer' class Supplier(BaseContact): class Meta: default_related_name = 'supplier' class Employee(BaseContact): class Meta: default_related_name = 'employee' verbose_name = 'Employee' verbose_name_plural = 'Employees' So my urls/contact.py is looking grim. from django.urls import path from main.views.contact import UpdateEmployeeView, DetailEmployeeView, CreateEmployeeView, DeleteEmployeeView from main.views.contact import UpdateSupplierView, DetailSupplierView, CreateSupplierView, DeleteSupplierView from main.views.contact import UpdateCustomerView, DetailCustomerView, CreateCustomerView, DeleteCustomerView urlpatterns = [ path('employee/create/', CreateEmployeeView.as_view(), name='create-employee'), path('employee/detail/<int:pk>', DetailEmployeeView.as_view(), name='detail-employee'), path('employee/update/<int:pk>', UpdateEmployeeView.as_view(), name='update-employee'), path('employee/delete/<int:pk>', DeleteEmployeeView.as_view(), name='delete-employee'), path('supplier/create/', … -
How to go to a page with single post from the news list
Can you help me with my project. I 'm trying to go from the page with all the news to a single post, but whatever i stay in page with all news. But if I write the address o in the address bar, everything works. Models.py class News(models.Model): title = models.CharField(max_length=1000, verbose_name='Название') slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='articles/', verbose_name='Фото') publish = models.DateTimeField(default=timezone.now, verbose_name='Дата публикации') author = models.ForeignKey(User, related_name='news', on_delete=models.CASCADE, verbose_name='Автор', null=True) text = models.TextField(verbose_name='Текст') tags = models.ManyToManyField(Tag, related_name='news', verbose_name='Тэг') created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') updated = models.DateTimeField(auto_now=True, verbose_name='Дата обнавления') status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='опубликован', verbose_name='Статус') class Meta: ordering = ('title',) verbose_name = 'Новости' verbose_name_plural = 'Новости' def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) Views.py def list_news(request): news = News.objects.all() return render(request, 'diplom/news/post.html', {'news': news}) def single_news(request, post_slug): post = get_object_or_404(News, slug=post_slug) return render(request, 'diplom/news/blog-single.html', {'post': post}) urls.py urlpatterns = [ path('news/', views.list_news, name='News'), path('post/<slug:post_slug>/', views.single_news, name='post') ] templates <div class="col-lg-4 col-md-6 grid-item"> {% for news in news %} <div class="blog-item large-item set-bg">{{ news.image }} <a href="{{post.get_absolute_url}}" methods="post" > <div class="categories">{{ news.title }}</div> <h5>{{ news.text| linebreaks|truncatechars:200 }}</h5> </a> <div> {{ news.publish }} {{ news.tag }} </div> </div> {%endfor%} </div> -
Is it possible to use the action tag in the form tag in ul or li?
I am trying to do web development with Django. It is recommended to use a form to be translated in its path while changing the language. In the proposed document, the language change function is given to the action attribute. Can I do this in ul or li? The suggested form is as follows: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> -
its showing a warring that sender is not accessed! and same with **kwargs and when I login as admin my profile page shows the details about the admin
"""I'm unable to access senders and **kwargs and this is my signals.py file and I guess is causing a bug that is when I login as admin its start showing admin details in my profile page too, please help me out as I'm new to Django""" from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance,**kwargs): instance.profile.save() -
How to automatically launch django web server by windows SYSTEM
I want to know if there's a way to have windows server 2019 automatically launch django's web server. I also want the launch to be performed at startup and by SYSTEM. I tried using batch scripts that launch manage.py from venv's python interpreter. When I launch the batch manually (i.e. double click) it works fine and dandy. But it appears that SYSTEM fails in running the script correctly when planning the task. I made SYSTEM launch another script at startup (a simple python script that creates a txt file from within its own venv) and it works. If the Django launch sceipt is launched by USER then it works. The problem is with the launching of django with SYSTEM. I've also tried streamlit and the result is the same. Do you have any Ideas? Sample batch script: cd path\of\managepyfile\ C:\path_to_venv\Scripts\python -m manage.py -
How to better format Django filter query for +1000 entries using SQLite3 database? (Expression tree is too large (maximum depth 1000))
The Django models I have are Component and Product. Components have Products as their Foreign Key. I am retrieving a search parameter from request.GET, called "components," that has a list of substrings that can belong to any Component. Based on the Components matched, I want to retrieve all Products that have this Component and return it back to the client. There are roughly 12000 Components and 3000 Products in my SQLite database I have been filtering out Products with the "|" operator for each of the Component's Product's id number, which works fine when searching for specific Component substrings, such as "Lactose" and "Bacterium." However, when I search for shorter substrings, such as "ac," I get the error: "OperationalError at /search, Expression tree is too large (maximum depth 1000)". From what I can understand, it's because the database is executing a multitude of union queries, and more than 1000 of those queries causes that error. I would like to know how to fix or workaround this error. Is there a better way to use Django's filter queries? Here is my models.py: from django.db import models class Product(models.Model): id_number = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=200) class Component(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name … -
Adding password protection with openpyxl in Django project
I tried to add password protection the excel file as shown below, but the protection is not happening, any body can tell us what is wrong here. def export_member_to_xlsx(request): user_queryset = User.objects.filter(is_staff=False) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-members.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = 'Members' worksheet.protection = WorkbookProtection(workbookPassword='password', lockStructure=True) columns = [ 'User', 'Email', 'First Name', 'Last Name', 'Member Since', 'Subscription Expiry', ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for member in user_queryset: row_num += 1 row = [ member.username, member.email, member.first_name, member.last_name, member.date_joined, member.subscriptions.current_period_end, ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response I tried the same protection code before workbook.save, but still it doesn't work -
empty formset CSS with Django Crispy Forms
I am trying to render a formset with crispy forms in Django, utilizing an add-more forms button. However I can't figure out how to apply the same CSS to the empty form as the original form. The only way I have been successful is creating a new empty form like this solution, but this adds in another <form> tag which is a problem that isn't covered in the solution. How can I apply CSS to the dynamically added formset? The below image is the expected result once I click the add more ingredients <button>: forms.py from .models import Recipe, RecipeIngredient from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Layout, Field class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['name', 'quantity', 'unit', 'description'] labels = { 'name': "Ingredient", "quantity:": "Ingredient Quantity", "unit": "Unit", "description:": "Ingredient Description"} def __init__(self, *args, **kwargs): super(RecipeIngredientForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-entryform' self.helper.form_class = 'form-inline' self.helper.layout = Layout( Div( Div(Field("name", placeholder="Chickpeas"), css_class='col-6 col-lg-4'), Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'), Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'), Div(Field("description", placeholder="No added salt tins"), css_class='col-12'), css_class="row", ), ) views.py: def recipe_create_view(request): form = RecipeForm(request.POST or None) RecipeIngredientFormset = formset_factory(RecipeIngredientForm, prefix="ingredient") formset = RecipeIngredientFormset(request.POST or None) context = { "form": … -
Iframe URL in Django? [duplicate]
I'm essentially trying to use an IFRAME on my django's html page to display another website inside of my current page. However nothing is popping up in the iframe, just the border. I think its due to the way django handles urls but im not for sure (Im fairly new to django). <iframe src="http://examplesite.com" style="border:0px #ffffff none;" name="myiFrame" scrolling="no" frameborder="1" marginheight="0px" marginwidth="0px" height="400px" width="600px" allowfullscreen></iframe> This is currently what im passing in my html file, but again, nothing is displaying inside of the iframe. Any ideas? -
Django custom AdminSite admin_view() not working, 404 error codes
admin.py class MyAdminSite(AdminSite): login_template = "admin/Slogin.html" index_template="admin/Shome.html" def get_urls(self): urls = super(MyAdminSite,self).get_urls() urls += [ url(r'^add_department/$', self.admin_view(self.add_department),name="add_department"), url(r'^add_equipment/$',self.admin_view(self.add_equipment),name="add_equipment"), url(r'^add_engineer/$',self.admin_view(self.add_engineer),name="add_engineer"), url(r'^engineer/<int:id>$',self.admin_view(self.update_engineer),name="update_engineer"), ] return urls def index(self,request): if request.method=="POST": engid=request.POST['eng_id'] noti=request.POST['notification'] ndate=date.today() ntime=datetime.now().strftime("%H:%M:%S") n=notification(engineer_id=engid,notification_text=noti,notification_date=ndate,notification_time=ntime) n.save() #messages.info(request,'Notification Send Successfully') department=Department.objects.all() engineer=User.objects.filter(is_staff=False) service=Service.objects.raw('''SELECT engineer_service.id as service_id,auth_user.username,engineer_service.service_date,engineer_equipment.id,engineer_equipment.equipment_name FROM engineer_service JOIN auth_user ON auth_user.id=engineer_service.equipment_id JOIN engineer_equipment ON engineer_equipment.id=engineer_service.equipment_id ORDER BY engineer_service.id DESC ''') equip=equipment.objects.all() noti=notification.objects.raw(''' SELECT * FROM engineer_notification Join auth_user on auth_user.id=engineer_notification.id order by engineer_notification.id DESC ''') activity=activity_tracker.objects.all().order_by('-id')[:5] context={ 'department':department, 'engineer':engineer, 'equipment':equip, 'service':service, 'activities':activity, 'notification':noti } return render(request,'admin/Shome.html',context) def add_department(self, request): if request.method=="POST": dept_name=request.POST['dept_name'] dept_id=request.POST['dept_id'] if dept_id!='0': dept=Department.objects.filter(id=dept_id).update(department_name=dept_name) messages.success(request,"Department Updated Successfully") else: d1=Department(department_name=dept_name) d1.save() messages.success(request,"Department Added Successfully") request.method="GET" return MyAdminSite.index(self,request) else: department=Department.objects.all() return render(request,"admin/add_department.html",{'department':department}) def add_equipment(self,request): # print("eq called") if request.method=="POST": equip_name=request.POST['name'] equip_doi=request.POST['doi'] dept_id=request.POST['dept_id'] equip_det=request.POST['details'] e=equipment(equipment_name=equip_name,department_id=dept_id,equipment_doi=equip_doi,equipment_details=equip_det) e.save() messages.success(request,"Equipment Added Successfully") request.method="GET" return MyAdminSite.index(self,request) else: equip=equipment.objects.all() department=Department.objects.all() return render(request,"admin/add_equipment.html",{'equip':equip,'department':department}) def add_engineer(self,request): print("add eng") engineer=User.objects.filter(is_staff=False) if request.method=="POST": firstname=request.POST['firstname'] lastname=request.POST['lastname'] username=request.POST['user_name'] pwd=request.POST['pwd'] if User.objects.filter(username=username).exists()==False: user=User.objects.create_user(username=username,first_name=firstname,last_name=lastname,password=pwd) user.save() messages.success(request,"Engineer Account Created Successfully") request.method="GET" return MyAdminSite.index(self,request) else: messages.warning(request,"User_name Already taken") return render(request,'admin/add_engineer.html',{'engineer':engineer}) else: return render(request,"admin/add_engineer.html",{'engineer':engineer}) def update_engineer(self,request,id): if request.method=="POST": username=request.POST['eng_username'] firstname=request.POST['eng_firstname'] lastname=request.POST['eng_lastname'] password=request.POST['eng_password'] user=User.objects.filter(username=username).update(first_name=firstname,last_name=lastname,password=password) messages.success(request,"Details Updated Sucessfully") request.method="GET" return MyAdminSite.index(self,request) else: user=User.objects.filter(id=id,is_staff=False) if user is not None: return render(request,'admin/update_engineer.html',{'user':user}) else: return render(request,'admin/Shome.html') admin_site = MyAdminSite() admin.site=admin_site admin.site.register(activity_tracker) admin.site.register(Service) admin.site.register(Department) admin.site.register(notification) admin.site.register(equipment) … -
How to extract the id of a Django formset in Javascript?
I have a doubt what happens is that I am trying to extract the id of a Django formset in Javascript, however when trying to do it I realized that this appears in Chrome DevTools: S.fn.init [[Prototype]]: Object (0) That is, nothing is happening, but it seems strange to me because when printing in the console I get the id name that I want what is happening and how can I extract its id and therefore the value?? calculate.js //the number of total forms is taken var formId="id_form-TOTAL_FORMS" var form_idx = document.getElementById('id_form-TOTAL_FORMS').value; console.log("el valor es:" + form_idx); var totalForms=parseInt($('#'+formId).val()); console.log("totalForms:"+totalForms) console.log(totalForms+1); //dynamic id are created var formset_quantity='id_form-'+form_idx+'-quantity'; var formset_unit_price='id_form-'+form_idx+'-unit_price'; console.log('formset quantity: '+formset_quantity); console.log('formset unit price: '+formset_unit_price); //the value of the one that contains the dynamic id is taken //This is when everything goes wrong because when printing in the console I get the error above, // as if that id does not exist(formset_quantity and formset_unit_price) or I am not creating it correctly var id_formset_quantity=document.getElementById('formset_quantity').value; var id_formset_unit_price=document.getElementById('formset_unit_price').value; var formset_total_price=document.getElementById('id_form-'+form_idx+'-total_price'); presupuestos-forms.html td id="parent_id_form-0-quantity"> <input type="number" name="form-0-quantity" class="form-control" id="id_form-0-quantity"> </td> <td id="parent_id_form-0-unit_price"> <input type="number" name="form-0-unit_price" class="form-control" id="id_form-0-unit_price"> </td> <td id="parent_id_form-0-total_price"> <input type="number" name="form-0-total_price" class="form-control" id="id_form-0-total_price"> </td> -
when and where & why need to use Django - signals
when and where & why need to use Django - signals . I didn't understand Django signals can anyone can help in details with sample example thank you. -
Tag inside of another in Django HTML
I am trying to do this: {% block content %} {% with card_header='Войти на сайт' card_body="{% include 'includes/form.html' %}" %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} But it seems like I can not add tag inside of tag, I tried other hints from other stack overflow post, but none of them worked for my case. This is what I tried: {% include 'includes/form.html' as card_body_url %} {% block content %} {% with card_header='Войти на сайт' card_body=card_body_url %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} {% block card_body %} {% include 'includes/form.html' %} {% endblock card_body %} {% block content %} {% with card_header='Войти на сайт' %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} -
Exception Value: Failed loading libasound.so.2: libasound.so.2: cannot open shared object file: No such file or directory (Django/heroku)
I made a drowsiness detector for driving using django. I tried deploying it on heroku and everything seems to be working fine except as soon as I try to open the camera, I get the error: Exception Value: Failed loading libasound.so.2: libasound.so.2: cannot open shared object file: No such file or directory All the other pages are working fine, you can try it out here. As soon as you click on Start Driving it throws this exception. The app is working fine in localhost. Please help! -
Django Migrations: How to resolve error of charfield to datetimefield
What im doing is i clone my prod database to sandbox. and I'm getting error while migrate Cause of previously I made charfield to datetime field. And then datetime field to Charfield after few migrations. So how do I solve below error: Error : python manage.py migrate System check identified some issues: WARNINGS: Operations to perform: Apply all migrations: admin, auth, contenttypes, pro_auth, service_list, sessions, token_blacklist Running migrations: Applying pro_auth.0002_alter_userorder_order_booking_time...Traceback (most recent call last): File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidDatetimeFormat: invalid input syntax for type timestamp with time zone: "2021-10-10 10.00" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, … -
how can i solve this pipenv install error - django project on vscode
Hello_world! This is my first post - ever - on the internet so give me some credit haha...Im basically a noob programmer who had this crazy idea of giving a shot at Django so I can (hopefully) create a humble plataform website with login, CRUD etc, even though i just know very basic python and still have a long way to learn all the frontend + react... So, im basically doing a course from Mosh (kinda famous youtube instructor) and got really (really) stuck on [Part 1 of the Django class -> Django ORM -> 3-Resetting the Database] - and i have no idea how to fix and i don't know no programmer in the real world to help me smh On this class, Mosh wants to make sure that we are on the same page, so he tells us to drag and drop into VSCode a specific folder (that contains the django project) that he makes it available at the beginning of the course. I followed all the steps but, as soon as i tried to run "pipenv install" on my terminal (as he tells us to right after dropping that folder), i get the following (BIG) error message...here … -
How to convert to crispy forms simple and fast?
I have project that at the end I realised that I need to switch to crispy forms. I'll provide code, maybe you have simple and fast solution without doing it again. Form needs to have two buttons; browse and submit button. This is upload_document.html {% extends "base.html" %} {% load static %} {% block content %} <!-- Upload form. Note enctype attribute! --> <form action="{% url "upload_doc" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations 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, 'upload_document.html', { 'form': form, 'page_title':page_title }) -
How to limit number of entries from GeoDjango Postgis django-rest-framework query?
I've built basic Django mapping functionality through this tutorial but Python keeps blowing through 32GB of ram and/or the browser crashes, presumably because the query isn't limited to the first n results and the DB has millions of entries. My "vietsets.py": from rest_framework import viewsets from rest_framework_gis import filters from core.models import Tablename from core.serializers import MarkerSerializer class MarkerViewSet(viewsets.ReadOnlyModelViewSet): bbox_filter_field = "geom" filter_backends = (filters.InBBoxFilter,) queryset = Tablename.objects.all() serializer_class = MarkerSerializer I think InBBoxFilter needs to be elaborated upon but the docs don't seem to mention any further options. The docs say "if you are using other filters, you’ll want to include your other filter backend in your view" giving the example, filter_backends = (InBBoxFilter, DjangoFilterBackend,), but I only want to limit the number of results for the functionality InBBoxFilter already provides. Can I write some kind of DjangoFilterBackend to limit results? Or is this best addressed through django-rest-framework functionality? How can I tell it to limit the number of results, or otherwise improve performance when using big databases? -
how to get access to post data incoming inside a Django middleware?
I am writing a middleware due to which i need to access post data but none of the answers are solving my doubt, i am reading the data like this but this is working in postman but giving error in browser dict_str = request.body.decode("UTF-8") any help is highly appreciated -
Uploaded Media files are only served after I reload the django server
I'm quite new to django development, tired of searching for this particular case of mine. I have django app running on my windows 10 with debug = False. I am just about to deploy my app to digital ocean droplet. I am facing so many deployment and static + media file issues. I kind of figured out static files, they are fine, media files are also loaded. But, when I upload a new image, access it directly, it says the resource I'm looking for isn't found. But it's 100% uploaded to media/images folder, and I can see it. Today, I think I found the some solution, I can access the media files only after I reload the django server. I want to know why is that? My settings.py file # Application definition INSTALLED_APPS = [ 'livereload', 'mnotes.apps.MnotesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', ] DJANGORESIZED_DEFAULT_SIZE = [100, 100] DJANGORESIZED_DEFAULT_QUALITY = 75 DJANGORESIZED_DEFAULT_KEEP_META = True DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'livereload.middleware.LiveReloadScript', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'MarketingNotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
How to cache the data pulled from BigQuery in Django?
I have a webapp that pulls data from BigQuery into my Django views, which then will be passed as a context to the frontend templates. However, this data pulling process will occur initially when I open the web, and will occur again everytime I refresh the page. Is there a way I can cache the data I have pulled? My views.py code looks similarly to this: def index(request): client = bigquery.Client() dataset_id = "project-id.dataset-id" tables = client.list_tables(dataset_id) tables_list = [table.table_id for table in tables] data_list = [] for table_id in tables_list: query_string = f""" SELECT * FROM `project-id.dataset-id.{table_id}` """ query_job = ( client.query(query_string) .result() ) records = [dict(row) for row in query_job] data_list.extend(records) df = pd.DataFrame(data_list) ... # Data manipulation syntax here using pandas dataframe ... data_json = df.to_json(orient="records") context = {'data_json': data_json} return render(request, 'template_name', context) I passed the data as a JSON to the context because I'm passing it to a React frontend. -
Django Crispy Formsets CSS
I am trying to utilize crispy forms & bootstrap with formsets but I can't seem to figure out the CSS styling. I need to style it in the backend as I want to allow the client to dynamically add more of the same form, and when you add an empty form into the HTML it does not keep the same styling. create.html <!--RECIPE INGREDIENTS--> {% if formset %} <h3>Ingredients</h3> {{ formset.management_form|crispy }} <div id='ingredient-form-list'> {% for ingredient in formset %} <div class='ingredient-form row'> {{ ingredient }} </div> {% endfor %} </div> forms.py class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['name', 'quantity', 'unit', 'description'] labels = { 'name': "Ingredient", "quantity:": "Ingredient Quantity", "unit": "Unit", "description:": "Ingredient Description"} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='form-group col-md-6 mb-0'), Column('quantity', css_class='form-group col-md-4 mb-0'), Column('unit', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), Row( Column('description', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), ) views.py def recipe_create_view(request): form = RecipeForm(request.POST or None) RecipeIngredientFormset = formset_factory(RecipeIngredientForm) formset = RecipeIngredientFormset(request.POST or None) context = { "form": form, "formset": formset, } if request.method == "POST": #print(request.POST) if form.is_valid() and formset.is_valid() and instructionFormset.is_valid(): parent = form.save(commit=False) parent.user = request.user parent.save() #recipe ingredients for form in … -
"NoModuleNamed" when using custom logging filters
Im trying to use different formatters for different log levels, for that I created a custom filter. This is the error I get: Traceback (most recent call last): File "...\Python\Python39\lib\logging\config.py", line 385, in resolve found = self.importer(used) ModuleNotFoundError: No module named 'logging_formatter' In my_django_project/logging_formatter/formatter_filter.py I have the filter named FilterLevels And the settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'info_formatter': { 'format': '{asctime}|{levelname}|{message} [in {funcName}]', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '{', }, 'error_formatter': { 'format': '{asctime}|{levelname}|{message} [in {filename}:{funcName}:{lineno}]', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '{', }, }, 'filters': { 'filter_info_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "INFO" ] }, 'filter_error_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "ERROR" ] }, 'filter_warning_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "WARNING" ] } }, 'handlers': { 'app_info': { 'formatter': 'info_formatter', 'filters': ['filter_info_level'], 'class': 'logging.StreamHandler', 'filename': 'my_django_project/logs/app.log', }, 'app_error': { 'formatter': 'error_formatter', 'class': 'logging.StreamHandler', 'filename': 'my_django_project/logs/app.log', 'filters': ['filter_error_level'], }, }, 'loggers': { 'my_django_project.app': { 'handlers': ['app_info', 'app_error'], 'level': 'DEBUG', }, }, } -
Django many to many field not showing on admin - Legacy database
I want to show a many to many field that was created in nocodb on django admin panel. Therefore the database schema were created by nocodb. I want to also edit the db with django. The many to many tags field doesn't show in django admin. There is no error message. Can someone help? I used inspectdb to create the models and admin_generator to create the admin code for the nocodb fields. I tried adding an id column in the join table. I made it the primary key. That didn't seem to help. ================================================= The following pic shows that the tags are not shown on the page. ================================================= This is how it looks in nocodb. ================================================= These are the tables in mysql. You can see the note table, tag table, and the note-tag table. ================================================= This is a post tagg many to many I created in Django, and it works. ================================================= The models.py and admin.py follow: models.py # ================================================= class Tagg(models.Model): title = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return str(self.id) + " - " + self.title class Post(models.Model): # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) title = models.CharField(max_length=230) body = models.TextField(max_length=32100, default=None, blank=True, null=True) taggs = models.ManyToManyField(Tagg) …