Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host
I am running locally this script. On postgres connection, I am facing "Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host". Database is up, I started it with docker run --publish 8000:8000 --detach --name db remoteaddress:latest When I do the same using docker-compose, and exec to django app and run it as management command, it works. The code: conn_string = "host='db' dbname='taras' user='postgres' password='postgres'" with psycopg2.connect(conn_string) as connection: with connection.cursor() as cursor: ... my stuff -
mysql 2006 error when filtering with large list of arguments
Say I have a model like this: class Order(models.Model): code = models.CharField(max_length=90, db_index=True, unique=True) When I have a list of codes, list_of_codes, with more than 600,000 elements and I try to get a list of codes that are in my database, I get a 'MySQL server has gone away' error on the second line below - which I think makes sense because that's when the queryset get evaluated so it's probably taking a while and the connection times out(?): duplicate_codes = Order.objects.filter(code__in=list_of_codes).values_list('code', flat=True) duplicates.update([some_dict[code] for code in duplicate_codes]) ## error gets thrown here I'm trying to understand why this is happening and what would be some good ways to fix this with scalability in mind. I can't find much in the django docs about filtering with a lot of data like this. For now, I'm partitioning the list of codes and doing the filtering in chunks. -
Inline with recursive self OneToOneField in Django's admin
I'm trying to display a read-only OneToOneField (recursive self) as Inline however in my admin I see it empty. I have the following model defined: class LogEntry(models.Model): data = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) origin_request_log = models.OneToOneField( 'APILogEntry', blank=True, null=True, related_name='response', on_delete=models.SET_NULL ) And in my admin.py: class APILogEntryInline(admin.StackedInline): model = APILogEntry readonly_fields = fields = ['created_at', 'data'] class APILogEntryAdmin(admin.ModelAdmin): list_display = list_display_links = ['created_at', 'data'] readonly_fields = fields = ['created_at', 'data'] admin.site.register(APILogEntry, APILogEntryAdmin) In my admin I see it like this: -
Not able to get Login user in Django Channels using WebsocketConsumer
I am not able to get login user in Django channels. I am using AuthMiddlewareStack but still facing the issue. Django channels error. Using WebsocketConsumer but not able to get current logged in user Consumers.py class TableData(WebsocketConsumer): def connect(self): print(self.scope["user"]) self.group_name='tableData' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() data = Game.get_games(1) self.send(text_data=json.dumps({ 'payload': data })) routing.py ws_pattern= [ path('ws/tableData/',consumers.TableData), path('ws/room/' , consumers.Room), path('ws/game/room/<room_name>' , consumers.ChatConsumer) ] application= ProtocolTypeRouter( { 'websocket':AuthMiddlewareStack(URLRouter(ws_pattern)) } ) `` -
Django: Logging to custom files every day
I'm running Django 3.1 on Docker and I want to log to different files everyday. I have a couple of crons running and also celery tasks. I don't want to log to one file because a lot of processes will be writing and debugging/reading the file will be difficult. If I have cron tasks my_cron_1, my_cron_2,my_cron_3 I want to be able to log to a file and append the date MyCron1_2020-12-14.log MyCron2_2020-12-14.log MyCron3_2020-12-14.log MyCron1_2020-12-15.log MyCron2_2020-12-15.log MyCron3_2020-12-15.log MyCron1_2020-12-16.log MyCron2_2020-12-16.log MyCron3_2020-12-16.log Basically, I want to be able to pass in a name to a function that will write to a log file. Right now I have a class MyLogger import logging class MyLogger: def __init__(self,filename): # Gets or creates a logger self._filename = filename def log(self,message): message = str(message) print(message) logger = logging.getLogger(__name__) # set log level logger.setLevel(logging.DEBUG) # define file handler and set formatter file_handler = logging.FileHandler('logs/'+self._filename+'.log') #formatter = logging.Formatter('%(asctime)s : %(levelname)s: %(message)s') formatter = logging.Formatter('%(asctime)s : %(message)s') file_handler.setFormatter(formatter) # add file handler to logger logger.addHandler(file_handler) # Logs logger.info(message) I call the class like this logger = MyLogger("FirstLogFile_2020-12-14") logger.log("ONE") logger1 = MyLogger("SecondLogFile_2020-12-14") logger1.log("TWO") FirstLogFile_2020-12-14 will have ONE TWO but it should only have ONE SecondLogFile_2020-12-14 will have TWO Why is this? … -
Unable to update individual items in Django
I am trying to update some information in my Django application but I am getting this error "Cannot assign "9": "Reservation.table" must be a "Tables" instance". I have tried so manual method also but it still same error. Error: Cannot assign "9": "Reservation.table" must be a "Tables" instance views.py @login_required def UpdateReservation(request, pk): table_exists = get_object_or_404(Reservation, id=pk) form = ReservationForm(instance=table_exists) if request.method == "POST": form = ReservationForm(request.POST, instance=table_exists) if form.is_valid(): form = ReservationForm(request.POST, instance=table_exists) if form.is_valid(): form.save() return redirect('view_reservations') messages.success(request, "successfully updated table") context = {"form": form} return render(request, "dashboard/super/landlord/update_reserve.html", context) models.py class Reservation(models.Model): status_choices = ( ("pending", "pending"), ("confirmed", "confirmed") ) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField() phone = PhoneNumberField(blank=True) people = models.IntegerField(default=1) time = models.TimeField() date_reserved = models.DateField() date_booked = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=status_choices, default="confirmed") comment = models.TextField(blank=True) table = models.ForeignKey(Tables, on_delete=models.CASCADE) def __str__(self): return self.first_name forms.py class ReservationForm(forms.ModelForm): time = forms.CharField( widget=forms.TextInput(attrs={'id': 'timepicker', 'class': 'input-group', 'placeholder': '12:00:AM'})) date_reserved = forms.DateField(widget=forms.TextInput( attrs={'placeholder': 'yyyy-mm-dd', 'id': 'datepicker'}), required=True,) comment = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Leave a message'}), required=True,) first_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Leave a message'}), required=False,) email = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Your Email Address'}), required=True,) phone = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Your Telephone number'}), required=True,) table = forms.IntegerField(widget=forms.TextInput( attrs={'placeholder': 'Table Number'}), … -
If radio is checked on submit jQuery
im trying to check if a radio button is checked on submit of a form. Ive researched but i didnt get it to work. It might be a silly mistake or type but ive been trying for hours now. The two different methods i tried are. $("#form").submit((e) => { e.preventDefault(); if ($("#radio").attr("checked") == "checked") { alert("checked"); } if ($("#radio").is("checked")) { alert("checked"); } }); And the html is: <form action="" method="POST" id="form"> {% csrf_token %} <label for="radio"> <input type="radio" name="" id="radio" /> </label> <button type="submit">Submit</button> </form> </div> Im doing this in django also. Thanks for any replies and sorry if im just making a silly mistake. -
If I have a separate models for an item and a separate model for the images relating to that item, how can I combine these into a query?
I am trying to display in a card view the items from my queryset. I have a model for Item and a separate model for ItemImage to allow several uploaded images for a single item. Each image also has a property is_primary to determine if it's the image that will be displayed in the dynamically generated cards. I've succeeded in displaying item details from my item model queryset. However, I am struggling to understand how I can combine the itemimage.url attribute with the all_items context I am passing into the template. How can I make sure that the images from my image queryset match the pk of the item they are assigned to and are also the primary photo for that item? views.py from django.shortcuts import render, redirect # Create your views here. from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .models import Item, ItemImage def home(request): all_items = Item.objects.all() item_images = ItemImage.objects.all() ItemImage.objects.filter(is_primary=True) context = {'items': all_items} return render(request,'items/home.html',context) models.py from django.db import models from django.utils import timezone from decimal import Decimal # Create your models here. class Item(models.Model): name = models.CharField(max_length=70) date_added = models.DateTimeField(default=timezone.now) price = models.DecimalField(max_digits=9, decimal_places=2, default=Decimal('0.00')) description = models.CharField(max_length=300) def … -
How to Change Django AbstractUser Group to String
I made some groups inside of Django Admin, but whenever I add a user to one of those groups, only the group ID displays inside of my API endpoint. Is there a way to display the string name? So instead of 1, I want the field to be "Directors". Does it have anything to do with extending the AbstractUser Model? This is all I have right now, for my User info: class User(AbstractUser): -
How to create user and then login client in django test
I am developing a web application using Django 3.1.4. My app allows register and login and now I want to write some tests. To reach this I need a logged testing-user. And here is a question: How to do it ? I found many many solutions like : self.user = User.objects.create_user(username='testuser', password='12345') self.client.login(username='testuser', password='12345') etc. etc. but I am confused where should I looking for data to pass inside create_user(....), how many args should I pass ? In register form ? In my Profile Model ? my example test: def setUp(self): User = get_user_model() user = User.objects.create_user('test12345', 'test@gmail.com', 'test12345') def test_profile_response(self): url = reverse('profile') self.client.login(username = 'test12345', password = 'test12345') response = self.client.get(url) self.assertEquals(response.status_code, 200, msg ='login request is invalid') Here are the whole code: https://github.com/Equilibrium23/Walk-For-The-Dog -
Django Channels - self.channel_layer.group_send not working
I am trying to configure my Channels application for deployment. All is good until I connect to a websocket. I'm mainly using websockets for chat and "announcements". However, when I connect and try to send a message, my consumer receives it but doesn't send anything back. asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import re_path from . import consumers application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": (URLRouter([ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ])) }) consumers.py: import json from asgiref.sync import AsyncToSync as b from channels.generic.websocket import AsyncWebsocketConsumer, WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group b(self.channel_layer.group_add( self.room_group_name, self.channel_name )) print("connected!") self.accept() def disconnect(self, close_code): # Leave room group b(self.channel_layer.group_discard( self.room_group_name, self.channel_name )) # Receive message from WebSocket def receive(self, text_data): data = json.loads(text_data) message_type = data['body_type'] body = data['body'] send_data = { 'type': message_type, "body": body } print(send_data) # Send message to room group send = b(self.channel_layer.group_send( self.room_group_name, send_data )) print(send) # Receive message from room group def message(self, event): # Send message to WebSocket b(self.send(text_data=json.dumps({ 'message': event }))) CHANNEL_LAYERS in settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } When … -
How to automatically update model fields in Django?
So I have this simple models: class Room(models.Model): STATUS = ( ('Available', 'Available'), ('Occupied', 'Occupied'), ) status = models.CharField(choices=STATUS) name = models.CharField(max_length=200) class Reservation(models.Model): STATUS = ( ('Confirmed', 'Confirmed'), ('Pending', 'Pending') ) status = models.CharField(choices=STATUS) room = models.OneToOneField(Room, on_delete=) date_created = models.DateTimeField(auto_now_add=True) I want that whenever I create a new Reservation and assign a room to it, the status field of that particular Room is automatically changed to 'Occupied'. I think there is a way to do this with Django Signals but I haven't figured out how to implement it on my own yet. Thanks in advance. -
What kind of IntegrityError is Django raising during test?
I am running the below test: from django.db import IntegrityError def testInvalidSubAndOutcodeCombination(self): with self.assertRaises(IntegrityError): Property.objects.create( property_id=1234567, property_type='Flat', property_outcode=self.outcode, property_sub_outcode=SubOutcode(self.outcode, sub_outcode='FAIL'), bedroom_count=1, property_url='https://www.rightmove.co.uk/' ) It should pass as it should raise an IntegrityError. It raises an IntegrityError but the test fails: ERROR: testInvalidSubAndOutcodeCombination (snippets.tests.models.TestModels) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 282, in _setup_and_call self._post_teardown() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 1005, in _post_teardown self._fixture_teardown() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 1163, in _fixture_teardown connections[db_name].check_constraints() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 343, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'property' with primary key '1234567' has an invalid foreign key: property.property_sub_outcode_id contains a value 'FAIL' that does not have a corresponding value in sub_outcode.sub_out code. What "kind" of IntegrityError is this if it's not from django.db import IntegrityError ? I've tried django.db.backends.sqlite3.base.IntegrityError but the result is the same: ====================================================================== FAIL: testInvalidSubAndOutcodeCombination (snippets.tests.models.TestModels) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Arturka\Documents\repos\ldnRentAPI\snippets\tests\models.py", line 66, in testInvalidSubAndOutcodeCombination Property.objects.create( AssertionError: IntegrityError not raised -
imagefield.url not working, setting up media_url, media_root, and static_url
The problem: I'm trying to display Notification objects that I have assigned to each user. Each notification has an icon I want to display. I set the <img> src attribute to {{ notif.icon.url }}, but i'm seeing the icon for a bunch of unloaded images instead. I think I need to change MEDIA_ROOT and MEDIA_URL and STATIC_URL, but I'm not really sure how. notification-btn.html <div data-simplebar style="max-height: 230px;"> {% for notif in notifications %} <a href="" class="text-reset notification-item"> <div class="media"> <img class="avatar-xs mr-3 rounded-circle" src="{{ notif.icon.url }}"> From inspecting element, I see that it's trying to load the url 127.0.0.1:8000/media/user_icons/logo.png. This is almost correct, the image exists at 127.0.0.1:8000/static/media/user_icons/logo.png. I've been working on an existing django project and the person who started it wasn't very confident in their python/django abilities. I see a lot of tutorials recommend putting the static/ folder inside each project directory. Instead, this django project currently has a static/ folder in the project root directory. There is a media/ folder inside of static. Our file tree looks like lpbs_website/ lpbs_website/ settings.py urls.py wsgi.py, asgi.py, __init__.py... static/ media/ uploaded_files/ user_icons/ images/, css/, js/, ... templates/ manage.py And our settings.py... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') … -
modules cannot load in a new Django project
I made 2 projects with django so far and everything smooth. using python 3.6 and conda env with django 3.1.4 I am following the tutorial to kick off my new project as I did for my previous one : https://docs.djangoproject.com/fr/3.1/intro/tutorial01/ Start a new one using "django-admin startproject ngedemocarto" then used "django startapp sitemanager" it gives me this : but suddenly in this project I keep having error when I try to call any app module like "apps.py" or "urls.py" typical error if I add the app config in settings.py like this : INSTALLED_APPS = [ 'sitemanager.apps.SitemanagerConfig' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] resolve in this error : ModuleNotFoundError: No module named 'sitemanager.apps.SitemanagerConfigdjango'; 'sitemanager.apps' is not a package every command like manage.py runserver or manage.py migrate is failing at import because it can't resolve any names like "sitemanager.apps" or "sitemanager.urls" I checked basic things : I have a init.py at sitemanager root folder urls.py or apps.py exist if I use python in cmd at mynewproject folder and try import "sitemanager.apps" , it works. ( no error) I am in a very basic config just after starting this new project and nothing works ... I tried to build a new conda … -
How to make cart for multi vendor in Django
Should I make separate cart model and app or can I filter session for a particular model Like: If request.session['key'] has product1 model then ... do something -
How can I display glyphicon-plus in django?
i'm making my blog site via django. but plus icon is not working in post.html :( what is wrong? directory path is blog/templates/base.html, blog/templates post.html What I've tried to do: move the <div class "page-header"> to post.html If you need any information I didn't provide, please ask and I will. Guys, what is wrong? Thanks in advance for any help! base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'blog/style.css' %}"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </head> <body> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Django Project</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" ariacontrols="navbarSupportedContent" aria-expanded="false" aria-lable="Toggle navigation"> <span class="navbar-toggle-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home:home' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'polls:index' %}">Polls <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'bookmark:list' %}">Bookmark <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'blog:post_list' %}">Blog <span class="sr-only">(current)</span></a> </li> </ul> </div> </nav> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'blog:post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> {% endif %} <h1><a … -
How to perform query in Django
I need to filter the a particular user's bar in whcih reservations were made. I am a beginner in Django and have tried some methods which unfortunately didn't work. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class Bar(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class Tables(models.Model): table_no = models.CharField(max_length=14, unique=False) bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE) def __str__(self): return self.table_no class Reservation(models.Model): first_name = models.CharField(max_length=200) table = models.ForeignKey(Tables, on_delete=models.CASCADE) def __str__(self): return self.first_name Note: I wan to filter the reservations made in a particular user's bar -
TemplateSyntaxError at 'bootstrap4' is not a registered tag library. Must be one of: bootstrap is installed and in INSTALED_APPS
I am trying to use bootstrap_datepicker_plus and to do that I need bootstrap4. I have installed it. when I run pipenv run pip freeze, I see: django-bootstrap==0.2.4 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==2.3.1 django-compressor==2.4 django-jquery==3.1.0 and I have in settings.py: INSTALLED_APPS = [ "bootstrap4", "bootstrap_datepicker_plus", But I still see TemplateSyntaxError at /myapp/ 'bootstrap4' is not a registered tag library. Must be one of: when I include {% load bootstrap4 %} in my template. Does anyone have an idea of why the tag is not registered? I have restarted the server. -
Django Model Form is_valid returning False always
I am new to django, my is_valid() doesn't seem to work here, my code: forms.py: class ImageForm(ModelForm): class Meta: model = Image exclude = ['album'] models.py class Image(models.Model): image = models.ImageField(upload_to=save_path) default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) def __str__(self): return self.image views.py if request.method == 'POST': form = ImageForm(request.POST) if form.is_valid(): print('form.is_valid working') return render(request, "auctions/index.html") -
Checking for duplicate email address causing Bad Request error
I have a form for creating new users and I've added clean_email function for checking if the email address already exists like this: class NewUserForm(ModelForm): class Meta: model = Student fields = __all__ def clean_email(self): email = self.cleaned_data.get('email') try: match = User.objects.get(email = email) except User.DoesNotExist: return email raise forms.ValidationError('User with this email address already exists.') Unfortunately, after I try to test this by attempting to register a user with an email address that already exists I get the This page isn't working error in my browser. I'm not sure why this is happening, can anyone help? -
Retrieve instance DRF
I am trying to retrieve an instance that does not exist. Whenever I send GET by postman it returns "detail": "Not found." And whenever an instance does not exist I want it to be created, but can't set up proper condition. What should I type instead of None, or how can I improve this code to work in a proper way. def retrieve(self, request, *args, **kwargs): instance = self.get_object() if instance == None: instance = Cart.objects.create(owner=self.request.user) serializer = self.get_serializer(instance) return Response(serializer.data) -
How to filter a type of user in Django
I am working a particular web application. I have made use of the Django Abstract user has my application has different types of user. I have the admin user as well as the bar owner. I need to be able to return the number of bar owners in the application but don't know how to go about it. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_landlord = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) Note: I need to be able to return the number of is_landlord -
Django rest framework - set default serializer for a class
In my code, I have a few models with multiple custom properties: @dataclass class Value: amount: float currency: str class MyModel(models.Model): ... @property def v1(self) -> Value: ... @property def v2(self) -> Value: ... @property def v3(self) -> Value: ... An I have the following serializer: class MyModelBaseSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [..., "v1", "v2", "v3"] When serializing any MyModel instance, a TypeError raises: TypeError: Object of type Value is not JSON serializable. I know this can be solved by explicitly adding v1, v2, v3 as fields inside MyModelBaseSerializer, but I don't want to do that: I have many models with Value properties. I want the default DRF serializer to know how to serialize Value instances. I tried overriding to_representation, but that didn't seem to work. I want something similar to overriding the JSONEncoder.default(o) method, but I don't see how to tell DRF which encoder to use. -
When want to acces forms: ModelForm has no model class specified
I have a mistake but I don't understand the reason. I everytime use this method. But now not working. I try old way its working but then lot of code working. How I can pass this error? Why I have these error? Can you tell me about this? error typye: ModelForm has no model class specified. Models.py; from django.db import models from django.db.models.base import Model # Create your models here. class Personel(models.Model): KullaniciAdi=models.CharField( max_length=8, verbose_name="Kullanıcı Adı", null=False, blank=False, unique=True, error_messages={ "unique":"Böyle Bir Kullanıcı Mevcut.", "null":"Kullanıcı Adı Boş Bırakılmaz", "blank":"Kullanıcı Adı Boş Bırakılmaz", "max_lenght":"Kullanıcı Adı 8 Karekteri Geçmemeli" } ) Parola=models.CharField( max_length=18, verbose_name="Parola", null=False, blank=False, error_messages={ "max_lenght" : "Parolanız Çok Uzun", "null":"Parola Boş Bırakılmaz", "blank":"Parola Boş Bırakılmaz" } ) IsimSoyisim= models.CharField( max_length=30, verbose_name="İsim Soyisim", null=False, blank=False, error_messages={ "null":"İsim Boş Bırakılmaz", "blank":"İsim Boş Bırakılmaz", "max_lenght":"Girilen İsim Çok Uzun" } ) Email = models.EmailField( max_length=50, null=True, verbose_name="E-Mail", blank=True, unique=True, error_messages={ "max_lenght":"Mail Adresi Çok Uzun", "unique" : "E-Posta Adresi Kayıtlı" } ) Telefon = models.EmailField( max_length=11, verbose_name="Telefon", null=True, blank=True, unique=True, error_messages={ "max_length" : "Numara Çok Uzun", "unique":"Numara Kayıtlı" } ) MagazaID=models.ForeignKey( "auth.User", on_delete=models.CASCADE, verbose_name="Firma Adı" ) MagazaYoneticisi=models.BooleanField( verbose_name="Mağaza Yöneticisi", null=True ) TeknikServis=models.BooleanField( verbose_name="Teknik Servis", null=True ) HesapOlusturmaTarihi=models.DateTimeField( auto_now_add=True, verbose_name="Oluşturulma Tarihi" ) HesapGuncellenmeTarihi=models.DateTimeField( auto_now_add=True, verbose_name="Güncellenme …