Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin class model issue
class TheList(admin.ModelAdmin): list_display = ['name', 'age'] actions = None I want to see a list in admin panel as readonly. If I use the below method it will show a list of objects which then need to be clicked on in order to display the name and age. readonly_fields = ['name', 'age'] I have tried using the below admin functions which didn’t fix the problem: has_delete_permission has_add_permission The list is still editable I tried using this with list_display: has_change_permission that made the class not viewable in admin panel I want it to be like list_display but readonly, is that even possible? -
Make another dataframe from pandas or make another table
mates, tried for 3 days to deal it with my own but unsuccesfully... I have these models: A patient: class Patient(models.Model): <...> hist_num = models.IntegerField(validators=[MinValueValidator(0)], primary_key=True) <...> def __str__(self): return f"{self.first_name} {self.last_name}" Group of labaratory Analysis: class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) # analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" An analysis (haemoglobin and etc.): class AnalysisType(models.Model): a_name = models.CharField(max_length=16) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) analysis_group = models.ManyToManyField(AnalysysGroup) And a patient analysis: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) I try to get a table with all analysis of my patient per day and sort by analysis types. My query seems like this analysis_qs = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date').distinct() df1 = pd.DataFrame(analysis_qs.values('analysis_type','analysis_date','analysis_data')) <...> return df1.to_html() And gives me: Result of {{df1 | save} I want to see sth like ideally + measurments | Data | Haemoglob| Red blood| Leuc | | -------- | -------- | -------- | -------- | | Data | Result | Result | Result | | Data | Result | Result | Result | -
Secure Django REST Api with react and keycloak
I'm new to the world of keycloak. I have a little trouble understanding some things. I understood well how to authenticate with React and get a JWT token. However I would like to protect a Django API with this JWT Token retrieved with React. And I don't see how to do it. The resources are scarce or from several versions. I am with Keycloak 20. Thx in advance. -
ImportError: cannot import name 'views' from project (C:\django_projects\project\project\__init__.py)
This is my first Django project. I tried to execute the code available at: https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ Just made few changes such as removed staff module and modified the file names. The tree structure of my project is shown below: c: manage.py project asgi.py settings.py urls.py wsgi.py __init__.py media static templates sudent_information_system admin.py │ Admin_Views.py │ apps.py │ base.html │ contact.html │ forms.py │ login.html │ models.py │ registration.html │ Student_Views.py │ tests.py │ views.py │ __init__.py │ ├───migrations │ __init__.py │ ├───templates │ home.html │ └───__pycache__ admin.cpython-37.pyc apps.cpython-37.pyc models.cpython-37.pyc __init__.cpython-37.pyc The code in urls.py is as follows: The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from . import views from . import HodViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', include('sudent_information_system.urls')), path('', views.home, name="home"), path('contact', views.contact, … -
AxiosError: Request failed with status code 403 - login and token
auth.js export async function loginUser(data) { const response = await axios.post( 'http://10.0.2.2:8000/api/rest-auth/login/', { username: data.username, password1: data.password, }, { headers: { "Content-Type": "application/json", } } ); console.log(response.data) LoginScreen.js import { useState } from 'react'; import LoadingOverlay from '../../components/ui-components/LoadingOverlay'; import AuthContent from '../../components/auth-components/AuthContent'; import { loginUser } from '../../util/auth'; function LoginScreen() { const [isAuthenticating, setIsAuthenticating] = useState(false); async function loginHandler(username, password1) { setIsAuthenticating(true); await loginUser(username, password1); setIsAuthenticating(false); } if (isAuthenticating) { return <LoadingOverlay message="Logging you in..."/> } return <AuthContent isLogin onAuthenticate={loginHandler}/>; } export default LoginScreen; setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } I've tried logging into both the REST API and Postman, and everything works fine - it returns the token to me once the right credentials are issued. But when I try to send the request via the login form from react native to django via axios, it gives me the error 403 forbidden by axios. On the contrary, the registration makes me carry it out both via REST API and via the registration form (React Native) and returns the token. -
Is it possible to calculate direction in Postgis & Django (GeoDjango)?
Is it possible to calculate direction to detect if users are moving in "similar" direction having a few of their last coordinates(Points) using PostGIS + Django (https://docs.djangoproject.com/en/4.1/ref/contrib/gis/)? I could't find information about this feature. -
Trying to get ForeignKey's names instead of pk in a QuerySet Django
Im trying to make a complex queryset and I want to include my ForeignKeys names instead of pk. I'm using ajax to get a live feed from user inputs and print the results on a DataTable but I want to print the names instead of the pk. Im getting a queryset and when I console.log it, sensor_name is not in there. My models are like this: class TreeSensor(models.Model): class Meta: verbose_name_plural = "Tree Sensors" field = models.ForeignKey(Field, on_delete=models.CASCADE) sensor_name = models.CharField(max_length=200, blank=True) class TreeSensorMeasurement(models.Model): class Meta: verbose_name_plural = "Tree Sensor Measurements" sensor = models.ForeignKey(TreeSensor, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) soil_moisture_depth_1 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_2 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_1_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_moisture_depth_2_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_temperature = models.DecimalField(max_digits=15, decimal_places=2) And my view looks like this: field_list = Field.objects.filter(user=request.user) tree_sensors = TreeSensor.objects.filter(field_id__in=field_list.values_list('id', flat=True)) Tree_Metrics = request.GET.getlist("Tree_Metrics[]") if Tree_Metrics is not None: for array in Tree_Metrics: From_T.append(array.split(',')[0]) To_T.append(array.split(',')[1]) try: statSensors = (TreeSensorMeasurement.objects .filter(sensor_id__in=tree_sensors.values_list('id', flat=True)) .filter(datetime__date__lte=To_T[0]).filter(datetime__date__gte=From_T[0]) .filter(soil_moisture_depth_1__lte=To_T[1]).filter(soil_moisture_depth_1__gte=From_T[1]) .filter(soil_moisture_depth_2__lte=To_T[2]).filter(soil_moisture_depth_2__gte=From_T[2]) .filter(soil_temperature__lte=To_T[3]).filter(soil_temperature__gte=From_T[3]) .order_by('sensor', 'datetime')) TreeData = serializers.serialize('json', statSensors) except: TreeData = [] The code above works correctly but I cant figure out the twist I need to do to get the TreeSensors name instead of pk in the frontend. An example … -
Registration form is not submitting
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django. This is the registration form <h1>Register</h1> <div> <form method="POST" action="{% url 'register' %}"></form> {% csrf_token %} {{ form.as_p}} <input type="submit" value="register" /> </div> Below is the views.py ` def register_page(request): form = CustomUserCreateForm() if request.method == 'POST': form = CustomUserCreateForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() login(request, user) return redirect('login') page = 'register' context={'page':page, 'form':form} return render(request, 'login_register.html', context) ` The forms.py ` class CustomUserCreateForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'name', 'password1', 'password2'] ` Its not throwing any error, rather just not submitting. I tried changing the input to button feature but it is still not working. Any Ideas? -
How deploy django application on your own company server?
I have a django application ready to go for production but my company gave me a suggestion which is having there own server and deployed there and honestly I have no clue how to acheive this. Any help with specific details would be highly appreciated -
I am getting IntegrityError NOT NULL constraint failed: login_new_user.sturesidance
In my template I have defined it like this, ` <!-- residance --> <div class="input-group mb-2 "> <span class="input-group-text w-25" for="residance">Residence</span> <input class="form-control text-bg-primary bg-opacity-10 text-dark text-opacity-50" type="textarea" name="stureisidance" cols="4" rows="5" placeholder="type current address" required> </div> ` In my models i have this filed . ` sturesidance=models.TextField() ` This is how I created my object, ` new_user.objects.create( stuname= stuname, stubirthday= stubirthday, stuphoto= stuphoto , stugemail= stugemail ,stugrade= stugrade , stuclass= stuclass,stuentrance= stuentrance , sturesidance= sturesidance ,stuguardian= stuguardian , stugtele= stugtele , stumother= stumother ,stumothertele= stumothertele ,stuotherskills= stuotherskills ,stucertificate= stucertificate ,stuletter= stuletter ,stumedical= stumedical ,stusports= stusports ,stupassword= stupassword ) ` Now I am getting error IntegrityError Exception Value: NOT NULL constraint failed: login_new_user.sturesidance -
<int:pk> or {pk} does not work in DRF router
I have an Comment which have an Article foreign key (so Article have an "array" of comments). I need to build an url to fetch theese comments using article's pk, but when I am trying to do smth like "articles/int:article_pk/comments/" or "articles/{article_pk}/comments/" drf router crates static route with path "articles/{article_pk}/comments/". How can I implement getting a comments using article pk? -
Cannot install mysqlclient for my Django project using pip on ZorinOS
Im new in Django. I am using python3.11.0 and pip 22.3.1 in django framework. I want to use mariaDB in my Django project. For that I have to install mysqlclient. I tried a lot of things, but it doesn't work. This error is coming when I try: pip install mysqlclient Output: (venv) kiril@noknow-PC:~/Work/django_project/mysite$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [44 lines of output] mysql_config --version ['8.0.31'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-311 creating build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-311/MySQLdb creating build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py … -
Why Django throws an error creating test database?
When I try to run tests on my Django project, it throws the following error creating the test database: django.db.utils.ProgrammingError: relation "users_websiteuser" does not exist If I run the project, everything works fine. I've already tried running all the migrations (makemigrations and then migrate) and deleting the test database, but it still doesn't work. How can I fix this? -
Django admin can't create records for model with self-referential foreign key
This is my model: class Customer(models.Model): name = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) referee = models.ForeignKey('self', on_delete=models.RESTRICT, blank=True, null=True) def __str__(self): return self.name When I try to create a customer via admin site I got this error: TypeError at /admin/customer/customer/add/ Field 'id' expected a number but got <Customer: my_customer_name>. How can I fix this? Thank you. -
Django, PgBouncer and DigitalOcean, How to work DB Connection Pools
I'm using digitalocean managed database with django. How to create connection pool? -
Is there a way to add custom data into ListAPIView in django rest framework
So I've built an API for movies dataset which contain following structure: Models.py class Directors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'directors' ordering = ['-id'] class Movies(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.IntegerField(blank=True, null=True) rank = models.FloatField(blank=True, null=True) class Meta: db_table = 'movies' ordering = ['-id'] class Actors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) gender = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = 'actors' ordering = ['-id'] class DirectorsGenres(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres') genre = models.CharField(max_length=100, blank=True, null=True) prob = models.FloatField(blank=True, null=True) class Meta: db_table = 'directors_genres' ordering = ['-director'] class MoviesDirectors(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors') class Meta: db_table = 'movies_directors' ordering = ['-director'] class MoviesGenres(models.Model): movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres') genre = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'movies_genres' ordering = ['-movie'] class Roles(models.Model): actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles') role = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'roles' ordering = ['-actor'] urls.py from django.urls import path, include from . import views from api.views import getMovies, getGenres, getActors urlpatterns = [ path('', views.getRoutes), path('movies/', getMovies.as_view(), name='movies'), path('movies/genres/', getGenres.as_view(), name='genres'), path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'), ] serializer.py from … -
Editing in Django admin reversed depended by foreign key
How in class QuestionsAdmin(admin.ModelAdmin) implement that in Django admin in Question can see all, add, edit and delete all Answers? class Answer(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) value = models.TextField() correct = models.BooleanField() question = models.ForeignKey("Questions", models.DO_NOTHING) class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) content = models.TextField() -
First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model?
I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py class User(AbstractUser): is_type1 = models.BooleanField(default=False) ... class Type1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite') views.py def FavoriteView(request, pk): current_user = request.user Type1.user = current_user.id buser = Type1.user Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite fuser = Type1.favorite if Type1.favorite.filter(id=request.user.id).exists(): Type1.favorite.remove(request.user) else: Type1.favorite.add(request.user) return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite})) class UserView(DetailView): model = User ... template_name = 'users/profile-details.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite favorite = False if favorite_connected.favorite.filter(id=self.request.user.id).exists(): liked = True data['user_is_favorite'] = favorite return data profile-details.html ... {% if user.is_authenticated %} <form action="{% url 'favorite' object.id %}" method="POST"> {% csrf_token %} {% if user_is_favorite %} <button type="submit" … -
Django Queryset to search for article title
I aim to search for the article title using a query set, I am following this 'basic filtering' guide however it doesn't work for me. terminal traceback- AttributeError: 'DeferredAttribute' object has no attribute 'filter' views.py class SearchResultsView(ListView): model = Article template_name = 'search_results.html' queryset = Article.title.filter(name__icontains='1st') I tried using queryset = Article.objects.filter(name__icontains='1st') however this resulted in the below which is why I used 'title' rather than 'objects' File "/Users/Lucas/Python/Projects/news/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1677, in names_to_path raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: author, author_id, body, comment, date, id, title models.py class Article(models.Model): title = models.CharField(max_length=225) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("article_detail", kwargs={"pk": self.pk}) I looked at this but can't get it to work. Also tried the documentation. If i remove the query set line at the bottom of the class the search function returns all of the values as per the below .html file. Which displays all the article content but without any filters of course. search_results.html <ul> {% for article in article_list %} <li> {{ article.title }}, {{ article.body }} {{ article.date }}{{ article.author }} </li> {% endfor %} </ul> Am I missing … -
Does anyone know if i can add an image upload function to a form with cloudinary?
I'm building a Django blog in which i want registered users to be able to create their own blog posts including a title image. i've incorporated cloudinary but can currently only upload images through the admin panel. After reading through the docs and a few similar questions here i am none the wiser. Has anyone encountered anything like this? Is it possible to just put an image upload in my form and tie that in to cloudinary somehow? please help! -
Django serializer returns empty dictionary on create
I have this model that basically joins two different users: class Couple(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) user1 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False, related_name="user1" ) user2 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False, related_name="user2" ) def __str__(self): return str(self.id) What I did next, was create a Serializer where user1 invites user2 to create a couple. And I want to do this by writing user2 email address: class CreateCoupleSerializer(serializers.Serializer): partner_email = serializers.EmailField(write_only=True, max_length=250, required=True) def create(self, validated_data): partner_email = validated_data['partner_email'] try: partner = User.objects.get(email=partner_email) except Exception: partner = None if not partner: raise serializers.ValidationError( {"details": 'User does not exist'}) if partner.couple_id: raise serializers.ValidationError( {"details": 'User is already assigned to a couple'}) user = self.context['request'].user couple = Couple.objects.create(user1=user, user2=partner) user.couple_id = couple.id partner.couple_id = couple.id user.save() partner.save() return couple And this is my view: class CreateCoupleView(generics.CreateAPIView): serializer_class = CreateCoupleSerializer queryset = Couple.objects.all() By testing this I can see that the Couple is being created, which is great! However, in my body response, I'm getting an empty dictionary instead of the new couple instance. My question is why is this happening? Bonus question: When should I create logic in def create() from the Serializer side vs def create() on the View side? … -
Annotate on reverse many-to-many
I'm trying to work out why this doesn't work:- class A(models.Model): contacts = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField() If I try and get a count of how many A there are with multiple contacts:- A.objects.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() there are 10. but if I have a particular contact and I want to get a count of how many A's they are connected to that have more than 1 contact on them:- B.a_set.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() I get 0. The num_contacts count always comes out as 1, even when the A has more than 1 contact. I must have missed something silly but I can't see it. Any ideas? -
django select_for_update(nowait=False) in transaction.atomic() does not work as expected
I have a django app that needs to get a unique ID. Many threads run at the same time that need one. I would like the IDs to be sequential. When I need a unique ID I do this: with transaction.atomic(): max_batch_id = JobStatus.objects.select_for_update(nowait=False).aggregate(Max('batch_id')) json_dict['batch_id'] = max_batch_id['batch_id__max'] + 1 status_row = JobStatus(**json_dict) status_row.save() But multiple jobs are getting the same ID. Why does the code not work as I expect? What is a better way to accomplish what I need? I cannot use the row id as there are many rows that have the same batch_id. -
"No such table" error coming from serializers.py file, when running migration command
I recently moved my Django app from using the default User model to a custom User model, and since this is not recommended to do mid-way through a project, I had to drop the database and migrations and recreate migrations and run migrate. This works fine when I comment out the entire serializers.py file, as well as comment out everywhere it is referred to. However, now that I want to be able to action all the new migration steps at production level WITHOUT having to comment out serializers.py. I know that I have referenced a table that doesn't technically exist so, I'm just wondering what is the best way to do this? Here is my serializers.py code: class MyModelSerializer(serializers.Serializer): features = Feature.objects.values_list("feature_name", flat=True) # Feature is a model feature = serializers.ChoiceField(features) # this is where the error happens The error says: "no such table: myapp_feature" -
Best way to store multiple date in one object django
I have model Topic. Now i have date = models.DateTimeField class Topic(models.Model): owner = models.ForeignKey(Profile, on_delete=models.SET(GUEST_ID)) seminar = models.ForeignKey(Seminar, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(default='') speaker_name = models.CharField(max_length=200, default='') date = models.DateTimeField(null=True, blank=True) but i want to save multiple date for example: 27.11.2022,29.11.2022,01.01.2023. I have idea to write date = models.CharField() and save dates as string Is there a better solution?