Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django using loaddata from subfolder setup
Here's the INSTALLED_APPS setup INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... #imported old dependencies 'lamusoftware.blog', ] trying to loaddata to blog like so (kpsga) sam@sam:~/code/kpsga$ python manage.py loaddata blog < new_blog.json CommandError: No fixture named 'blog' found. or (kpsga) sam@sam:~/code/kpsga$ python manage.py loaddata lamusoftware.blog < new_blog.json CommandError: Problem installing fixture 'lamusoftware': blog is not a known serialization format. without restructuring the folder setup is there a way to make it work? -
Django not discovering models when moved into folder
My previous layout: project: app: models.py Right now it is like this: project: app: models: __init__.py model_name.py Because I have many more models now so I had to separate them. Inside project/app/models/__init__.py I have imported the model, hence I can import from app.models instead of app.models.model_name, but I'm getting ImproperlyConfigured. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed settings.py: APPS = [ 'comments', 'forums', 'notifications', 'posts', 'privatemessages', 'profiles', 'subforums', 'summaryreports', 'users', ] Users app layout: users.models.init.py: from users.models.user_backends import UserBackend from users.models.users import User users.apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' Why??? EDIT: In settings.py, also tried: APPS = [ 'comments.apps.CommentsConfig', 'forums.apps.ForumsConfig', 'notifications.apps.NotificationsConfig', 'posts.apps.PostsConfig', 'privatemessages.apps.PrivateMessagesConfig', 'profiles.apps.ProfilesConfig', 'subforums.apps.SubforumsConfig', 'summaryreports.apps.SummaryreportsConfig', 'users.apps.UsersConfig', ] Django version is 3.1. Python 3.8.5. WSGI and ASGI are properly pointing to settings.py. -
Converting Model object to Json in graphene
I am fetching models data using graphene resolver. Below is the models. class Movie(models.Model): name = models.CharField(max_length=100) genere = models.CharField(max_length=50) budget = models.FloatField() releaseYear = models.IntegerField() files = models.FileField(upload_to='', default="") Below is the resolver def resolve_all_movies(self, info, search=None): record_count=12 filtered_count=8 return session.query(Movie).all() Now I also wants to get the record count( in above it is hard coded). How to send all movie data and record_count and filtered_count. else how to convert movie objects to json so I can convert all the three data to json and return. -
Django NOT displaying SOME images on webpage
I am creating an app which is having categories of workers. So I hv created model for getting worker data and using that data I am displaying it on webpage. but when I want to display worker data of specific category Django showing some images on page, NOT ALL. here is my models.py: settings.py: urls.py: views.py : In views.py I have created to funtions (display()-It is used for displaying all worker data and its displaying all images also. display.html: for showing all worker data on a page Here is the one data along with image (output of display.html) Now coming to point as I said above that django is not displaying some images on page for specific category(checkout views.py in which category is Painter()) here is Painter.html: Here is the output of Painter.html: Notice that on this page the card which is not showing Image works fine on DISPLAY.HTML but not on PAINTER.HTML NOTE : I used ({{i.myfile}}) in painter.html because of that it is showing some images and not showing other image. In display.html I have used {{dest.myfile.url}} which works fine there and shows all images. But when i used {{i.myfile.url}} in painter.html. Its not showing any image at … -
I want to display just the years and not the dates and months using ajax in django
I want to display just the years and not the dates and months using ajax in django. Example: My code output1 displays in the format of a calendar. But I want to display as output2 containing just the years. output1: outpu2: My code are as follows: click.js $(document).ready(function(){ console.log("READY"); $("#datepicker").datepicker({ format: " YYYY", viewMode: "years", minViewMode: "years" }); }); layoutstyle.html <script src="{% static ' https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' %}"></script> <script src="{% static 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js' %}"></script> <link href="{% static 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css' %}" rel="stylesheet"/> <script src="{% static 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' %}"></script> <link href="{% static 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' %}" rel="stylesheet"/> <script src="{% static 'websitejs/click.js' %}"></script> <input type="text" id="datepicker" /> -
How to Seed add data in database in Django
I'm been trying to save data in database using seeder in Django. I want to add some data of my table usertypes and I think seeder is the only way to add it. The problem is how can I execute my seed.py file and save bunch of data into usertype table in database. Is there any trick or idea about this? seed.py from django_seed import Seed seeder = Seed.seeder() from .models import usertypes_tbl types = ["Super User", "Admin", "Customer"] descriptions = ["Super User", "Admin", "Customer"] status1 = ["Super User", "Admin", "Customer"] seeder.add_entity(user_type, types) seeder.add_entity(description, descriptions) seeder.add_entity(status, status1) inserted_pks = seeder.execute() python manage.py seed app/seed.py -
Django problem : How to extract data from a web
if i have a website: https://geodata.gov.hk/gs/api/v1.0.0/locationSearch?q=St.+Clare%27s+Primary+School which will show [{"addressZH":"","nameZH":"聖嘉勒小學","x":832498,"y":816065,"nameEN":"St. Clare's Primary School","addressEN":""}] How can I extract the text from the website using Django? i.e. given https://geodata.gov.hk/gs/api/v1.0.0/locationSearch?q=St.+Clare%27s+Primary+School Then,i need to get x=832498, y=816065 and use them in my program -
Internal Server Error:/admin/login/ DoesNotExist at /admin/login Site matching query does not exist`
Below are my setting files. I have them split into base.py (used for development and production), production (used for just production) and development (used for just development). After completing Coreys Blog series and a Udemy Ecommerce series, I have tried to merge the two together. On https://www.rossecommerce.com/, I am getting the error Internal Server Error:/admin/login/ DoesNotExist at /admin/login Site matching query does not exist. I have tried disabling 'django.contrib.sites' and changing SITE_ID to 2 (it was 1). I tried to look at the information in django_site, but could not figure out how to do it. Note - secret keys and email addresses have been modified, to prevent confidential info being leaked init.py from .base import * # from .local2 import * from .production import * base.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = "6a28569690e44af0de19f3eb6b3cb36cb448b7d31f881cde" DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', # third party 'storages', 'crispy_forms', 'mptt', #our apps 'blog.apps.BlogConfig', 'accounts', 'addresses', 'analytics', 'billing', 'carts', 'categorytree', 'discounts', 'marketing', 'orders', 'products', 'search', 'tags', 'properties', 'floppyforms', 'photologue', 'sortedm2m', 'photologue_custom', 'taggit', ] SITE_ID = 2 #SITE_ID = 'http://localhost:8000/' AUTH_USER_MODEL = 'accounts.User' #changes the built-in user model to ours FORCE_SESSION_TO_ONE = False FORCE_INACTIVE_USER_ENDSESSION= False … -
Django allauth, how to fetch email from all auth user model
I had been doing a lot of research of how to fetch email field in django allauth user model but I don't have any answer so i am turning to you please help me out i am stuck. In views.py i tried to fetch email from django allauth as per my understanding but don't know how to do it...!!! # Settings.py ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300 # Models.py class OrderItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE # Views.py order = Order.objects.get(user=self.request.user, ordered=False) cust_mail = order.user.email As you can see in the image that email is registered and entred in database I am stuck at a point where i dont know how to fetch it back, I really hope you guys can help me out!!!enter code here -
How do I change a field value in Django form based on input?
Let's say I have a form with 3 fields - Book, Title, Author. The user could manually enter the title and the author, but he can also choose a book from the Book field. When a book 'some_title(some_author)' is chosen, I want the Title and Author fields to automatically update to 'some_title' and 'some_author'. Can I do this with only Django/HTML or do I need something else like Javascript? How? I don't know anything about JS, sorry if this is basic stuff. -
How to send Django and Celery logs to CloudWatch
I use Django and Celery. I can send django logs to aws cloudwhatc. But I can't send Celery's logs. I'm waiting for your help. I use this for log. https://pypi.org/project/watchtower/ -
Configure NGINX with custom URL (server_ip/custom_name)
I'm trying to configure my nginx to access my site in this pattern IP_ADDRESS/folder_name Example 127.0.0.1/testapp. Currently i adjusted my nginx to this configuration location /test/* { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8082; break; } proxy_connect_timeout 600; proxy_read_timeout 600; alias /var/www/html/test/; } but whenever i try to access my site 127.0.0.1/testapp. i always get 404 error. and upon checking my nginx error log. I get the following 2020/10/28 03:34:01 [error] 8711#8711: *5 open() "/usr/share/nginx/html/test" failed (2: No such file or directory), client: xxxxx, server: localhost, request: "GET /test Btw i'm configuring django site. Thanks! -
Unit testing for Django login page
I'm currently trying to write unit tests for the built-in django login page, and I keep getting this error. ERROR: test_login_success (User.tests.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\---------------\User\tests.py", line 74, in test_login_success self.assertTrue(response.data['authenticated']) AttributeError: 'TemplateResponse' object has no attribute 'data' Codes: no view function because I used the Django built-in login page test.py def test_login_success(self): testuser = User.objects.create_user(username = 'howdycowboy', password= 'Testing123' ) response=self.client.post(self.login_url,{'username':'howdycowboy', 'password': 'Testing123'},format='text/html') #self.assertEqual(response.status_code ,302) self.assertTrue(response.data['authenticated']) #HTML code {% extends 'User/base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} I've also tried self.assertEqual(response.status_code ,302) it redirects once it logs in, but for some reason the response.statuscode is 200. % (response.status_code, status_code) AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) -
How to take data from model and display on the product page?
I am developing an ecommerce website with django, I can not show on the product page (product_detail.html) the dates from Product_details model, from other models I can display dates, for example, from the Product_image model and from Category model I already take dates and display without any problems. It seems that I did all steps right, but I can not display the dates. Please help me. urls.py: from django.urls import path from . import views from .views import ProductListView from django.conf.urls.static import static urlpatterns = [ # path('', views.home, name='amd-home'), path('', ProductListView.as_view(), name='amd-home'), # path('', views.home_page, name='amd-home'), # path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail'), path('product/<int:id>/', views.product_detail, name='product-detail'), path('about/', views.about, name='amd-about'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=200) parent_id = models.IntegerField(default=0) description = models.TextField() image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Brand(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Product(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/', blank=True, null=True) sku = models.CharField(max_length=200) price = models.IntegerField(default=0) price_old = models.IntegerField(default=0) description = models.TextField() status = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f'{self.title}, {self.description}' class … -
Django Admin Inline & TabularInline – Appending ordered text fields with a sql database structure
I have read and have tried some of the examples in https://docs.djangoproject.com/en/3.1/ref/contrib/admin/ in regard to appending additional objects. Essentially what I want is a Question to have multiple Answers and within the Admin Question area with the ability to get a [+] button to add additional questions. I want to get that working first; but down the road I also want to do the following: Ordered list of Answers: that is, ranked ordering to the questions. Ability to repeat Answers in the ordered list In models.py file from django.db import models class Question(models.Model): name = models.CharField(max_length=50) question = models.CharField(max_length=50) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) class Answer(models.Model): answer = models.CharField(max_length=50) In admin.py file: From .models import ( Question, Answer, ) class AnswerTabularinline(admin.TabularInline): model=Answer class QuestinAdmin(admin.ModelAdmin): inlines = [AnswerTabularinline] class Meta: model = Question admin.site.register(Question, QuestinAdmin) admin.site.register(Answer) This is a fairly standard implementation of tabular inline; however, I am linking it to a SQL database and I have added the following tables: CREATE TABLE "ModME_question" ( "id" INTEGER NOT NULL UNIQUE, "name" TEXT, "text" TEXT, "answer" INTEGER, FOREIGN KEY("answer") REFERENCES "ModMe_Answer"("id"), PRIMARY KEY("id" AUTOINCREMENT) ); CREATE TABLE "ModMe_Answer" ( "id" INTEGER NOT NULL UNIQUE, "text" TEXT, PRIMARY KEY("id" AUTOINCREMENT) ); -
How i can use a CreateView with the same model Post to create a Post(Parent) with comments Post(Children)?
Im trying to create a view to use it in two cases: Create a Post Create a Post with comment. Using the same model and view (Im open to use two views, but im looking for the Pythonic/Django way to do it). I dont know to do it with CBV -> CreateView Model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=500) image = models.ImageField(upload_to="user/post", blank=True) video = models.URLField(blank=True) comment = models.ForeignKey("self", on_delete=models.CASCADE, default=None, blank=True, null=True, related_name='comments') date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) featured = models.BooleanField(default=False) View: class PostCreateView(LoginRequiredMixin, CreateView): form_class = PostForm template_name = "core/post_create.html" def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.date_created = timezone.now() obj.save() return redirect("feed") Source code on Github -
converting ERD to django models
Is there any tool which can convert an ERD to django models ? NOT the other way round. I mean If I drew an ERD. is it possible to generate django models from it ? -
While appending a UUID field in to a list it also storig the type of the filed
I am having a model and it having a uuid field public_id = models.UUIDField( unique=True, editable=False, default=uuid.uuid4) I am getting an issue while filtering I am getting a query set like this <obj1,obj2, obj3...> I am looping through it and saving the public_id in a single list like this associated_elements = list() for i in query_set: associated_elements.append(i.public_id) print(associated_elements) I am getting output like this [UUID('a3d69af6-9678-4c1a-8adf-3b9f3600c3b5'), UUID('c0cc4cbd-9b79-4e04-bbc2-dcfb52a9e3de'), UUID('86cd21a5-0833-4b46-8dd8-bf730a3014ee'), UUID('70596f50-2e00-44e9-9795-fce13d33fdbb'), UUID('e60c88b3-1066-4ddd-bab6-7a33a84dd998')] But I need an output in this format ['7e254d14-488a-45ed-8712-fe1a339d6c28', '40949d78-8252-4087-b69e-2143915b2317'] Is there any way for that ? -
get Django model all related generic records
I have a Django model with a GenericForeignKey, and several other models pointing to it through GenericRelation: class InventoryAction(CustomModel): action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale', 'inventorysalecancellation', 'inventorystockinit')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción")) action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción")) action_object = GenericForeignKey('action_content_type', 'action_object_id') timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora")) class InventoryStockInit(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stock_init', verbose_name=_("Almacén")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios")) inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id') class InventoryInput(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén")) reference = models.ForeignKey(InventoryAction, null=True, blank=True, on_delete=models.PROTECT, limit_choices_to=Q(action_content_type__model__in=['inventorytransfer', ]), related_name='referenced_by', verbose_name=_("Referencia")) inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id') And I have a Django Rest Framework viewset that attempts to get all related records from the GenericForeignKey: class InventoryActionForListViewSet(viewsets.ViewSet): permission_classes = (permissions.IsAuthenticated,) def list(self, request): self.repository = request.query_params['repository'] inventory_actions = models.InventoryAction.objects.filter(inventory_action__repository_id=self.repository).order_by('-timestamp') inventory_actions_to_return = serializers.InventoryActionForListSerializer(inventory_actions, many=True) return Response(inventory_actions_to_return) The problem is that the view raises the following exception: django.core.exceptions.FieldError: Cannot resolve keyword 'inventory_action' into field. Choices are: action_content_type, action_content_type_id, action_object, action_object_id, batch, id, products, referenced_by, referenced_by_input_or_output, referenced_by_output, timestamp I can see that the GenericRelation is not being recognized. how can I execute the query I want, using generic relationships? -
How do I process in Django a text submit with "Post" or "GET" method from HTML?
I have a project to build a Wiki page in Django and I require to process a word sent from a search field and display its information on screen in case the word matches the stored information. For this I want to send a parameter with "POST" method from the following html template. <form action="{% url 'wiki:index' %}" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> </form> The idea is for the parameter to be received by the following functions of my file views.py written in Django. def index(request): if request.method == "POST": title = request.POST["q"] return redirect("wiki:languages") else: return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def languages(request, title): return render(request, "encyclopedia/definitions.html", { "title": util.get_entry(title) }) This file has the next header sentences: from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse from django.urls import reverse from . import util The "Languages" function in turn processes the get_entry(title) function of the "util.py" code def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None I have the following paths … -
Seeder insert bunch of data in database Django
I'm been trying to seed my data using python manage.py seed but it gives me an error below, All I want is to insert : Admin,Super admin etc. I been searching and reading documentation but its not working. Is there any expert can help me?It's almost three days Im been searching. Settings.py INSTALLED_APPS = [ 'app.apps.appconfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_seed', 'data_seeder', ] I also want to seed bunch of data, so I created a file seed.py under app folder: Reference link from django.core.management.base import BaseCommand import random MODE_CLEAR = 'clear' class Command(BaseCommand): help = "seed database for testing and development." def add_arguments(self, parser): parser.add_argument('--mode', type=str, help="Mode") def handle(self, *args, **options): self.stdout.write('seeding data...') run_seed(self, options['mode']) self.stdout.write('done.') def clear_data(): """Deletes all the table data""" logger.info("Delete Address instances") auth_permission.objects.all().delete() def create_usertype(): """Creates an address object combining different elements from the list""" logger.info("Creating address") usertype = ["Admin", "Super Admin", "MRB", "Customer", "Users"] //this is what I want to insert street_localities = ["Bakers Street", "Rajori Gardens", "Park Street", "MG Road", "Indiranagar"] pincodes = ["101234", "101232", "101231", "101236", "101239"] address = usertypes_tbl( user_type=random.choice(usertype), description=random.choice(street_localities), status=random.choice(pincodes), ) address.save() logger.info("{} address created.".format(address)) return address def run_seed(self, mode): """ Seed database based on mode :param mode: … -
Django read data from an sync_to_async db call
I'm trying to read some data that I need to get from the database in an async function. So i'm wrapping it with channels sync_to_async function. Now the issue is how do I access the actual data that I retrieved from the database? Currently it just outputs as this: <channels.db.DatabaseSyncToAsync object at 0x7f7b672ea6d0> Code: from ...models import admin_list from channels.db import database_sync_to_async def get_admins(): return admin_list.objects.values('name') @bot.event async def on_message(message): admin_names = database_sync_to_async(get_admins) print(admin_names) -
Django Rest Framework serializer field incorrectly named
When I run api request I get a following error: AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'email'. New user gets inserted in database anyway, email field is filleld properly. View: class Register(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'username', 'name', 'password'] def create(self, validated_data): user = User.objects.create_user(**validated_data), return user Model: class User(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True) username = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=60) date_of_birth = models.DateField(blank=True, null=True) bio = models.CharField(default='', max_length=10000) photo = models.ImageField(max_length=255, null=True, blank=True) email_verified_at = models.DateTimeField(null=True, blank=True) email_token_time = models.DateTimeField(null=True, blank=True) email_token = models.CharField(default='', max_length=64) password_token_time = models.DateTimeField(null=True, blank=True) password_token = models.CharField(default='', max_length=64) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) last_seen = models.DateTimeField(null=True, blank=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username', 'name'] objects = UserManager() class Meta: db_table = "User" def __str__(self): return self.username I also have custom user manager, but that is probably irrelevant, and works as user … -
What would be the most optimal/logical way to store answers to pre-determined yes or no questions to the database
I've been thinking: What would be the most optimal/logical way to store user answers to pre-determined 'yes or no' questions to the database. Note: the question model is in a one-to-one relationship with the user model. No. of Questions: 25 A: Store the questions as straight boolean variable/column to the database. Per user x 25 columns B: Store the questions as 'question' and boolean 'answer' to the database. Per user x 25 question rows, 1 user x 25 answer rows Which is faster? Please share your thoughts. -
Can't apply retrieved form data to multiple objects
I'm trying to use a form with one field (shown as a dropdown in rendered template.html) to change an attribute of multiple objects of the same model. However, for some reason I can't apply the retrieved form data to the objects. models.py: class Player(models.Model): class Race(models.TextChoices): HUMAN = "Human" UNDEAD = "Undead" race = models.CharField(choices=Race.choices) forms.py: class PlayerRaceForm(ModelForm): class Meta: model = Player fields = [ 'race' ] views.py: def index(request): players = Player.objects.all() player_race_form = PlayerRaceForm() if request.method == 'POST': print(player_race_form.errors) # nothing here print(player_race_form.non_field_errors) # see next code block if player_race_form.is_valid(): # it aint for some reason :/ for player in players: player.race = player_race_form.cleaned_data['race'] player.save() context = {'player_race_form': player_race_form,} return render(request, 'template.html', context) On print(player_race_form.non_field_errors): <bound method BaseForm.non_field_errors of <PlayerRaceForm bound=False, valid=False, fields=(race)>> I tried to bypass the is_valid and cleaned_data and made it work somehow, but it saved a noticeably wrong value not in the Race class. def index(request): players = Player.objects.all() player_race_form = PlayerRaceForm() if request.method == 'POST': print(player_race_form.errors) # nothing here print(player_race_form.non_field_errors) # see next code block for player in players: player.race = player_race_form['race'].value() # player.race = player_race_form.data['race'] #MultiValueDictKeyError player.save() context = {'player_race_form': player_race_form,} return render(request, 'template.html', context) Also tried to modify one object …