Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save and data to different Model in Django
you all, I wanna try to implement saving data in another table. There is favorite table and food table and what I need to do is to transfer to a food on favorite model to food table when users click add button. When transferring I don't want lose the adding data from the favorite table, instead keeping it in the favorite table. Any comment is helpful and thanks for your time in advance!! def add_to_today_foods(request, pk): favorite = get_object_or_404(Favorite, pk=pk) food = favorite if request.method == 'POST': food.user = request.user food.save() return redirect('today_foods') context = { 'food': food, 'favorite': favorite, } return render(request, 'base/add_to_today_foods.html', context) from django.urls import path from .views import FoodCreate, FoodUpdate, FoodDelete, FoodList, TargetCreate from . import views urlpatterns = [ path('', views.foods, name='today_foods'), path('all_foods', FoodList.as_view(), name='all_foods'), path('all_foods/search/', views.food_search, name='food_search'), path('favorite', views.favorite, name='favorite'), path('favorite/delete/<int:pk>', views.favorite_delete, name='favorite_delete'), path('favorite/update/<int:pk>', views.favorite_update, name='favorite_update'), path('favorite/add_to_today_foods/<int:pk>', views.add_to_today_foods, name='add_to_today_foods'), path('target', TargetCreate.as_view(), name='target'), # path('', FoodList.as_view(), name='foods'), path('create/', FoodCreate.as_view(), name='food-create'), path('update/<int:pk>', FoodUpdate.as_view(), name='food-update'), path('delete/<int:pk>', FoodDelete.as_view(), name='food-delete'), ] {% extends 'base.html' %} {% block title %}|お気に入り登録{% endblock %} {% block content %} <div class="header-bar"> <a href="{% url 'today_foods' %}">&#8592; 戻る</a> </div> <div class="body-container"> <div class="body-header"> <h1>お気に入り登録</h1> </div> <div class="notion2"> <p>※数字は半角で打ち込んでください</p> </div> <form action="{% url 'favorite' %}" … -
unable to give path to templates in Django
Django question here: So I was trying to get some html files to work through templates. I put this in the views.py file: def about (request): return render(request, 'about.html') def contact (request): return render(request, 'contact.html') def pricing (request): return render(request, 'pricing.html') def faq (request): return render(request, 'faq.html') and this in the urls.py file: path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('pricing', views.pricing, name='pricing'), path('faq', views.faq, name='faq'), ] Yet when I try to go there through the home page, it doesn't work and I get this: Error page Does anyone know how to fix this?!?!!! My templates folder and manage.py are in the same folder -
Modern practical option for Django search with Postgres? Need multiple criteria, but icontains is too inefficient
Django search / filter in views.py using icontains and gte, simplified: def BootstrapFilterView(request): qs = Table.objects.all() food_contains_query = request.GET.get('food') country_contains_query = request.GET.get('country') price_min_query = request.GET.get('pmin') qs = qs.filter(food__icontains= food_contains_query) qs = qs.filter(property_locality__icontains= country_contains_query) qs = qs.filter(purchase_price__gte=price_min_query) gte works fine but upon testing icontains is unsuitably inefficient. Indexing doesn't help for icontains and I think iexact might work, but users can't be expected to provide exact matches. I'm bewildered by more advanced options for a task well beyond my understanding and am reluctant to attempt potentially obsolete approaches. Using Postgres 11.6 with millions of rows, and need multiple optional search criteria. There are thousands of unique food and all are children of one of dozens of country. Django Postgres has full text search but all search criteria are nouns so don't need lexeme conversion but spelling correction (eg. "burito" → "burrito") and synonym matching (eg. "hamburger" → "cheeseburger") are desirable. Is Postgres full text suitable and can this be used with other search criteria of gte and similar numeric operations? What's a modern and practical way to improve performance? -
How can I get a blank quantity field to update as a 0 and stop my stripe payment from crashing?
I'm really stuck here and could use some help. When testing my project I found a flaw I'm having an issue fixing. In the shopping cart, if I remove the amount of any item and click Update Quantity: ...then I get the following error, and I would appreciate any tips or tricks. I'm thinking forcing it to update with 1 somehow? Thank you! -
AttributeError: module 'django.db.models' has no attribute 'RESTRICT'
Both CASCASE and PROTECT are working, but I cannot get RESTRICT to work. I am going through the Mozilla tutorial. book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) I am getting this error when I try to make migrations AttributeError: module 'django.db.models' has no attribute 'RESTRICT' I am running django 3.2.4 -
i am trying to upload image in django but it gives me MultiValueDictKeyError at /index 'myfile'
I tried to insert image into sqlite but it didn't worked with it gives me error evertime this is my code def index(request): dbname = 'user1' cursor = connections[dbname].cursor() if request.POST.get('done'): cursor.execute('insert into images values(%s)', [request.FILES['myfile']]) return render(request, 'index.html') and this is the error MultiValueDictKeyError at /index 'myfile' Request Method: POST Request URL: http://127.0.0.1:8000/index Django Version: 3.2 Exception Type: MultiValueDictKeyError Exception Value: 'myfile' Exception Location: D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ Python Executable: D:\omar\pythonProject\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: ['D:\\omar\\pythonProject', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39', 'D:\\omar\\pythonProject\\venv', 'D:\\omar\\pythonProject\\venv\\lib\\site-packages'] Server time: Mon, 28 Jun 2021 00:18:52 +0000 Traceback Switch to copy-and-paste view D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 76, in __getitem__ list_ = super().__getitem__(key) … ▶ Local vars During handling of the above exception ('myfile'), another exception occurred: D:\omar\pythonProject\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars D:\omar\pythonProject\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars D:\omar\pythonProject\Dhb\views.py, line 5951, in index cursor.execute('insert into images values(%s)', [request.FILES['myfile']]) … ▶ Local vars D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ raise MultiValueDictKeyError(key) I tried to insert image into sqlite but it didn't worked with it gives me error evertime -
Basic data model for a food tracker
I am new to data modeling and trying to develop a Django model for a simple food tracker. What did you eat? Pancakes Meal Breakfast Ingredients Eggs Flour Milk Allergens Eggs When the user logged their Food, Meal, and Ingredients it would lookup to see if any of those ingredients are a known allergen. What would be the appropriate data model for this? My guess is below. Food Name Notes User_Id Meal Name User_Id Ingredients Name User_Id Allergens Name -
django 3.2 Import
Any idea why I'm not able to import files? For example if i use the period to import from the current package, it works. But if I try to explicitly define it or import from a remote application withing the project, it does not work. from device.serializer import DeviceSerializer ModuleNotFoundError: No module named 'device.serializer' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_countries', 'customer.apps.CustomerConfig', 'device.apps.DeviceConfig', ] -
Using yaml key values globally in Django
I want to use some key values from yaml file in my django project. example of 'Validation_Errors.yaml' file: errors: ERROR-BAD-REQ: PL : "Wprowadziłeś błedne dane spróbuj jeszcze raz" EN : "Wprowadziłeś błedne dane spróbuj jeszcze raz" RU : "Wprowadziłeś błedne dane spróbuj jeszcze raz" ERROR-BAD-CITY: PL : "To miasto jest błędne" EN : "To miasto jest błędne" RU : "To miasto jest błędne" I wrote a class that is initialized in views after the start: class UploadYaml(Exception): _file = 'Validation_Errors.yaml' _category = None _errors = None _error_code = 'ERROR-BAD-REQ' error_desc = str _language = 'PL' required = bool def __init__(self, **params): with open(self._file, 'r') as yaml_file: yaml_file = yaml.safe_load(yaml_file) self._errors = yaml_file.get(self._category) UploadYaml.error_desc = self._errors.get(self._error_code).get(self._language) for k, v in params.items(): if not k.startswith("_"): if hasattr(self, k): self.__setattr__(k, v) and it's working but I think there is a better method to do it. For example, can I initialize these code descriptions somewhere else globally in the application and use them everywhere I want (load file only once when application starts)? If I am initializing my class and want to import it into a different place there are some issues with correctly import file from the directory I know that I can … -
Using tables to submit information in Django
I am trying to create a website where I have a form with two tables that exchange information using Django with the top one containing information that would be submitted. The information submitted in the top table is each "Name" and the "Permissions". This currently works by using JS to exchange rows from a Datatables row (the lower table) to a standard table (the top table) and vice versa. The "name" and "value" tags for each row in the top table are done using JS and a hack using the number of rows currently populating the "Added Permissions" table. I then do parsing by iterating over the request dictionary and matching indices between names and values (i.e. "names" are things like group_name[1], desc[1] and so on while values are the actual values for each) While the solution works to a degree I want to, if at all possible, use Django Forms for this. However, I can't seem to find ways to use Django forms and table elements at the same time (as in a form.Form). The ideal solution would be for the description and "Added Permissions" table to be encapsulated by a Django forms.Form class while the "Available Permissions" table … -
How do I resolve Django takes no arguments error I get when I plug in external api to project
I am a bit new to Django and Python in general I am trying to consume an external API (alpacas get account) and return the result as json /rest I tested the code in a simple python project without Django and it works perfectly, but when I plug it into Django, I get the takes no arguments error After writing my code and running it, When I invoke the API in postman I see the takes no arguments error see error details below Django Version: 3.1.5 Exception Type: TypeError Exception Value: AccountView() takes no arguments Internal Server Error: /alpaca/v1/alpaca_account/ Traceback (most recent call last): File "/Users/xxxx/PycharmProjects/xxxx/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/xxxx/PycharmProjects/xxxx/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: AlpacaAccountView() takes no arguments [27/Jun/2021 21:24:12] "GET /alpaca/v1/alpaca_account/ HTTP/1.1" 500 56001 Honestly, I have no idea what this error is talking about Please help me resolve this See My code below View import requests, json from .config import * BASE_URL = BASE_URL ACCOUNT_URL = "{}/v2/account".format(BASE_URL) ORDERS_URL = "{}/v2/orders".format(BASE_URL) HEADERS = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY} # Create your views here. class AccountView: def get_account(self): r = requests.get(ACCOUNT_URL, headers=HEADERS) return json.loads(r.content) see urls.py from django.urls import path, … -
Associate a Django Bool FormField with a submit button in a ModelForm and CBV
The view has a Boolean Field which will define if a question is OK or needs correction. The template will load two buttons to act as submit to the form, "Question is OK" and "Question needs correction". I need to pass the value of this button as the Boolean Field value. I found the answer when using Function-based views, but I'm using Class-based views, so I don't know how to pass the request.POST values. Here's my views.py and forms.py: views.py class QuestionValidation(PermissionRequiredMixin, UpdateView): permission_required = 'users.validator' model = Question form_class = ValidationForm template_name = 'question_validation.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['question'] = Question.objects.filter( question_order=self.kwargs['order']).get(id_by_order=self.kwargs['id_by_order']) context['order'] = self.kwargs['order'] context['id_by_order'] = self.kwargs['id_by_order'] return context def get_object(self, *args, **kwargs): question_order = Q(question_order__id=self.kwargs['order']) question_id = Q(id_by_order__contains=self.kwargs['id_by_order']) q = Question.objects.get(question_order & question_id) return get_object_or_404(Question, pk=q.id) def get_success_url(self, *args, **kwargs): view_name = "order-detail" return reverse(view_name, kwargs={'pk': self.kwargs['order']}) forms.py class ValidationForm(forms.ModelForm): class Meta: model = Question fields = ['revision_report', 'revision_approval'] widgets = { 'revision_report': forms.HiddenInput(), 'revision_approval': forms.HiddenInput(), } and part of the template that this code will be loaded: <form action="" method="POST">{% csrf_token %} {{ form.as_p }} <button class="btn btn-success" name="question_approved">Questão aprovada</button> <button class="btn btn-danger" name="question_refused">Questão não foi aprovada</button> </form> <br><br> <script src="{% static 'js/hoverValidatorTextbox.js' … -
Use is_authenticated using OneToOneField relation with User
I have built a model which have a OneToOne relation with the User object in Django like this : class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) But in the HTML file, the filter {% if user.student.is_authenticated %} does not work but the filter {% if user.is_authenticated %} works. I thought that the Student class inherits the attributes from the User class. Is there an other possibility to create custom users from the User class with the possibility to use {% if user.student.is_authenticated %} ? I want also to have the possibility to use for example {% if user.teacher.is_authenticated %}. -
FIlter table using CBV ListView that has pagination
I'm trying to do a ListView from a Class Based View that has filtering, and pagination I was able to get the table showing and the pagination working as I want, this gives me a basic list of all invoices that I need to show: but I'm not able to make the filtering work, for what I understand I need to override the "get_queryset" method and this would return a queryset, (in this cased called "invoices_filtered_list") however I don't know how should I render this in the .html page so it will have the textbox in which I should type. These are my files: views.py from django.views.generic import (TemplateView, ListView) from .models import WoodhistAzolveInvoices from .filters import WoodhistAzolveInvoicesFilter class InvoicesListView(ListView): model = WoodhistAzolveInvoices template_name = 'home.html' context_object_name = 'invoices' ordering = ['suppliername', 'invoicenumber'] paginate_by = 50 def get_queryset(self): qs = self.model.objects.all() invoices_filtered_list = WoodhistAzolveInvoicesFilter(self.request.GET, queryset=qs) return invoices_filtered_list.qs urls.py from django.urls import path from .views import InvoicesListView app_name = 'web' urlpatterns = [ path('', InvoicesListView.as_view(), name='home'), ] filters.py import django_filters from .models import * class WoodhistAzolveInvoicesFilter(django_filters.FilterSet): class Meta: model = WoodhistAzolveInvoices fields = ['suppliername'] models.py from django.db import models class WoodhistAzolveInvoices(models.Model): docid = models.CharField(db_column='DocId', primary_key=True, max_length=50) # Field name made lowercase. … -
Django. TemporaryUploadedFile
I upload a file through the form, check it, and only after checking it I want to add it to my database. form = BookForm(request.POST, request.FILES) file = form.files path = file.get('book_file').temporary_file_path() in path - '/tmp/tmpbp4klqtw.upload.pdf' But as soon as I want to transfer this file from the temporary storage to some other folder, I get the following error: path = os.replace(path, settings.MEDIA_ROOT) IsADirectoryError: [Errno 21] Is a directory: '/tmp/tmpbp4klqtw.upload.pdf' -> '/home/oem/bla/bla' Can't understand why this file is not in reality? What can I do about it? Is it possible to set some special path for the "temporary file"? -
Access Users from Group model Django
I'm trying to access the users inside the group model of django. For now i can only access it the other way, the groups from the user model. I want to be able to do multiple action from the Group endpoints: Retreive the users inside the group and return them inside the view create a group and add user directly in the request update the group to add or remove a user from it I've done the same thing for the permissions, i can add them inside the groupe, but i can't do it for the user because there isn't a field for the users inside the group model. To do it for the permission i made a serializer I would like to do the same as the Permissions field, but for the users, is there any way ? I looked to override the Group model and add a field so a could use it in the serializer but i didn't find how to do so. class GroupSerializer(serializers.ModelSerializer): Id = serializers.IntegerField(source='id', required=False) Name = serializers.CharField(source='name') Permissions = PermissionSerializer(source='permissions', many=True, required=True) class Meta: model = Group fields = ('Id','Name','Permissions',) def create(self, validated_data): print(validated_data) permissions_data = validated_data.pop('permissions') permissions = [] for permission … -
Django Admin panel unable to retrieve and show image(already uploaded through model)
As you can see in SS i am unable to view the image in admin panel; under the image tag error from CMD: Not Found: /upload/images/How-to-buy-a-desktop-PC-header.jpg [27/Jun/2021 13:00:51] "GET /upload/images/How-to-buy-a-desktop-PC-header.jpg HTTP/1.1" 404 2605 I already checked the upload folder and image is in the folder. settings.py MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py # under the Product class def image_tag(self): return mark_safe('<img src="{}" height ="50"/>'.format(self.image.url)) image_tag.short_discription = 'Image' last admin.py class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'category', 'status', 'image_tag'] list_filter =['category'] readonly_fields = ('image_tag',) inline = [ProductImageInline] screenshot: -
Best way to serialize object dynamically based on parameter using Django Rest Framework
I want to render a dynamically selected object using an intermediate model and a custom query_param. For instance,I want to make a query like this: http://api.url/v1/recipes/19/?location=1 and obtain a serialized Recipe object with it's ingredients based on the location send as query_params: Recipe object: { "id": 19, "ingredients": [ { "id": 35, # Product id "name": "Tomato", # Product name "price": 2.0, # Product price "quantity": 3, "supplier": 12, # Supplier at location=1 }, { "id": 36, # Product id "name": "Cheese", # Product name "price": 5.0, # Product price "quantity": 2, "supplier": 12, }, ], "title": "Pizza" } If I change the ?location= query param I want to obtain the same recipe but getting the products of another Supplier. This is my current schema. But any suggestion is very appreciated: class Recipe(models.Model): title = models.CharField(max_length=255) class IngredientRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.FloatField(default=0.0) product_name = models.CharField(max_length=255) class Meta: unique_together = ['product_name', 'recipe'] class Supplier(models.Model): name = models.CharField(_('Name'), max_length=255) location = models.ForeignKey(Location, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=255) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) price = models.FloatField() I'm trying to serialize Recipe objects with its related ingredients based on supplier's location: class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' … -
Django 3.2 `get_asgi_application` is not a replacement for channels AsgiHandler
I'm upgrading from Django 3.0/Channels 2 to Django 3.2/Channels 3. In channels 3.0 release notes, it is stated that instantiating a ProtocolRouter without the http key is deprecated, and that one should use django.core.asgi.get_asgi_application as value. However, when I'm explicit on the http protocol using get_asgi_application, my middlewares don't work anymore: the app is complaining that I'm using sync middleware in an async context. This is the Django error popping up: SynchronousOnlyOperation at /graphql/ You cannot call this from an async context - use a thread or sync_to_async. ... Here is the content of asgi.py # my_project/asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter import django from django.core.asgi import get_asgi_application assert os.environ.get('DJANGO_SETTINGS_MODULE') is not None, \ 'The `DJANGO_SETTINGS_MODULE` env var must be set.' django.setup() from core.urls import ws_routes application = ProtocolTypeRouter({ # If the following line is not commented out, I get the above error. # 'http': get_asgi_application(), 'websocket': URLRouter(ws_routes) }) I do not want to use async logic in my HTTP handlers/middleware, as I prefer the simplicity of synchronous patterns. I use Channels only to deal with websockets. I'm looking for advice on how to follow Channels guidelines (ie, be explicit about the http protocol application). In the meantime, … -
Get User id from class based view
I have a class based view: class PostListViewMojeReported(ListView): def get_username(self, **kwargs): login_username = request.user.username context = {'login_username': login_username} return context model = Post template_name = 'blog/filter_moje_reported.html' context_object_name = 'posts' queryset = Post.objects.filter(Q(status='Otvorena') & (Q(res_person_1_username=username) | Q(res_person_2_username=username))) ordering = ['-date_posted'] paginate_by = 30 I don't know how to get username from the current logged in user to use as a filter in my queryset. I need to compare the current logged in user with 'res_person_1_username' and 'res_person_2_username'. -
ListView in Django
I am using Class Based views and want to display data on a webpage using ListView. Am using for loop to display many objects data. In my models, the items have a category field which is ForeignKey where the category is either Bags, Tshirts or Shoes. I want to display items whose Category is Shoes only. I have tried using the if condition which isnt working with the ForeignKey field. How do I filter the Category field to display Bags only? models.py from django.db import models # Create your models here. class Category(models.Model): title = models.CharField(max_length=30) createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Categories" class Product(models.Model): mainimage = models.ImageField(upload_to='product') name = models.CharField(max_length=264) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') previewtext = models.TextField(max_length=200, verbose_name='Preview Text') detailstext = models.TextField(max_length=1000, verbose_name='Description') price = models.FloatField() oldprice = models.FloatField(default=0.00) createddate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-createddate',] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from shopapp.models import Product # Create your views here. class Home(ListView): model = Product template_name = 'shopapp/home.html' html file <div class="container my-5"> <h2 class="my-5">Handbags</h2> <div class="row"> {% for product in object_list %} {% if product.category == 'Bags' %} <div class="col-md-6 col-sm-12 col-lg-3"> … -
Django Images not showing when DEBUG=False on Heroku
I am trying to get images show up on website whenever a user uploads it, but they do not show up when DEBUG=False. The site got deployed successfully on Heroku. I am using Whitenoise and Gunicorn too. Here are my configurations:- settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Procfile web: gunicorn appname.wsgi --log-file - requirements.txt asgiref==3.3.4 astroid==2.5.6 colorama==0.4.4 Django==3.2.4 gunicorn==20.1.0 isort==5.8.0 lazy-object-proxy==1.6.0 mccabe==0.6.1 Pillow==8.2.0 pylint==2.8.3 pytz==2021.1 sqlparse==0.4.1 toml==0.10.2 whitenoise==5.2.0 wrapt==1.12.1 -
Export multiple Django models into one file
Is there a way to export your objects from different models to a csv file? I can add all the objects from a model one by one, but I need multiple objects from different models next to each other instead of under each other. for doc_uren in DocentUren.objects.all().values_list('docent', 'periode', 'studiejaar', 'uren'): writer.writerow(doc_uren) for data in PeriodeData.objects.all().values_list('studiejaar', 'periode_1', 'periode_2', 'periode_3', 'periode_4'): writer.writerow(data) This results in the objects from DocentUren, with the objects from PeriodeData the line under the last objects from DocentUren. I need it next to each other. Thanks! -
Showing extra field on ManyToMany relationship in Django serializer
I have a ManyToMany field in Django, like this: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=50) pinyin_marks = models.CharField(max_length=50) translation = models.TextField() level = models.IntegerField() frequency = models.IntegerField() idiom = models.BooleanField() child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True) class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] class DictionaryChildChar(models.Model): class Meta: db_table = 'dictionary_child_char' from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary") to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary") word_order = models.IntegerField() Currently, I have a serializer like this: class FuzzySerializer(serializers.ModelSerializer): pinyin = serializers.CharField( required=False, source="pinyin_marks") definition = serializers.CharField( required=False, source="translation") hsk = serializers.CharField(required=False, source="level") class Meta: model = Dictionary fields = ["id", "simplified", "pinyin", "pinyin_numbers","definition", "hsk", "traditional", "child_char"] depth = 1 This gives me a dictionary entry, as well as the child dictionary entries associated with it (as a Chinese word is made up of several Chinese characters) However, I need to know what order these child characters are in, and hence why I have word_order. I would like this word_order field to appear on the individual child_char - how do I write my serializer in such a way that this additional field is present? Would I need to make a separate serializer for child_char? -
Grouping (not ordering) objects into alphabetical list on a single Django page
I’m trying to display a list of objects in an alphabetic list for a directory page. Something that looks like this: https://en.wikipedia.org/wiki/List_of_film_and_television_directors To avoid having to click on the link, the list would be: Surname starts with A • Anderson, Wes Surname starts with B • Burton, Tim Surname starts with C • Coppola, Sofia A simplified version of the model would be: class Person(model.Models): first_name = model.CharField last_name = model.CharField def __str__(self): return "{}, {}".format(self.last_name, self.first_name) Route 1. In the view? If not filtering in the template, after that I thought it would be possible to filter the objects within the view and send each portion separately. def person_list(request): startswith_a = Person.objects.filter(last_name__startswith="a") startswith_b = Person.objects.filter(last_name__startswith="b") startswith_c = Person.objects.filter(last_name__startswith="c") etc. etc. return render(request, "directory/person-list.html", {"startswith_a": startswith_a, "startswith_b": startswith_b}) But that feels wrong as I’d have to hard code the alphabet into the view definition, and then pass all 26 (or more) sets into the view. Route 2. In the model? Finally I thought it might be possible to have a new field in the model which would affix its location in the directory. This could be updated manually or (I guess?) by customising the save function on the model to …