Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the correct way to implement Django password history?
I have implemented a solution for checking a new password against the last 5 passwords like so: Created 5 fields in a user profile table to store the encrypted passwords On creating a new user, I stored the initial password in encrypted form in all the 5 fields On reset, I changed the views.py from Lib>django>contrib>auth directory from my virtual environment like so: def form_valid(self, form): #all initial code to get the keys etc goes here newpwd = form.cleaned_data['new_password2'] #get the unencrypted passwords from history p1 = cipher.decrypt(b64decode(user.pwd1)) p2 = cipher.decrypt(b64decode(user.pwd2)) p3 = cipher.decrypt(b64decode(user.pwd3)) p4 = cipher.decrypt(b64decode(user.pwd4)) p5 = cipher.decrypt(b64decode(user.pwd5)) #check if the password is already used and redirect with error message if newpwd == p1 or newpwd == p2 or newpwd == p3 or newpwd == p4 or newpwd == p5: messages.error(self.request, _('New Password should be different from old password')) return redirect('password_change') else: #store the password in the password history user.pwd5=user.pwd4 user.pwd4=user.pwd3 user.pwd3=user.pwd2 user.pwd2=user.pwd1 user.pwd1=newpwd user.save() form.save() messages.error(self.request,'Password Changed Successfully') return redirect('/user/login') form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) This works fine. But it feels incorrect editing the existing contrib>auth files like this. Is … -
How do I properly type annotate ForeignKey for Django Mixins?
I would like to use this solution to annotate mixins for models. So I need ForeignKey: from django.db import models class MultiplicatorMixin(models.Model): foo: models.ForeignKey def multiply(self, m: int) -> int: return self.foo.value * m Please note that foo: models.ForeignKey works. However, I want the type of the foreign key as well. So I need something like foo: models.ForeignKey[Foo]. Is it possible to also give the information to which type the foreign key belongs? -
django.db.utils.OperationalError: could not connect to server: Connection
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Unfortunately, I got this error: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Unhandled exception in thread started by <function wrapper at 0x7f80449f4850> web_1 | Traceback (most recent call last): … -
Migrating Django app to use online media storage
I have a Django app running on a server. Currently user uploads are stored on the server filesystem. I already know how to set up S3 storage. What is the best way to migrate existing uploads to S3 without breaking the API and having existing uploads still available? These files are served to the front end in two ways: Directly through a /media/path/to/upload endpoint: /media/<path> django.views.static.serve Through a viewset: /api/v1/users/<user_pk>/items/<item_pk>/attachments/<pk>/ project.app.views.ItemAttachmentsViewSet Does the following make sense: Change the storage backend Go through all model objects Save each model object to get the files uploaded Have /media/path go to a new view that will serve the files similar to how ItemAttachmentsViewSet does it. ? Or is there a better way? -
Want to create unique and autofill the value of the model whenever user fill the form
here is my model.py class Product(models.Model): user = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE) coinid = models.CharField(max_length=255, unique = True, null=True) digit = models.CharField(max_length=18, unique = True, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) when the user fills the form which includes = coinid and ctp. I want Django to automatically fill Digit(unique) and user(logged in) fields for me when updated to the products table. here is my form.py class CreateProduct(ModelForm): class Meta: model = Product fields = ['user','coinid', 'ctp'] exclude = ['user'] views.py def createProduct(request): user_id = request.user.customer form = CreateProduct(instance=user_id) if request.method == 'POST': form = CreateProduct(request.POST) if form.is_valid(): form.save() return redirect('/products/') context = {'form': form} return render(request, 'accounts/newcoin.html', context) Also, I want to validate the product's ctp value whenever a user types in the unique digit to another form. -
django async support - not fully understanding the main concept
which is main concept of django asgi? when there are multiple tasks to be done inside a view, handle those multiple tasks concurrently thus reduce view's response time. when there are multiple requests from multiple users at same time, hendle those requests concurrently thus users wait less in queue. Channels? Web Socket? I'm trying to understand and use the asgi concept but feeling so lost. Thanks. -
Got error when tried to restore postgresql data from docker in windows
i'm using windows and got this error when tried to restore PostgreSQL data from docker. The problem seem like because docker can't find that file but there is file exist in postgresql_backups folder. I tried searching but no result, can anyone help? (by the way, macos seem run fine without problem) -
how to handling IST timeZOne to UTC timeZone i Django?
How do i convert IST timeZone to UTC timeZone , as i have made an api and an application is making a post request and there is a transaction_time which is in IST format but i need to store transaction_time in database in UTC timeZone format. models.py class Payments(models.Model): datetime = models.DateTimeField(auto_now=False,auto_now_add=False) views.py @api_view(['POST']) def cashfree_request(request): if request.method == 'POST': data=request.POST.dict() datetime = data['txTime'] print(datetime) #datetime sent by the application in '2021-05-17 14:26:33' #it should be changed in UTC timeZone and then save into database -
Why do my entries don't get saved in the Database in Django?
The post requests from the frontend do not get saved in the database, without any error shown. However, when I manually add entries from the admin panel, it shows on the frontend. My index.html(form part): <form class="main__input--form" method="POST"> {% csrf_token %} <p class="main__input--text"> <textarea name="content" id="content" class="main__input--content" cols="35" rows="8" aria-label="Entry content" placeholder="Enter text here..."></textarea> </p> <button class="main__input--submit" type="submit">Vent</button> </form> My extension of index which loops through the database entries: {% for obj in all_vents %} <div> <h1>{{obj.vent}}</h1> </div> <br /> {% endfor %} My models.py: class Vents(models.Model): vent = models.CharField(max_length=10000) def __str__(self): return self.vent My forms.py: from django import forms from .models import Vents class VentForm(forms.ModelForm): class Meta: model = Vents fields = ['vent'] My views.py: from django.shortcuts import render, redirect from .forms import VentForm from .models import Vents def ventout(request): if request.method == "POST": form = VentForm(request.POST or None) if form.is_valid(): form.save() return redirect("ventout") else: all_vents = Vents.objects.all() return render(request, "ventout.html", {"all_vents": all_vents}) -
Django signals: Check if the data inside of ManyToManyField is change/updated
how can I check if the objects inside of ManyToManyField is change or updated while still accessing the main Model where the manytomanyfield is placed. Here is the example of code: class Student: name = models.CharField(max_length=255, null=True, blank=False) age = models.IntegerField(default=0, null=True, blank=False) class Room: students = models.ManyToManyField(Student, related_name="list_of_students") I tried the m2m_changed but it only recieve those signals when there's a Newly added/updated/deleted on students field. I want to get the Room model where the student is selected at students field. s1 = Student.objects.first() s1.name = "John Doe" s1.save() '''prints the data with Room model on it.''' -
Is there a way to iterate through all the fields in a Django database object and display them through a template HTML?
I have this HTML code for my template HTML file: name : {{object.name}} age : {{object.age}} gender : {{object.gender}} name, age, gender etc are stored in a MySQL database. Instead of listing every field, which is a lot, I want to generalize the code like this: {% for field in object %} {{field.field_name}} : {{field.field_value}} {% endfor %} My problem is that I have multiple tables and each table has lots of fields. I cannot generalize the table. How do I generalize my template the way I've shown in the latter code snippet? -
Sending Email via Crontab in Django Not working
This is my first time to use crontab, I have a cron task and set every 1 minute to run the task but nothing happen. My sending email script is 100% working if I run manually via Django view but in crontab task not working. Can you please help me if whats wrong with my task? No error found via terminal and application. Im using: django-cronjobs==0.2.3, django-crontab==0.7.1 cron.py This Django sending email script is 100% working via Django views. class request_cron_email(): sent_status = table.objects.all(), cstatus = table.objects.filter(Deadline__date = datetime.datetime.today(), sent_email="No") plate = "" for carreg in cstatus: plate = carreg.plate_no print(plate) if plate != "": for item in cstatus: subject = 'FMS Automated Email' html_message = render_to_string('vr/pms_email.html',{'content':item.plate_no}) plain_message = item.plate_no recipient_list = [item.email] from_email = 'FMS <test@gmail.com>' mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False) car_status.update(sent_email="Yes") setting.py CRONJOBS = [ ('*/1 * * * *', 'request.cron.request_cron_email') ] INSTALLED_APPS = [ 'django_crontab' ] -
Kubectl. No environment variables are found in the service
I built an API with django, celery and redis. I deployed the API in minikube an add some secrets to the cluster with: kubectl create secret generic my-secret-storage \ --from-literal=AZURE-STORAGE-ACCOUNT-NAME='account_name' \ --from-literal=AZURE-STORAGE-ACCOUNT-KEY='account_key' \ --from-literal=AZURE-STORAGE-CONTAINER-NAME='container_name' And I build the deployd and the service in this way: apiVersion: apps/v1 kind: Deployment metadata: name: api-consulta-acciones labels: app: api-consulta-acciones spec: replicas: 1 selector: matchLabels: app: api-consulta-acciones template: metadata: labels: app: api-consulta-acciones spec: containers: - name: api-consulta image: my_image args: - sh - -c - |- python3 ./manage.py runserver 0.0.0.0:8000 ports: - containerPort: 8000 env: - name: AZURE-STORAGE-ACCOUNT-NAME valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-ACCOUNT-NAME - name: AZURE-STORAGE-ACCOUNT-KEY valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-ACCOUNT-KEY - name: AZURE-STORAGE-CONTAINER-NAME valueFrom: secretKeyRef: name: my-secret-storage key: AZURE-STORAGE-CONTAINER-NAME - name: celery # Celery deployd - name: celery-beat # Celery-beat deployd --- apiVersion: v1 kind: Service metadata: name: api-consulta-svc labels: app: api-consulta-svc spec: type: LoadBalancer ports: - name: "8000" port: 8000 targetPort: 8000 selector: app: api-consulta-acciones If I get into the container api-consulta-acciones -c api-consulta, I can confirm that the secret variables were created: # Inside the pod >>> import os >>> os.environ environ({'AZURE-STORAGE-ACCOUNT-NAME': 'account_name', 'AZURE-STORAGE-CONTAINER-NAME': 'container_name', 'AZURE-STORAGE-ACCOUNT-KEY': 'account_key', ..... }) However, the problem is when I use the API in the … -
For login, request provides user details in Django
I am trying to create a Django todo app by using the Django rest framework where I ran into this problem. I am authenticating the user via the rest framework so that I am able to get an authentication token, for the user. My views.py... def login(request): print("\n\n", request, "\n\n") if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(user) response = requests.post("http://127.0.0.1:8000/api/login/", data={"username":username, "password":password}) token = json.loads(response.text).get("token") request.session["token"] = f"Token {token}" request.session.modified = True # r = requests.get("http://127.0.0.1:8000/api/", headers={"Authorization":request.session["token"]}) return redirect("home") else: return render(request, "todo/login.html", {"message":"Your entered credentials are wrong"}) else: return render(request, "todo/login.html") In which I have figured that when my user input is invalid, the request parameter carries the value <WSGIRequest: POST '/login'>. But when the user input is valid the request parameter carries my user details (the value najaaz - my username). This output was figured out using the print statement in line 2. Since it carries my user details I get the following error 'User' object has no attribute 'method', since the line if request.method == "POST": would be invalid then. This is something new for me, and I am a bit unsure of how … -
TemplateDoesNotExist: personal/home.html
I am trying to access home.html, the relative path looks like this hub/templates/hub/home.html. However, I want to access all the template folders, I am trying to accomplish that through the code provided in settings.py. It looks different than other people's post ( there is no 'os' option) Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # My apps 'hub', # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path(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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True … -
chartjs datalabels not showing anything with django template
I tried so many time to ask this question but no one was able to help me so I decided to deleted the previous question and reask with taking into considerations the answers that I received. I have this chart created with chartjs, as you can see you can hover over points to see their coordinated or data, I would like to have an option to show them without having to hover. The reason why I want to do this is because I am going to add export to pdf, and it exports whatever it can see on the HTML , and exporting a chart without its values would be unreadable to the end user. Note (I don't know if this matters but I am using django and I did not do any npm installation of datalabels) Another Note : I was told that I have to register the plugin before using it, with Chart.register(ChartDataLabels); but adding it the chart script just causes the chart to disappear. .cann { border: 3px solid darkgrey; padding: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); transition: all 0.3s cubic-bezier(.25,.8,.25,1); width: 650px; height: 250px; margin-left: 3em; } <!-- Required meta tags --> … -
Django REST Framework - method patch not allowed with UpdateModelMixin
I would like to update a record in my database with the REST framework. I'm getting an message of method not allowed for anything but "GET". views.py class MetadataViewTest(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = deployment.objects.all() serializer_class = SerializerTest def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) urls.py urlpatterns = [ path('api/metadata_test/<int:pk>/', views.MetadataViewTest.as_view()) ] serializers.py class SerializerTest(serializers.ModelSerializer): class Meta: model = deployment fields = [field.name for field in deployment._meta.fields] I've tried the request through postman as a PATCH PUT or POST at api/metadata_test/20/ -
Session expired error every 5 min in saleor admin after set JWT_EXPIRE
What I'm trying to achieve I set JWT_EXPIRE='True' in my server, so that the access token will expire every 5 min, but I'm having a problem in the admin panel, every 5 min it closes my session. Steps to reproduce the problem Setup Saleor 2.11.0 in Ubuntu 20.04 server Set environment variable JWT_EXPIRE='True' Hosting as static website the Dashboard on amazon bucket Try to stay login after 5 min What I expected to happen Shouldn't the user stay logged in with a silent authentication after 5 minutes? Screenshots Current problem Configured environment variables Http request and response from inspector In screenshot I put the response of the last graphql request. Console output This happens after trying to enter one of the administrator tabs, in this case the product tab, after 5 minutes. System information Saleor version: [ ] dev (current master) [ ] 3.0 [x] 2.11 [ ] 2.10 Operating system: [ ] Windows [x] Linux [ ] MacOS [ ] Other Browser: [ ] Safari [x] Chrome -
How to render Django UTC time in local time
I have USE_TZ = True enabled in my settings.py file, so dateTime values are stored as UTC. When I want to display these dates/times on a template, they will be displayed in whatever timezone I have set in setings.py with TIME_ZONE = 'America/Toronto'. But what if my users are in different timezones and I want it to automatically change the time based on the users timezone? I found that using javascript I can do : new Date(djangoDate)).toLocaleString() will format the date and time to my timezone, regardless of what I have in TIME_ZONE = 'America/Toronto' But is there a way to do this in python/Django? Everything I have tried, like {% load tz %} relies on TIME_ZONE = 'America/Toronto'. in settings.py. I have also tried: timezone.activate(pytz.timezone('America/Winnipeg')) in my view, which seems to display the dates as intended, but found that this will actually change the UTC value in the database when using forms to update dateTime data, which is behavior I do not want. I want to store in UTC, and render/display in local time, automatically without the user having to tell the application what timezone they are in. Is this possible? -
Issue while trying to add a new object with depth = 1 in my serializer
I'm working on a small project using Django / Rest Framework. I have two models Contacts and Category, related using a foreign key everything works fine but when I do depth = 1 in my serializer I get an error 'IntegrityError: (1048, "Column 'category_id' cannot be null")' # foreignkey but when I remove depth = 1 from my serializer it works fine with no errors -
No Python at 'C:\Users\rodne\Desktop\Py 382\python.exe'
Im trying to run my django application. Im not sure what I did to cause it not to work but now when I use the command "python manage.py runserver" in the correct directory cmd gives me the error No Python at 'C:\Users\rodne\Desktop\Py 382\python.exe' can anyone help me understand what I did wrong? -
How to copy staging database to Heroku review app
A similar thread to this one already exists (see link), but I do think that my case is a bit different - my main issue is that heroku.yml's release section doesn't play nicely with app.json's postdeploy script. heroku.yml: ... release: command: - python manage.py migrate image: web app.json: { ... "environments": { "review": { "addons": [ "heroku-postgresql:hobby-dev", ], "scripts": { "postdeploy": "pg_dump $STAGING_DATABASE_URL | psql $DATABASE_URL && python manage.py migrate" } } } } During a deploy, the release from heroku.yml gets executed before the postdeploy script, which introduces a bunch on conflicts when psql is called because the tables already exist. Does anybody know how to handle this? release shouldn't be ignored as it's run on every new release, whereas postdeploy is run only once. But at the time that postdeploy is being run, the database should be empty for psql to succeed without errors. -
Haar Cascades Eye Detection Does Not Work On Python Django Webpage?
I try to display live stream webcam on webpage using Django with OpenCV eye detection. from imutils.video import VideoStream import imutils import cv2,os,urllib.request import numpy as np from django.conf import settings eyes_detection = cv2.CascadeClassifier('haar/haarcascade_eye.xml') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) eyes_detected = eyes_detection.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in eyes_detected: cv2.rectangle(image, pt1=(x, y), pt2=(x + w, y + h), color=(0,255,0), thickness=2) frame_flip = cv2.flip(image,1) ret, jpeg = cv2.imencode('.jpg', frame_flip) return jpeg.tobytes() The video stream will not be displayed with the code above, however, the video can be displayed if I remove line 20-23(gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY). How can I display the video stream with eye detection on the webpage? Below is my views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.http.response import StreamingHttpResponse from main.tryhaar import VideoCamera import cv2 def gen(tryhaar): while True: frame = tryhaar.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') -
ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory: while using cross-platform scripts
I am using import os to create an absolute path, as suggested here, because relative paths are not allowed, see here. But it's still being logged as an error. Here I import the os and use a base_dir: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) then I create directories: LOGGING_ROOT = os.path.join(CROWDFUNDING_ROOT, 'logs') ERROR_LOGS = os.path.join(LOGGING_ROOT, 'errors') INFOS_LOGS = os.path.join(LOGGING_ROOT, 'infos') DEBUG_LOGS = os.path.join(LOGGING_ROOT, 'debugs') per logger type. But I am still getting this error on EC2 on ubuntu. Now I can't do a makemigrations because of this. I don't know what to do, I even used sudo su before I went into the env. -
why can't upload photos in django?
When I try to upload a picture from my form, everything processes, but the image is not being saved. I checked everything on the internet but did not find any solution. In the Html file I am writing Does anyone know why this is happening? Thanks ahead of time! forms.py: class NewPostForm(forms.ModelForm): picture = forms.ImageField(required=True) caption = forms.CharField(widget=forms.Textarea(attrs={'class': 'input is-medium'}), required=True) tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input is-medium'}), required=True) class Meta: model = Post fields = ('picture', 'caption', 'tags') class Post(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable=False) picture = models.ImageField(upload_to = user_directory_path, null=True) caption = models.TextField(max_length=1500, verbose_name='caption') posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='tags') user = models.ForeignKey(User, on_delete=models.CASCADE) #likes = models.IntegerField() def get_absolute_url(self): return reverse('postdetails', args=[str(self.id)]) views.py: @login_required def NewPost(request): user = request.user.id tags_objs = [] if request.method == 'POST': form = NewPostForm(request.POST, request.FILES) if form.is_valid(): picture = form.cleaned_data.get('picture') #picture = form.cleaned_data.get('picture') caption = form.cleaned_data.get('caption') tags_form = form.cleaned_data.get('tags') tags_list = list(tags_form.split(',')) for tag in tags_list: t, created = Tag.objects.get_or_create(title=tag) tags_objs.append(t) p, created = Post.objects.get_or_create(caption=caption, user_id=user) p.tags.set(tags_objs) p.save() return redirect('home') else: form = NewPostForm() context = { 'form':form, } return render(request, 'newpost.html', context)