Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Migrations with multiple legacy databases with multiple tables in same app
Need help with migrations of already existing databases (MySQL) with lots of tables and data. These databases were manually being updated from CLI but now they need a web interface with all the stats and collaborations etc. The tables are connected between DBs and let's say there are 10tables in db1, 5 tables in db2. I have two apps 'login' and 'main'. Login: The 'default' database is being used for authentication/login. model.py is in app 'login'. Db setting for 'default' is in settings.py This is working fine. Initial migrations worked. Main: Second app, 'main', is suppose to connect to two databases, db1, db2 and fetch/update/remove data to already existing data through views. I added the mysql connector to settings.py with database parameters and it's able to connect via dbshell. Connection is working. Using 'inspectdb' I got the two models, one from each database (m1.py, m2.py). The 'models.py' in main app is empty for now. 'managed' in meta is False for all classes generated via inspectdb. Q: How to put all the tables/classes from both the databases (m1, m2) into models.py and do migrations? If I do migrate it can affect the 'default' (please correct me). If I specify the --database … -
Python/Docker - Method delete not allowed Django
I am trying to run a program using docker that will allow me to destroy requests by using a program called PostMan to do this I have set up a class named ProductViewSet which will allow me to delete a query. But when I run docker-compose up in my Visual Studio Terminal and try to run a DELETE query through PostMan it gives me an error in PostMan that says "detail": method "DELETE" not allowed. I have tried to use the @action function to try and link the destroy function from my views.py to my urls.py in the same folder using this answer Method Delete Not Allowed - destroy() method Django, I have also tried to just use my main function Product and use a router as seen in this answer "detail": "method \delete\ not allowed" django but both of these answers do not help me at all. Here is my error that I am getting in PostMan and in my Visual Studio Terminal: Postman: { "detail": "Method \"DELETE\" not allowed." } Visual Studio Terminal: backend_1 | 172.19.0.1 - - [16/Mar/2022 00:58:14] "DELETE /api/products HTTP/1.1" 405 - Here are my requirements.txt, Dockerfile, docker-compose.yml, and views.py files respectivly: requirements.txt: Django==3.1.3 djangorestframework==3.12.2 … -
Delete db.sqlite via terminal (Django)
I'm currently deploying a project to Heroku, however it returns me the following error: ValueError: Related model 'store.user' cannot be resolved. But there is a way to avoid such error locally. You simply do: py manage.py migrate store And then py manage.py migrate In other words, if I migrate separetely, I won't face such error. However, Heroku migrates all together, then the deploy fails because of this error. If I proceed locally as Heroku does, i.e. run py manage.py migrate I can effortlessly click on and delete the db.sqlite3 file and makemigrations and migrate separetely. Then the issue would be resolved. However, that's not possible when deploying to Heroku. Thus, how can I delete this file only via terminal? I have been searching, but people only say you click on the file and the delete it, which for me it is not possible. Thanks -
How to add source code option to Rick text field in django
I want to add the source code functionality to my rich text field in Django and I don't know how to go about it. I already know how to install and setup rich text field but how to add the source code functionality is what I need -
Call html file in iframe with javascript, in a django project
I want to open a html file of a Django application, in a javascript. document.getElementById("iframe_id").src = "{% url 'application/file.html' %}"; I receive the error : Exception Type: NoReverseMatch Exception Value: Reverse for 'application/file.html' not found. 'application/file.html' is not a valid view function or pattern name. -
DRF DefaultRouter pk/slug
I noticed that sites such as SO and Reddit use <basename>/<pk>/<slug>/ for the detail view of posts, which makes me think that this should be the standard. Is there a way to accomplish this in drf using routers and ModelViewset? example of ModelViewset: class PostViewSet(viewsets.ModelViewSet): ... lookup_fields = ['pk', 'slug'] example of DefaultRouter : router = DefaultRouter() router.register('posts', PostViewSet, basename='post') app_name = 'api' urlpatterns = [ path('', include(router.urls)), ] URL patterns: /api/post/ api.views.PostViewSet post-list /api/post/<pk>/<slug>/ api.views.PostViewSet api:post-detail /api/post/<pk>/<slug>\.<format>/ api.views.PostViewSet api:post-detail /api/post\.<format>/ api.views.PostViewSet api:post-list -
Authentication credentials weere not provided when signing up
Building Django APIs to help me handle both the signup and login process for my React app. I am able to successfully login (get an access and refresh token from Django upon login), but having difficulties connecting my React signup process to Django to create a new user. This is the error I am getting on my console: POST http://127.0.0.1:8000/users/ 401 (Unauthorized) onSubmit @ Signup.js:32 and on my network: Authentication credentials were not provided. This is what I have in my serializers.py from django.contrib.auth.models import User from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only':True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], password=validated_data['password'], email=validated_data['email']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) class PasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) accounts.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('signup.urls')), ] signup.urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from .api import RegisterApi router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', … -
Posting images to userProfile django
I was able to automaticcaly create a userProfile everytime a user is created but I want to be able to modify somefields in the userprofile. So my Model.py def upload_path(instance,filename): return 'users/avatars/{0}/{1}'.format(instance.user.username, filename) class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE, related_name='userprofile') Profileimage= models.ImageField(upload_to=upload_path, blank=True, null=True, default='user/avatar.jpeg') def __str__(self): return self.user.username @ receiver(post_save,sender=User) def create_user_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) My Serializer.py class UserSerializer(serializers.ModelSerializer): #ProfileImage=serializers.ImageField(allow_null=True, use_url=True) class Meta: model = User fields =['id', 'username','password','email'] extra_kwargs={'password':{'write_only':True, 'required':True}} def create(self,validated_data): user =User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class UserProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: model =models.UserProfile #lookup_field = 'username' fields= ['id','user','Profileimage'] My view.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer lookup_field = "username" The page looks like : enter image description here So how can I modify the picture of the user, I tried to add forms but I couldn't match the username, sometime I guet the error Userprofile has no user. Anyhelp? -
Django no such table: Fligts_country when trying to migrate app model using Foreign key
Intro Hi, first off thanks in advanced for helping. I am learning the Django framework and I am having trouble trying to create a simple relation between two tables in my model. I am running django and mysql in docker in two separate containers, created by a docker-compose file (code is down below) and so far I have not been able to create the tables (migrations). Problem When I execute the command: python manage.py migrate --database=mariadb I get as a result: django.db.utils.OperationalError: no such table: Fligts_country In other posts similar to this one (Django - no such table exception for example) I see that a common solution is to remove the pycache folder and migrations as well, but this is not working for me and I have been strugling for some time now... Desired Solution I need the tables to be created in the database, but most importantly I want to know what is exactly wrong with my code. I assume that there is something that I am missing about Foreign keys. My code so far Docker-compose.yml version: '3' services: travel-crawler: restart: always container_name : travel-crawler build: ./Crawler tty: true ports: - '9005:8080' volumes: - type: bind source : E:\python-code\Traveler\Crawler … -
Passing context to serializer from Viewset
I have Viewset with get_serializer_context method class UserRetrieveView(generics.RetrieveAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = UserProfilePageSerializer def get_serializer_context(self): context = super(UserRetrieveView, self).get_serializer_context() context.update({'room' : self.get_object().room_set.all()}) print(context['room']) return context And now I want to put this context to my serializer : class UserProfilePageSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'name','bio'] Honestly I have no idea how to do this. I would really appreciate any help or even some clue -
Django passing data through the url, not finding page in url patterns
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns Error: Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order: admin/ [name='Home'] appointment-Maker/ account/ admin-home view_appointment/<id>/ login/ [name='Login Page'] registration/ [name='Registration Page'] logout [name='Logout Page'] The current path, adminview_appointment/21/, didn’t match any of these. GroomingService.urls #urls urlpatterns = [ path('admin/', admin.site.urls), path('', Home_view, name="Home"), path('appointment-Maker/', include('appointmentApp.urls')), path('account/', include('accountApp.urls')), path('admin-home', include('adminApp.urls')), path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding path('login/', Login_view, name='Login Page'), path('registration/', Registration_view, name='Registration Page'), path('logout', Logout_view, name='Logout Page') ] adminApp/views.py viewAppointment_view def viewAppointment_view(request, id): appointments = Appointment.objects.get(id = id) context = { 'appointments' : appointments } return render(request, "admin_templates/viewappointment.html", context) templates/admin_templates viewappointment.html {% extends 'base.html' %} {% block content %} <a>appointment view</a> {% endblock %} templates/admin_templates adminhome.html (the link is clicked through this page) {% extends 'base.html' %} {% block content %} <a>this is the admin page</a> <br> {% for a in appointments %} <a href="adminview_appointment/{{a.id}}/">Client name:{{a.client_dog_name}}</a><br> {% comment %} this is the link that is clicked {% endcomment %} {% endfor %} <br> <a>find month</a> <form method="POST"> {% csrf_token %} … -
How to iterate through queryset and get value Django
I wanna do a simple recommendation system based on users' Animals that they added. I want to show only products of a category, that's been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset? class MyAnimal(models.Model): name = models.CharField(max_length=256) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) class Product(models.Model): product_category = models.ManyToManyField(EcommerceProductCategory) def list(self, request): zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3} qs = MyAnimal.objects.filter(user=self.request.user) #checking if there is an animal with user == self.request.user if qs: if len(qs)==1: # if user has only 1 animal, get that animals race and if compare it with the dictionary to get product__product_category … -
heroku error - template does not exist at / web/index.html
i have been stumped for days, trying to figure this out. Ive looked at every stack overflow post relating to this and now I'm resorting to making my own. all the other posts say the error has something to do with the settings.py file so here it is: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent.parent ALLOWED_HOSTS = [ '127.0.0.1', 'd1sbot.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'botfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'botfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ os.path.join(os.path.dirname(__file__) ,'../templates').replace('\\','/') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # … -
How to get data from django orm inside an asynchronous function?
I need to retrieve data from the database inside an asynchronous function. If I retrieve only one object by executing e.g: users = await sync_to_async(Creators.objects.first)() everything works as it should. But if the response contains multiple objects, I get an error. @sync_to_async def get_creators(): return Creators.objects.all() async def CreateBotAll(): users = await get_creators() for user in users: print(user) Tracing: Traceback (most recent call last): File "/home/django/django_venv/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/django/django_venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_venv/src/reseller/views.py", line 29, in test asyncio.run(TgAssistant.CreateBotAll()) File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/django/django_venv/src/reseller/TgAssistant.py", line 84, in CreateBotAll for user in users: File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/home/django/django_venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. -
django show last 3 char of string in admin fields
database | id | salary_number | | --- | ------------- | | 1 | 1042 | models.py class user(AbstractUser): salary_number = models.CharField(max_length=4, unique=True, null=True, blank=True) def __str__(self): return f'{self.salary_number[-3:]}' admin.py class UserAdmin(admin.ModelAdmin): fields = ('salary_number[-3:]',) I would like to show Salary number: 042 in admin fields instead of 1042. Is it possible? -
creating/deleting folders in runtime using heroku/django
I have developed a Django app where I am uploading a file, doing some processing using a project folder name media. Process: user uploads a csv file, python code treats the csv data by creating temp folders in Media folder. After processing is complete, these temp folders are deleted and processed data is downloaded through browser. I am using the below lines of code to make and delete temp file after processing temp = 'media/temp3' os.mkdir(temp) shutil.copyfile('media/' + file_name, temp + '/' + file_name) shutil.rmtree(temp, ignore_errors=True) To set the media root, I used the below lines in settings.py which I am sure I am not using in other parts of the code. MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" Everything works fine when I run the app on local host. but as soon as i deployed it to heroku, it seems like these folders were not created/not found. I am looking for: Either a solution to create, read and delete folders/files in runtime using heroku, or a better way to manage files/folders in runtime. -
How to add a searchable text field to select a foreign key item in Django form?
I have a filter form as you can see in the screenshot. I would like to add a searchable field(in the red area) so users can filter the campaign naming tool object instead of scrolling. Any help is appreciated. My filter class class UserInsertionOrderFilter(django_filters.FilterSet): start_date = django_filters.DateFilter(widget=DateInput) end_date = django_filters.DateFilter(widget=DateInput) class Meta: model = UserInsertionOrder fields = [ 'campaign_naming_tool', 'start_date', 'end_date' ] My filter form -
Django request for CAC (common access card)
I am currently running my Django application on an Apache v2.4.5.2 server. When the user hits initial page (i.e. www.djangoApp.com) they are prompted to insert their CAC and PIN. Once complete, the PIN entry pop-up goes away and the user is directed to the landing page. The issue I'm having is figuring out how to identify the user based on the HTTP response received from the external source (GCDS). In the server logs, I can see the request information, but I am unsure how to view that request in Django views. I tried to comment out all middleware so that the request would make it through, but that doesn't work. Does Apache block certain HTTP Requests? Is there somewhere I need to allow external requests? The only request I'm getting is: {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'PATH_INFO': '/', 'PATH_TRANSLATED': '\DjangoWebProject1\\wsgi.py\\', 'HTTP_HOST': 'glen', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"Windows"', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_SEC_FETCH_SITE': 'none', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_COOKIE': 'csrftoken=Nd3ggEPk0vqYJwZKOVZZoZtUqZWXs155Y6V1q', 'HTTP_X_FORWARDED_FOR': '128.202.106.24', 'HTTP_X_FORWARDED_HOST': 'glen', 'HTTP_X_FORWARDED_SERVER': … -
Django kubernetes error error converting YAML to JSON: yaml: line 11: mapping values are not allowed in this context
im using Django and kubernetes to create a website and when i run helm upgrade --install --dry-run --debug django-test ./helm/django-website there seems to be a problem with deploypment.yaml but i cant seem to find the issue ive tried multiple methods from forms and used yaml checkers but i cannot fix it i dont know why it has a problem to begin with because the program generated it all i added was command: ["make", "start-server"] on line 36 here is the code for deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "django-website.fullname" . }} labels: {{ include "django-website.labels" . | nindent 4 }} spec: {{ if not .Values.autoscaling.enabled }} replicas: {{ .Values.replicaCount }} {{- end }} selector: matchLabels: {{- include "django-website.selectorLabels" . | nindent 6 }} template: metadata: {{- with .Values.podAnnotations }} annotations: {{- toYaml . | nindent 8 }} {{- end }} labels: {{- include "django-website.selectorLabels" . | nindent 8 }} spec: {{- with .Values.imagePullSecrets }} imagePullSecrets: {{- toYaml . | nindent 8 }} {{- end }} serviceAccountName: {{ include "django-website.serviceAccountName" . }} securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }} containers: - name: {{ .Chart.Name }} securityContext: {{- toYaml .Values.securityContext | nindent 12 }} image: "{{ .Values.image.repository }}:{{ … -
How to call function from views.py to models.py?
Problem I'm new in Django, I have a function to retrieve foreign key object in views.py and I want to call this function to models.py, is there any way to do this? views.py def get_fk(request): if request.method == 'POST': category = itemCategory.objects.get(pk=request.POST.get('idItemCat')) return category models.py class MyUser(AbstractUser): pass class ItemCategory(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) class ItemCode(models.Model): idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING) What I've tried To import a function usually in django like this from .views import get_fk, but every time I did that it doesn't work and getting this error, it said that my custom user has not been installed. Traceback (most recent call last): File "D:\VS_Code\.venv\lib\site-packages\django\contrib\auth\__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "D:\VS_Code\.venv\lib\site-packages\django\apps\registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "D:\VS_Code\.venv\lib\site-packages\django\apps\config.py", line 270, in get_model raise LookupError( LookupError: App 'aset_app' doesn't have a 'MyUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\VS_Code\.venv\lib\site-packages\django\core\management\__init__.py", … -
Django - (admin.E015) The value of 'exclude' contains duplicate field(s)
I have the following Models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') These are registered to django-admin as follows: @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): list_display = ['identifier', 'name'] @admin.register(Step) class StepAdmin(admin.ModelAdmin): list_display = ['start_time', 'time', 'schedule'] exclude = list('schedule') However when running the server I get the following error: ERRORS: <class 'manager.admin.StepAdmin'>: (admin.E015) The value of 'exclude' contains duplicate field(s). How can I resolve this issue? I am unfamiliar with how Two way binding in Django is supposed to work? -
How to map out With python Django Management CMD [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. -
Getting Realtime data and parsing it locally in Django Rest Framework
I want to build a Django REST API that gets crypto pricing data from Coin Market Cap and shows it on GET localhost according to my own parameters. There are a few questions, however, Coin market cap uses API auth keys, where does it go? Where do I put it? In What headers? Do I really need models if I am getting a predefined URL that already displays what I want? -
getting "This field is required" message. while uploading image
i don't have any problem in submiting char fields but when i put an image field i get this message -> "This field is required" while im filling the form . models.py : class Home(models.Model): image = models.ImageField(upload_to='image') titr = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) class Meta: ordering = ['created'] def __str__(self): return str(self.titr) views.py : def craethome(request): form = HomeForm() if request.method == "POST": form = HomeForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect("home") return render(request, 'home/home_form.html', {"form":form}) forms.py : from django.forms import ModelForm from .models import Home class HomeForm(ModelForm): class Meta(): model = Home fields = "__all__" my html file: {% extends 'main.html' %} {% block content %} <img src="{{home.image.url}}"> <h1>{{home.titr}}</h1> <p>{{home.description}}</p> {% endblock content %} -
Why does HTML/Django template execute code out of order?
This html template from my online class executes as intended, but why? It seems like it is executing out of order: It calls my python form class using Django's syntax {{form}} to inject the blank fields for the user to fill out (name, email, textbox) The user can enter and hit the "Submit" button but then (confusingly) is that it seems the {{form}} class is called again with the entry information as it then successfully prints out user input to the terminal. Why is this? html in templates.py <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <h1>fill out the form</h1> <div class="container"> <form method="POST"> {{form}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="submitme"> </form> </div> </body> </html> Form class in views.py def form_name_view(request): form = forms.FormName() if request.method == "POST": form = forms.FormName(request.POST) if form.is_valid(): print("VALIDATION SUCCESS") print("NAME: " + form.cleaned_data['name']) print("EMAIL: " + form.cleaned_data['email']) print("TEXT: " + form.cleaned_data['text']) return render(request, 'first_app/form_page.html', {'form' : form}) Supplemental: the url that uses the html template and my forms class from django.urls import path from first_app import views urlpatterns = [path('formpg', views.form_name_view, name = 'formpg')]