Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Encrypt Django auth User model's fields
I am trying to encrypt my username and email field in Djago's Default Auth model using a Proxy Model method but so far with no luck. Here is what I have attempted so far: class UserManager(models.Manager): def from_db_value(self, value, expression, connection): if value is None or value == '': return value # decrypt db value and return return decrypt(value) def get_prep_value(self, value): # prepare value to be saved to the database. return encrypt(str(value)) class CustomUser(User): objects = UserManager() class Meta: proxy = True def print_value(self, value): print('test', value) def save(self, *args, **kwargs): self.user = self.print_value(self.user) super().save(*args, **kwargs) I am trying to overwrite the User model with Proxy model and a custom Model manager. Any tips whether how can I achieve this would be really appreciated. -
How i can create a muti value filed without manytomany field in django?
I have a model: class People(models.Model): family = models.CharField(null=True) phone_numbers = ? How i can implement phone_numbers for some phone numbers. I think ManyToManyField is not a good idea for doing this. What is best practice for this? -
How can i do my url flexible in Django 1.11?
In my project with django I should do a site with flexible url. For instance: 'mysite.com/register/kj-1k-32-mk' When someone write some other things after register/ I want to redirect them to my site. How can I redirect them. What should my urls.py looks like? urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'), ] When I do like above, the part after register/ can't begin with a letter. -
Django exists query not work in if and else clause?
In given below if Medicine table consists medicine_name then query execute fine, but when medicine name doesn't exist then error is occured. Matching Query Doesn't Exists if Medicine.objects.filter(medicine_name=m.medicine_name).exists(): return Response({"message": "Successfully Recorded"}) else: return Response({"message": "Not Recorded"}) -
Deploying React front end with Django session based auth doesnt work over HTTPS
So I have a working LOCAL Twitter clone called Hater but cant deploy front end b/c I cant access secured Cookies(https://github.com/mustafabin/hater) I used Django's built-in Session-based auth I have middleware all set up LOGIN VIEW @method_decorator(csrf_protect, name="dispatch") class LoginView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): data = self.request.data username = data['username'] password = data['password'] try: user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return Response({'success': 'User authenticated'}) else: return Response({'error': 'Error Authenticating'}) except: return Response({'error': 'Something went wrong when logging in'}) SIGN UP @method_decorator(csrf_protect, name="dispatch") class SignupView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): data = self.request.data username = data['username'] password = data['password'] re_password = data['re_password'] tag = data['tag'] try: if password == re_password: if User.objects.filter(username=username).exists(): return Response({"error": "Username already exists"}) else: if len(password) < 6: return Response({"error": "Password must be at least 6 characters"}) else: user = User.objects.create_user( username=username, password=password) user = User.objects.get(id=user.id) user_profile = User_profile.objects.create( user=user, name=username, tag=tag) return Response({'success': "User created successfully"}) else: return Response({'error': "Passwords do not match"}) except: return Response({"error": "Something went wrong signing up"}) I'm aware some of these settings are redundant but ur man got desperate CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE … -
Image Fields In ModelForms in Django
I want to create a modelform that follows the model below but I do not know how to create an foreign key and imagefield in modelforms please help me thanks this is my model -
No module named 'rest_framework'
I am trying to deploy my django project on heroku but I'm facing this error of rest framework even though I've installed and it shows requirements already satisfied . and some other errors which I cannot understand $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_048f019e/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_048f019e/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/core/management/__init__.py", line 395, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/apps/config.py", line 224, in create remote: import_module(entry) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'rest_framework' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: … -
SSL implementation on custom port for django application using nginx
I am trying to host multiple django applications on the same IP. I have an django application on hosted on specific port 8001 with domain name (domain_name.com). Now on accessing https://domain_name.com, application runs pretty well, But on http://domain_name.com , another applciation hosted in port 80 loads. On accessing 'domain_name.com' how can i redirect to port 8001 for both http and https requests ? My nginx conf for domain is as below. server { listen 8001; server_name erostreasures.com www.erostreasures.com; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/agmarket.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/erostreasures.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/erostreasures.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } -
Private chat using django
Guys I want to create a private chat feature for my webapp. I referred numerous blog, everyone of them is pointing to creating a room and having group chat. Can anyone help me any blog,video or way to build a individual chat feature using django? -
Matching Query Doesn't Exists in Django?
I will Perform following this POST request in my views.py file if Medicine.objects.filter(medicine_name=m.medicine_name).exists(): if existing > 0: m.save() Medicine.objects.filter(id=p_key).update(no_of_medicine=existing) return Response({"message": "Successfully Recorded"}) else: return Response({"message": "Not much Medicine Stored"}) else: return Response({"message": "Medicine is not Stored"}) The code is working fine if Medicine Exists . if Medicine not exists give me above Exception . Please anyone can help me -
how can i filter my model to get user answer for a current question
I have two models the Answer model and the Question model. when user post the question i want another user to be able to post an answer in the current question similar to stack overflow, i know using this method: MyModel.objects.all() will returns all the answers from all question to a each question, that's is not what i want. How can i do this in Django please ? my model class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) i want to pass user's Answer into this viewQuestion view my view def viewQuestion(request, pk): question = Question.objects.get(id=pk) context = {'question':question} return render(request, 'viewQuestion.html', context) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) -
How can I host Django with celery on cpanel?
I am confused if I can host my django with celery project on cpanel.If yes, How? -
django multiple table query
I have a form for filling out lessons that I want to limit who the students can select as their teacher to only confirmed connections. I have three models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) class Lesson(models.Model): user = models.ForeignKey(User, related_name='fencer', on_delete=models.SET_NULL, null=True, blank=True) teacher = models.ForeignKey(Fencer, related_name='instructor', on_delete=models.SET_NULL, null=True, blank=True) lesson_date = models.DateField(default="1900-01-01") title = models.CharField(max_length=100, null = True, blank=True) description = models.TextField(null=True, blank=True) class Connection(models.Model): student = models.ForeignKey(User, related_name='student', on_delete=models.CASCADE, blank=True) teacher = models.ForeignKey(User, related_name='teacher', on_delete=models.CASCADE, blank=True) student_accepts = models.BooleanField(default=False) teacher_accepts = models.BooleanField(default=False) @property def connected(self): if self.student_accepts == True and self.teacher_accepts == True: return True else: return False My form so far is: class LessonForm(ModelForm): class Meta: model = models.Lesson #fields = () fields = '__all__' def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['teacher'].queryset = Users.objects.filter() # the best I have so far How do I filter the User model based on the link made in the Connection model? Maybe I'm overcomplicating this or is there a better way? Thank you in advance -
Django import export - ManyToManyfield
I have a ManyToMany field in my models. I want to import data and enter into that field. My Resources.py:- class ClinicResource(resources.ModelResource): language = fields.Field(column_name='language',attribute='language', widget=ForeignKeyWidget(Language, 'code')) country = fields.Field(column_name='country',attribute='country', widget=ClinicCountryForeignKeyWidget(model = Country, field ='name')) clinic_languages = fields.Field(widget=ManyToManyWidget(ClinicLanguages, field='name')) class Meta: model = Clinic fields = ('code', 'name', 'city', 'score') exclude = ('id',) import_id_fields = ('code', 'name', 'city', 'score', 'language', 'country') my Models.py:- class Clinic(models.Model): code = models.CharField(max_length= 10, blank= False, null= False) name = models.CharField(max_length= 256, blank= False, null= False) slug = models.SlugField(null= True, blank= True) # country = models.CharField(max_length= 256, blank= False, null= False) city = models.CharField(max_length= 256, blank= False, null= False) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allcliniccountry', blank= True, null=True) score = models.FloatField(blank= False, null= False, default= 2, validators=[MinValueValidator(min), MaxValueValidator(max)]) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='allclinicslanguage', blank= True) # about = models.TextField(blank= True, null= True) clinic_languages = models.ManyToManyField(ClinicLanguages, related_name='clinic_language', blank= True) about = tinymce_models.HTMLField(blank= True, null= True) created= models.DateTimeField(auto_now=True) status = models.CharField(max_length= 30, choices= SIZE_CHOICES, default= 'pending', blank= False, null= False) NOTE THE clinic_languages field, this is what I want to import -
Install grpcio via pip: "legacy-install-failure"
I want to install grpcio with pip(version 1.35). But I get this error: note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> grpcio I tried to install python-dev or wheel, but it did not work. My python version = 3.10 Ubuntu = 22.04 -
Django does not create foreign key in sqlite table
I use sqlite in a Django project. I created a model called Employee, and then Education, but I forgot to add a foreign key to Employee. When I found the problem, I added the foreign key: class Education(models.Model): employee=models.ForeignKey(Employee, on_delete=models.CASCADE), But when run manage.py makemigrations, it says nothing changed. So I tried to delete the sqlite database file, delete all migrations and tried to create a new database. It still say nothing changed! the sqlite database file is created, with 0 size! What is happening to django? -
Django-How can I upload image to a Model, without that field being present in the ModelForm
I am trying to build an image steganography application and for the encoding part I have a form with two fields, one for image and one for the message that is to be encoded. The encoding part takes place in a views.py, but I do not seem to manage how to upload the encoded image in the ImageModel in order to use it later for the decoding part. 1. If I include image_e in the form as a hidden field, I get an error that it needs to be submitted 2. If somehow the form is being submitted, the model contains only the two fields present in the form, 'image' and 'message', and for 'image_e' i get None or the default if i have that option 3. Right now, if I fill the form I get the defaults for all the fields I actually only need 'image_e' stored, but I thought that if I inherit all of the fields from the model it would be easier. I am a beginner in Django and this is my first more complex application. models.py class Image(models.Model): image = models.ImageField(upload_to='images', default='default.png') message = models.CharField(max_length=200, default=1) image_e= models.ImageField(upload_to='encoded', blank=True) forms.py class EncodeForm(forms.ModelForm): #method= forms.CharField(label='How would … -
Django models - how to assign as ForeignKey
My lab has a models.py as below: class Book(models.Model): isbn = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=100) published_year = models.IntegerField() total_qty = models.IntegerField() current_qty = models.IntegerField() max_duration = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.PROTECT) def __str__(self): return self.name class BookCopy(models.Model): class Status: AVAILABLE = 1 BORROW =2 LOST = 3 barcode = models.CharField(max_length=30, unique=True) buy_date = models.DateField(null=True, blank=True) status = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.PROTECT) def __str__(self): return self.barcode class User(models.Model): username = models.CharField(max_length=30, unique=True) fullname = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=10, null=True) def __str__(self): return self.fullname class BookBorrow(models.Model): class Status: BORROWING = 1 RETURNED = 2 borrow_date = models.DateField() deadline = models.DateField() return_date = models.DateField(null=True) status = models.IntegerField() book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT) book_name = models.ForeignKey(Book, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) And i wrote the api for borrow_book function like below: @csrf_exempt def muon_sach(request): body = request.POST username = body.get('username') barcode = body.get('barcode') user = User.objects.filter(username=username).first() bookcopy = BookCopy.objects.filter(barcode = barcode).first() if not user: return HttpResponse(json.dumps({ 'error':"Nguoi dung khong ton tai" })) if not bookcopy: return HttpResponse(json.dumps({ 'error':"ma sach khong ton tai" })) book_borrow = BookBorrow() # resp = [] book_borrow.user = user book_borrow.book_copy = bookcopy book_borrow.borrow_date = datetime.now() book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration) book_borrow.status = BookBorrow.Status.BORROWING book_borrow.book_name … -
How to display a list of search results in Django 4
I'm writing a Django app to manage sales leads. From the template that lists a page of leads, I want to give the user the ability to search all leads using first name and last name as the search criteria. When I type in a last name and press enter, the page flickers but remains on the same page rather than the template I created to list the search results. My views, urls, and templates are below. What have I missed? views.py class LeadsListView(ListView): model = Lead template_name = 'leads/list.html' context_object_name = 'leads_list' paginate_by = 10 def get_queryset(self): return Lead.objects.order_by('id') class LeadsSearchResultsView(ListView): model = Lead context_object_name = 'search_results' template_name = 'leads/search_results.html' paginate_by = 10 def get_queryset(self): query = self.request.GET.get('q') return Lead.objects.filter( Q(last__icontains=query) | Q(first__icontains=query) ) urls.py from django.urls import path from .views import LeadsListView, LeadsDetailView, LeadsCreateView from .views import LeadsSearchResultsView app_name = 'lead' urlpatterns = [ path('', LeadsListView.as_view(), name='list'), path('<int:pk>/', LeadsDetailView.as_view(), name='detail'), path('', LeadsCreateView.as_view(), name='create'), path('', LeadsSearchResultsView.as_view(), name='search_results'), ] The template that (successfully!) lists the leads, list.html: {% extends 'base.html' %} {% block content %} <nav aria-label="Page navigation example"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% … -
How can I print the url to the order id field of my django form?
I am doing a simple form site with Django. This is what my sites url is looks like: mysite.com/register/12345678 I want to print the part after the register (12345678) to the order id field. When someone goes this mysite.com/register/87654321 url then i want to print it. How can i do that? These are my codes.(Currently using Django 1.11.10) forms.py from django import forms from .models import Customer from . import views class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') widgets = { 'order_id': forms.TextInput(attrs={'class':'orderidcls'}), 'full_name': forms.TextInput(attrs={'class':'fullnamecls'}), 'company': forms.TextInput(attrs={'class':'companycls'}), 'email': forms.TextInput(attrs={'class':'emailcls'}), 'phone_number': forms.TextInput(attrs={'class':'pncls'}), 'note': forms.Textarea(attrs={'class':'notecls'}), } views.py from django.shortcuts import render from olvapp.models import Customer from olvapp.forms import CustomerForm from django.views.generic import CreateView,TemplateView def guaform(request,pk): form = CustomerForm() if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) else: print('ERROR FORM INVALID') theurl = request.get_full_path() orderid = theurl[10:] return render(request,'forms.py',{'form':form,'orderid':orderid}) customer_form.html {% extends 'base.html' %} {% block content %} <h1>REGİSTRATİON</h1> <form class="registclass" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-default">REGISTER</button> </form> {% endblock %} urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^thanks/$',views.ThankView.as_view(),name='thank'), url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'), ] -
in Django : Why nothing happens when I try to connect with YouTube API and search the top 10 videos about whatever subject
I've just started my first app with Django by following a video on YouTube. The app is a students dashboard with 8 tools and features to help the student to make note, search for help, save books, etc. When I follow the steps I get stuck in the YouTube search section but not from the admin side but from the actual YouTube template that has a crispy form and a search button. The program is supposed for searching the top 10 videos about anything as a result and show in the same template I created (youtube.html) and some information like title, description, duration, etc. when I try to click the search button nothing happens. #This is the view.py page in the dashboard app : from typing import Generic from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.shortcuts import render from . forms import * from django.contrib import messages from django.urls import reverse from django.views import generic from django.views.generic.detail import DetailView from youtubesearchpython import VideosSearch # the youtube function def youtube(request): if request.method == "POST": form = DashboardForm(request.POST) text = request.POST['text'] video = VideosSearch(text,limit=10) result_list = [] for i in video.result()['result']: result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['channel']['name'], … -
Python Django error "Select a valid choice. That choice is not one of the available choices."
I am relatively new to Django so I am likely doing something obviously wrong but I cant seem to figure out what exactly. I have a model called Report and this has a number of fields including a foreign key relationship to my Plot model. In my Report model form I have extra fields that are not part of the model but are used to filter/search for the correct plot. I am using javascript to fetch these values on change of the respective field. First the user selects a developer from a list (this is configured as a ModelChoice field and is populated on initialisation using a query set), this then populates a list of developments owned by the developer, they then select the desired development, this yields all plots that are part of that development, finally they select the desired plot. When the form is submitted I receive "Select a valid choice. 37d86254-29c5-456d-8264-f47e893ae789 is not one of the available choices." for both the development and plot_id fields. My aim is to use the plot_id value (plot pkid) to obtain an instance of the respective plot in the view and store this in the report.plot foreign key relationship as per … -
Django 4: Product.objects.get(id=1) returns an error "DoesNotExist" but I already have 7 products listed
I already have 7 products listed in my DB and I can check them by Product.objects.all() but when I do Product.objects.get(id=1) or pass any id as a parameter it returns me this error: meanwhile, this is what I am doing: [views.py file] here If I use Product.objects.all() it returns me all my 7 products listed in DB but if I use Product.objects.get(id=id) it retuns me the error def update_product(request, id): product=Product.objects.get(id=id) #As far I understood, here the actual problem starts. context = { "product": product } return render(request, "myapp/updateProduct.html", context) [urls.py file] from django.contrib import admin from django.urls import path from . import views app_name = "myapp" urlpatterns = [path('', views.index), path('products/', views.products), path('products/<int:id>', views.product_details, name='product_details'), path('products/add', views.add), path('products/update/<int:id>', views.update_product, name='update_product'), ] [updateProduct.html file] {% extends 'myapp/base.html' %} {% block content %} <main class="box-container"> <div class="title"> <h1>Update Your Product</h1> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Name" required> <input type="number" name="price" id="price" placeholder="Price" required> <!-- <input type="text" name="description" id="description" placeholder="Description"> --> <textarea spellcheck="true" name="description" id="description" placeholder="Description" cols="30" rows="10" required></textarea> <input type="file" accept="image/*" name="upload" id="upload" required> <input type="submit" name="Add Product" value="Add Product"> </form> {% endblock %} -
get_object_or_404 and .get(id=pk) is not working when i try to access my model in to some view
i'm trying to access my model using both method but one of them is not working in my view. i want when a user click on {{question.title}} in my home page to be able to see all the content of the post in vewQuestion template. but both method is not working in app. is anybody who can help me please. my urls path('view/<int:pk>/', views.viewQuestion, name='viewQuestion'), the both method my_list = get_object_or_404(Question, id=pk) list_of_question = Question.objects.get(id=pk) the url <a href="{% url 'viewQuestion' question.id %}" style="text-decoration: none;"> the home template <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title">{{question.user}}</p> </div> <div class="card-body"> <a href="{% url 'viewQuestion' question.id %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <p>Category: {{question.category}}</p> </div> </div> </div> {%endfor%} </div> </div> the viewQuestion template <div class="container"> <div class="row justify-content-center"> <h1>{{question.title}}</h1> <hr> </div> <br> <h3 style="font-family: arial;">{{question.body}}</h3> <hr> <br> <h5>{{question.user}}</h5> </div> the views @login_required(login_url='login') def index(request): query = request.GET.get('q', None) list_of_question = Question.objects.all() if query is not None: list_of_question = Question.objects.filter( Q(title__icontains=query) | Q(category__icontains=query) ) context = {'list_of_question':list_of_question} return render(request, 'index.html', context) def viewQuestion(request, pk): my_list = get_object_or_404(Question, id=pk) list_of_question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=list_of_question) context = {'list_of_question':list_of_question, 'answers':answers, 'my_list':my_list} return … -
How to assign a database model to a user
from django.db import models from datetime import datetime from django.contrib.auth.models import User class News(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) headline = models.CharField(max_length=100) content = models.CharField(max_length=1000000) time_created = models.DateTimeField(default=datetime.now, blank=True) i kept on trying this method but i keep getting an error" django.db.utils.OperationalError: no such column: blog_news.user_id "