Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
queryset average values of column
I´m trying to make an queryset with Django but I have no clue how to do that. The query that I want to do is: select format(avg(progress),1) as progreso from c_lp_view where user_id = 21 and c_id = 1; Now in Django my queryset looks like this: CLpView.objects.filter(user_id = user_id).filter(c_id__in=lRels).aggregate(avg_progress=Avg('progress')) Thanks for the help -
I am a beginner and I was trying to start local django server [closed]
D:\Talha\lecture3>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python\Python39\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hello.urls' from 'D:\Talha\lecture3\hello\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Upload images to django from axios
I am trying to send images from axios client to server with django. At completeInfo function at views.py when I set a print(request.FILES) <MultiValueDict: {'imagen': [<InMemoryUploadedFile: blob (text/html)>]}> So what instinct is that the image is empty. Also the media folder on the django server is never created. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'media') STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'static-only') STATICFILES_DIRS = ( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'static'), ) urls.py urlpatterns = [ path('completarinfo/',completeInfo) ] Models.py class clientData(models.Model): user=models.ForeignKey(client, on_delete=models.CASCADE, null=True) client_picture=models.ImageField(default=None, upload_to='images/') def __str__(self): return selft.user.user forms.py from django import forms from .models import * class clientDataForm(forms.ModelForm): class Meta: model = clientData fields = ['name', 'client_picture'] views.py @csrf_exempt def completeInfo (request): print(request.FILES) if request.method == 'POST': form = clientDataForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('successfully uploaded') else: form = clientDataForm() return HttpResponse("imagen") This is the axios code: const axios = require('axios'); axios({ url:url, method:'POST', headers: { "content-type": "multipart/form-data" }, data:formData }).then(function(res: any){ console.log(res) }).catch((error: any) =>{ console.log(error) //Network error comes in }); Someone could help me? Thanks in advance -
Many fields. Validate them so that errors should be next to problematic fields
Django 3.1.6 class RasterImageForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img_fields = self._get_img_fields() def _get_img_fields(self): result = [field[0] for field in self.fields.items() if "img" in field[0]] return result def _validate_equality_of_file_name_and_field_name(self): for img_field in self.img_fields: val = self.cleaned_data[img_field] full_file_name = os.path.basename(val.name) full_file_name_without_ext = os.path.splitext(full_file_name)[0] if full_file_name_without_ext != img_field: raise ValidationError( '%(filename)s: ' + str(_('File name is incorrect. It must coincide with the field name.')), params={"filename": full_file_name_without_ext}) def clean(self): self._validate_equality_of_file_name_and_field_name() I want to force users to name uploaded files exactly as the field name. This code works. But the error is shown at the top of the form. There are a lot of such fields. Say, 20-30. If if there were a couple of fields, I'd use clean_(). But I can't manage it with so many fields. Could you help me organize form validation so that an error should be not next to problematic fields. -
How to return username instead of ID
Before calling this a repeat question please have a look at my code. I have a Blog Model and here is the Favourites part of it: class Fav(models.Model) : post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: unique_together = ('post', 'user') def __str__(self) : return str(self.user.username) My serializer looks like this: class FavSerializer(serializers.ModelSerializer): class Meta: model = Fav fields = ['post', 'user'] I assumed because of the __str__ part, that this API will return the username but instead it returns only the user_id. How can I return the username? -
Django Display Multiple Values from Dependent Dropdown
I'm using Python 3.8 & Django 3.0 and need multiple values (volume & volume size) to go to a dependent dropdown. I've been able to populate the dependent dropdown with a single value (volume). I found posts that work with a dropdown sending multiple values from django dropdown and retrieve multiple values from Dropdown menu in Django but these don't work with a dependent dropdown. Here is my code: models.py class ArrayVolumes(models.Model): array = models.ForeignKey(Array, on_delete=models.CASCADE) volume = models.CharField(max_length=50, default=None) vol_size = models.CharField(max_length=10, default=None) def __str__(self): return self.volume views.py from .models import ArrayVolumes def load_volumes(request): array_id = request.GET.get('array') vols = ArrayVolumes.objects.filter(array_id=array_id).order_by('volume') # vol_size = ArrayVolumes.objects.filter(array_id=array_id).value('vol_size') return render(request, 'pure/volume_dropdown_list_options.html', {'vols': vols}) urls.py urlpatterns = [ path('ajax/load-volumes/', views.load_volumes, name='ajax_load_volumes'), ] dropdown_list_options.html <option value="">---------</option> {% for vol, size in vols %} <option value="{{ vol.pk }}#{{ size }}">{{ vol.volume }} ( {{ size.vol_size }} )</option> {% endfor %} main.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> {% crispy form form.helper %} <form method="post" id=volForm data-volumes-url="{% url 'ajax_load_volumes' %}" novalidate> <br><br> <h4>{{ note }}</h4> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_array").change(function () { var url = $("#volForm").attr("data-volumes-url"); var arrayId = $(this).val(); $.ajax({ url: url, data: { 'array': arrayId }, … -
Django - how to create multiple select (on CreateView) to a foreign key on the related model?
I have those two models: Student class Student(models.Model): name = models.CharField(max_length=50, default='') class = models.ForeignKey(Class, related_name='students', on_delete=models.SET_NULL, blank=True, null=True) Class class Class(models.Model): code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) When the user creates a new Class, I need them to be able to choose the students that it's going to be in the class. And they should be able to add students later. How would I create this view? -
UniqueValidator in drf
my model has a field: name = models.CharField(max_length=255, blank=True, null=True) in serializer, I am trying to raise a unique validation error name = serializers.CharField(validators=[UniqueValidator(queryset=Department.objects.all(), message=("Name already exists"))]) but it does not work, because the data comes to the serializer in this format name: {en: "drink"} I can raise an error in the create method, but I want to raise the error on the serializer. appreciate any advice. I'm in a hurry. sorry for any inconvenience. Thanks in advance -
JSON parsing using Python Django
I am trying to create dynamic database tables based on user import file. I have done excel import using react and store the json data(below json data) to my db. I have creating a restapi with function, if i received datum from user wants to create dynamic tables and data insertion. I have tried without rest with model json data its working fine. Request your suggestion please. I have received following json data from react. { "tableInfo": { "dbName": "ws1_kalairaman_sv", "tableData": [ [ { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker1": "722410010726613", "currency": 16687, "datetime": "01/01/2021 02:01:00" }, { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker1": "722410010729091", "currency": 16687, "datetime": "01/01/2021 02:01:00" } ], [ { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker2": "722410010726613", "currency": 16687, "datetime": "01/01/2021 02:01:00" }, { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker2": "722410010729091", "currency": 16687, "datetime": "01/01/2021 02:01:00" } ] ], "tableName": [ "Sheet8", "Sheet9" ], "tableColumn": [ [ { "type": "CHAR (60)", "field": "ticker1", "title": "ticker1", "width": "auto", "hidden": False, "tooltip": "ticker1", "cellStyle": { "whiteSpace": "nowrap" } }, { "type": "CHAR (60)", "field": "gerw", "title": "gerw", "width": "auto", "hidden": False, "tooltip": "gerw", "cellStyle": { "whiteSpace": … -
What does JWT being stateless really means?
Hi and thanks in advance, I've successfully setup JWT authentication using django-rest-framework-simplejwt and React but I'm still very confused about the advantages and specifically database hits. I'm using simplejwt with ROTATE_REFRESH_TOKENS': True 'BLACKLIST_AFTER_ROTATION': True, when my access_token expire I ask for a new one through /api/token/refresh and it blacklist old tokens, I'm using axios interceptors to perform that automatically. But in my understanding the benefits of JWt is that they are stateless, meaning I don't have to hit the user database table everytime I want to make an a request that needs authentication permission. The problem is even with a simple view like this : class IsConnecteddAPI(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, *args, **kwargs): data = "You seem to be connected" return Response(data, status=status.HTTP_200_OK) using django-silk I see that it still performs 1 query to my user table when I call it with a valid access token, is that normal ? If so why do we say that JWT are stateless ? I'm really confused. That's my axios code if needed : import axios from "axios"; const baseURL = "http://localhost:5000"; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem("accesstoken") ? "JWT " + localStorage.getItem("accesstoken") : null, … -
no user matches the given query
hi everyone i am building a ecommerce webapp where everything is done except this. i want the user to get the product that it posted by itself my views.py file is: class UserPostListView(ListView): model = Product template_name = 'product/user-posts.html' def get_queryset(self): user = get_object_or_404(User, email=self.kwargs.get('email')) return Product.objects.filter(user=user , is_staff=True).order_by('-date_posted') my urls.py file is: urlpatterns = [ # path('featured/' , ProductFeaturedListView.as_view()), #path('featured/<int:pk>' , ProductFeaturedDetailView.as_view()), path('' , ProductListView.as_view(), name= "list"), path('new/' , ProductCreateView.as_view() , name="product-create"), path('<slug:slug>/update/' , ProductUpdateView.as_view() , name="product-update"), path('<slug:slug>/delete/' , ProductDeleteView.as_view() , name="product-delete"), #path('product-fbv/' , product_list_view), #path('product/<int:pk>' , ProductDetailView.as_view()), path('<slug:slug>/comment' , CommentCreateView.as_view() , name="add-comment"), path('<slug:slug>' , ProductDetailSlugView.as_view() , name="detail"), path('userpost/', UserPostListView.as_view(), name='user-post'), # path('product-fbv/<int:pk>' , product_detail_view), ] and my user model is: class User(AbstractBaseUser): email = models.EmailField(max_length=255 ,unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non super user admin = models.BooleanField(default=False) #superuser time_stamp = models.DateTimeField(auto_now_add=True) and it give me the error that no user matches the given query -
Passing selected arguments with a multi-select to a page in Django
I have a webpage with elements that I select and that serve to make calculations and give results in another page. However, I don't seem to be able to get them when I press the send button... In fact, I send my elements from quiz2.html: <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="elements"> <ul class="items col-xs-6 col-sm-3 col-md-3 col-lg-3"> <li class="item"> <label> <input class="item-check" name="keywords[]" type="checkbox" value= {{ keyword.title }} /> <div class="item-name">{{ keyword.title }}</div> </label> </li> </ul> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> And here is the getmatch() function in views.py: def quiz(request): with open('todo/templates/todo/data/keywords.json') as f: keywords = json.load(f) if request.method == 'POST': form = QuizForm(request.POST) if form.is_valid(): keywords_selected = form.cleaned_data['keywords_selected'] print("keywords_selected: ", keywords_selected) form = QuizForm() return render(request, 'todo/quiz2.html', {'form': form, 'keywords': keywords}) def getmatch(request): if request.method == 'POST': result = request.GET.get('keywords[]') print("result: ", result) However, it returns None en result -
Postgres data_type modification in Django
The web application I'm working on in Django ran into a bug when I attempted modifying the data type of a field(column). I got some advice to drop/delete the table which didn't end up very well. Now I'm stuck. I tried creating a new table manually but its still giving me the same error. I tried changing the name of the previous table from its models.py, but that didn't work either. The website is giving me this error, 'Server Error (500),' as it is in production mode and the debug is set to false. I've tried. 'python manage.py makemigrations,' but it says no changes. Also, 'python manage.py migrate,' but that gives an error. -
Django can't create sqlite database in app directory, only create default one
Here is the DATABASES dictionary in settings.py in a django project root: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'tinysteps': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "project2/tinysteps.sqlite3" } } I want tinysteps database to be initialized in project2 app directory, but only default database is created, also I've checked the NAME and it's ok, don't get why this is happened -
django template access url kwargs
I want to access kwargs with their names in url from "django template tags". for example i have a url as below: path('sample_view/<slug:my_custom_slug>/', views.sample_view.as_view(), name='sample_view') what should I write in my html template to access "my_custom_slug"? -
Python braincube-connector date slicing
I have been successful in obtaining data via the package. I am now attempting to retrieve data based on a desired date range. The methods provided with the braincube_connector pypi project description site do not work properly to my knowledge. The parse_date parameter does not seem to work. Setting the condition to true using parameters.set_parameter({"parse_date": True}) does not actually return dates when using .get_data(). There is a timestamp variable in the data set I am trying to obtain. To my knowledge I should then be able to use a filter with the “BETWEEN” keyword to retrieve the data in the desired date range. The timestamp data is of a “DATETIME” type according to .get_type(). When I parse a datetime element the following error appears: TypeError: Object of type datetime is not JSON serializable I then attempted to use the DjangoJSONEncoder to no avail and various other methods of parsing a start and end timestamp. -
displaying and submitting different forms in single template in Django according to request
I am a newbie and I am working on a project in Django 3.1.2, Here I am creating a profile page where User(admin) can see/edit his/her profile details and also change password. All these functionalities I want to perform on single page but I can't understand the logic . models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') These are the functions I have created but not able to call the functions according to requirement. views.py def profile(request): form = EditProfile() return render(request, 'admin1/profile.html', {'form': form}) def changePassword(request): if request.method == 'POST': print("hi") form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! return redirect('admin-profile') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'admin1/profile.html', { 'form': form }) def editProfile(request): form = EditUserProfile(request.POST, request.FILES, instance=request.user) if request.method == 'POST': form = EditUserProfile(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect('view-profile') context = {'form': form} return render(request, 'admin1/profile.html', context) urls.py path('profile/', views.profile, name="admin-profile"), path('editProfile/', views.editProfile, name="admin-edit-profile"), path('changePassword/', views.changePassword, … -
Foundation Modal instantly closing
Hi guys how are you doing? This is my first Django project, and Im using Foundation for building my frontend (all new to me). I want to display a foundation reveal modal, and it opens, but instantly closes, not letting me push the close button or do anything. I can see the modal well created, with the button and correct context var, but in less than a second it closes and page is refreshed This is my html code {% extends "panel.html" %} {% load static %} {% block panel-content %} <div class="grid-x medium-10"> <h3 class="cell medium-12" style="text-align: center;color: wheat;">Usuarios del Sistema</h3> <div class="cell medium-12">&nbsp </div> <div class="cell medium-11 small-9"></div> <a href="{% url 'users_app:user-register' %}" class="success button cell medium-1 small-3"><i class="fi-plus"></i>&nbsp Agregar</a> <table class="cell medium-12"> <thead> <th>Usuario</th> <th>Nombre</th> <th>Teléfono</th> <th>Última Conexión</th> <th>Rol</th> <th>Estado</th> <th>Acciones</th> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.user_name }}</td> <td>{{ user.full_name }}</td> <td>{{ user.phone }}</td> <td>{{ user.last_login }}</td> <td>{{ user.get_role_name }}</td> <td> {% if user.is_active %} <span class="label success">Activo</span> {% else %} <span class="label alert">Inactivo</span> {% endif %} </td> <td> <div class="button-group"> <a href="#" class="button warning tiny"><i class="fi-eye"></i></a> {% if user.is_superuser %} <a href="#" class="button tiny disabled"><i class="fi-pencil"></i></a> <a href="#" class="button alert tiny … -
My Blog shows Same Content in Every post (Django)
I have created a blog using Django, I can add blogs in Django admin, but when I view blogs in my site, it shows the same content in every blog as was in the first blog that I added. -
CartItem matching query does not exist
So I get CartItem matching query does not exist error when I try to add to cart, I'm trying to check if the user already has that item in their cart and if they do not then it is supposed to be added, if they do then it will not be added again, When i click add to cart it gives me CartItem matching query does not exist. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem from django.contrib.auth.decorators import login_required from .forms import BookForm # Create your views here. def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already … -
Pagination using javascript only
I'm working on a Django project my code is javascript heavy, I want a way to do pagination with javascript only first i'm fetching from all_posts url to get all posts data fetch('/all_posts') .then(response => response.json()) .then(posts => { display_posts(user, posts) }) then the method display_posts create a card for each post and append it to <div id="all_posts"> in index.html function display_posts(userr, postss){ for (post in postss){ //create each post_container //put data inside it document.querySelector('#all_posts').append(post_container) } I can't go back to do it with Django loops and pagination in html, I want a way to do it using javascript only can anyone help me please and provide me with code examples on how to it using any plugin, thanks in advance -
does a user changing the title / slug cause an issue if i continue to get the correct post by pk?
Currently i have a django project where a user can ask a question and the title becomes the slug. MEaning the url is website/pk/slug To get to the url i use a basic DetailView which just uses the model. URLs path('question/<int:pk>/<str:slug>/', QuestionDetailView.as_view(), name='question-detail'), path('question/<int:pk>/<str:slug>/update/', QuestionUpdateView.as_view(), name='question-update'), View class QuestionDetailView(DetailView): model = Question When the user changes the title of the question, i do not update the slug but only the title. class QuestionUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question form_class = QuestionForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): question = self.get_object() if self.request.user == question.author: return True return False This mean is the original url upon question creation was website/1245/How-do-i-blah i can still get to the question with any slug after website/1245/ i would think this might be a problem but i cannot see why, as google will index the slug and as i am looking up by pk if the title changes it should automatically return the right question. Why do i think this might cause problems in the future? And should i be looking up the question by pk and slug. -
How to make Django-Admin timezone aware?
I want to show all the datetime fields in databases in a different timezone than the default ('UTC') timezone only for the admin. I found a few proposed solutions which are more catered towards saving timezones per user. However I am looking for a solution which only solved the problem for the admin. Any suggestion will be much appreciated. -
Memcached not caching page if it's requested by artificial request. Django
I use memcached for caching a page for 1 hour. My settings are following: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } I use method decorator to cache the view. @method_decorator(cache_page(60 * 60), name='dispatch') I want to warm up cache every hour. I do it by emulating request to the view. login_url = LOGIN_URL target_url = TARGET_URL request = requests.session() response = request.get(login_url) token = response.cookies['csrftoken'] data={'username': username, 'password': password,'csrfmiddlewaretoken':token} response = request.post(login_url, data=data) response = request.get(target_url) However, unlike requesting the view myself (by hands) it doesn't work. What am I doing wrong? -
TypeError: __init__() missing 2 required positional arguments: 'to' and 'on_delete'
I am just fresher and trying to build my first Blog App. after setup every thing... I wrote some codes in models.py file ----- Models.py file code ================= from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=250) summary = models.TextField() slug = models.SlugField() body = models.TextField() author = models.ForeignKey() auther = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title ============= ============= ============ ======= but it is giving me error -- File "E:\BlogProject\blog\blogapp\models.py", line 6, in class BlogPost(models.Model): File "E:\BlogProject\blog\blogapp\models.py", line 12, in BlogPost author = models.ForeignKey() TypeError: init() missing 2 required positional arguments: 'to' and 'on_delete' ========== ============== ============== I will be very thankful for your suggestions. Thanks