Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CKEditor custom config not working, And it has different options inside and outside of admin panel
based on customizing CKEditor editor I declared a custom config in settings.py: CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', 'toolbar_CustomToolbarConfig': [ {'name': 'clipboard', 'items': ['Bold', '-', 'Undo', 'Redo']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'BidiLtr', 'BidiRtl', '-', 'spellchecker' ]}, ], }, } this config is used in models.py: description = RichTextField(config_name='awesome_ckeditor', blank=True) in html file I use ckeditor in this way: <form action="{% url 'contact' %}" method="POST"> {% csrf_token %} <div> <textarea name="message" id="message" class="form-control"></textarea> </div> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdn.ckeditor.com/4.15.0/full/ckeditor.js"></script> <script> CKEDITOR.replace( 'message'); CKEDITOR.config.allowedContent = true; CKEDITOR.config.removeFormatAttributes = ''; </script> this config is not working. how to load it? before declaring this config, I was getting different editor options inside admin panel and outside ot it: inside admin panel: and outside it: how to fix this config so all pages have same config? -
Django&React, "detail": "Authentication credentials were not provided. (CSRF)
] ------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export const CSRFToken = () => { const csrftoken = getCookie('csrftoken'); console.log('token : ' + csrftoken); return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getplayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value) return ajax.get('/api/player/', {headers: {'X-CSRFToken': state.CSRFToken.props.value }} ).pipe( map(response => { const player = response.response; return getplayerSuccess({player}); }), catchError(error => of({ type: GET_player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django(python) ------ view.py class Listplayer(generics.ListCreateAPIView): permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer settting.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'post', 'rest_framework', 'polls.apps.PollsConfig', 'notes', 'knox', 'patientList', 'hospital', 'doctor', 'diagnosis', 'diagnosis.core', 'fundusList', 'users', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] … -
django urls exceptions NoReverseMatch
Good day, I have got a Django project where I want to link to order_detail but I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'orderdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['orders/myorder/detail/(?P<order_id>[0-9]+)$'] models.py from datetime import timezone from django.contrib.auth.models import User # Create your models here. from django.db import models from django.forms import ModelForm from django.urls import reverse from shop.models import Product from decimal import Decimal from django.core.validators import MinValueValidator, MaxValueValidator from coupons.models import Coupon class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) phone_number = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) braintree_id = models.CharField(max_length=150, blank=True) reference_id = models.DateTimeField(auto_now_add=True, blank=True) coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL) discount = models.IntegerField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100) ]) class Meta: ordering = ('-created',) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('orders:orderdetail', args=[self.id]) def get_total_cost(self): total_cost = sum(item.get_cost() for item in self.items.all()) return total_cost - total_cost * (self.discount / Decimal(100)) def delivery_fee(self): fee = 500 return fee def get_total_after_delivery(self): total = self.get_total_cost() + self.delivery_fee() return total class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): … -
Cannot resolve keyword 'articles' into field.Choices are: Choices are: author, caption,id etc
I am trying to relate articles for the user.Here are my codes: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) Serializers.py class UserSerializer(serializers.ModelSerializer): articles_set = serializers.SerializerMethodField() def get_articles_set(self, user): return ArticleViewSerializer(Article.objects.filter(articles__author=user), many=True).data class Meta: model = User fields = ('id','email','username','articles_set') class ArticleViewSerializer(serializers.ModelSerializer): author = UserSerializer(required=False,read_only=True) class Meta: model = Article fields = ('id','author','caption') def create(self, validated_data): return Article.objects.create(**validated_data) Now the issue here is that whenever i try to relate article to a user,i face with this problem Cannot resolve keyword 'articles' into field. Choices are: author, author_id, caption, comments, id How can i solve this problem? -
Django + Ajax. Data submitted two times in database when I click on button at first time
I use django for backend. Data submitted two times when I click button at first time and data submit one time when I clicked button second time and send response two time also. I am not know more about Jquery or Ajax.I need only one time data submit in database. views.py: @require_POST def checkAns(request,pk,ans,user): if request.method == 'POST': question = Question.objects.get(pk=pk) if ans == question.answer_hidden: message = 'Correct' fetch_name = Register.objects.get(name=user) user_data = SubmitAnswer.objects.get_or_create(name=fetch_name) score_in = SubmitAnswer.objects.get(name=fetch_name) score_in.score += question.point score_in.save() else: message = "False" ctx = {'message': message} return HttpResponse(json.dumps(ctx), content_type='application/json') question.html: **Other stuff like question,radio button,etc** <button type="submit" class="btn btn-primary" id="b1" onclick="getans()">click</button> <p id="userans"></p> <script> $(document).ready(function () { $('#b1').on('click', function (e) { const id = document.getElementById('question_id').className const ans = document.getElementById('userans').innerText const user = document.getElementById('session').innerText $(".rb").show(); $(".rb").attr("disabled", true); $.ajax({ type: "POST", url: `http://127.0.0.1:8000/checkAns/${id}/${ans}/${user}/`, data: { 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: "json", success: function (response) { console.log(response) }, error: function (rs, e) { if(rs.status === 404){ alert("Please, Select Appropriate Option") } else{ alert("sorry, Something went wrong!!!") } } }) }); }); </script> <script type="text/javascript"> function getans(e){ document.getElementById("userans").innerHTML = ""; var e = document.getElementsByTagName("input"); for(i = 0; i<=e.length; i++){ if(e[i].type == 'radio') { if(e[i].checked){ document.getElementById("userans").innerHTML = e[i].value } } } … -
Invalid symlink "venv/bin/python3"
I'm trying to upload my Django code to Heroku but I am getting a build error.. === Fetching app code failed. =!= Invalid symlink "venv/bin/python3". Cannot point outside the working directory My Pipfile is name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "~=3.1.0" whitenoise = "==5.1.0" gunicorn = "==19.9.0" psycopg2-binary = "==2.8.5" pillow = "==7.2.0" django-debug-toolbar = "==2.2" environs = {version = "==8.0.0", extras = ["django"]} django-storages = "*" boto3 = "*" [requires] python_version = "3.8" Is anyone able to help me please? -
How can I storage IP addresses any time someone logs in my app? Django
My goal si to storage Ip addresses and make an alert if in the next login the ip address of that person isn't the same. How can I do? -
Django tests are not working but views do
I'm trying to test to insert data into db to test if My views are working. What could i do to see what's happening inside the page? I've one error, when i try to assert if data that I've sent to My form exists. The stranger thing is that when i run My application with runserver, everything works fine, but when i'm in test, the view doesn't work. -
Return Full image Url in Django Rest Framework For Image
I am facing problem in returned image url, which is not proper. My return image URL is "/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG", but actual URL expected from serializer is http://127.0.0.1:8000/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG Here is my snippet of my Code that I have tried. class ListSliderSerializer(SliderSerializers): images = serializers.SerializerMethodField('get_images') def get_images(self, instance): return [slider_image.image.url for slider_image in instance.slider_image.all()] class Meta(SliderSerializers.Meta): fields = ( 'images', 'section', 'tag', ) what should i return in return [slider_image.image.url for slider_image in instance.slider_image.all()] to get full url for my image? -
docker-compose Vue Connection Reset Error
I am trying to start my Vue.js and Django Application with docker-compose. I can access the Django server, but the Vue frontend answers with Error: The connection was reset. Here are my Files: Dockerfile-django: FROM alpine:latest RUN apk add --update python3 py3-pip WORKDIR /app/backend COPY . . RUN pip3 install -r requirements.txt RUN python3 manage.py makemigrations RUN python3 manage.py migrate EXPOSE 8000 CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ] Dockerfile-vue: FROM alpine:latest RUN apk add --update nodejs npm WORKDIR /app/frontend COPY . . RUN npm install --save axios @vue/cli bootstrap-vue v-tooltip @popperjs/core jquery @vue/test-utils jest RUN npm audit fix RUN npm run build EXPOSE 8080 CMD [ "npm", "run", "dev" ] docker-compose.yml: version: "3.8" services: django-server: build: context: "./backend" dockerfile: "Dockerfile-django" ports: - "8000:8000" container_name: app-backend vue-ui: build: context: "./frontend" dockerfile: "Dockerfile-vue" ports: - "8080:8080" container_name: app-ui Both containers start fine and as I said, I can access the Django server just fine. Only the frontend seems to be the problem. -
Django reload current page using a button
Is there actually any way to simply reload the page in Django I'm currently viewing, preferably at the template with a button? Why do I need this: My website displays messages and I simply just want to give the user the ability to click on a button to make the message disappear. To make a message disappear I have to reload the current page ... Implementing this is JS is not an option! Thanks and kind regards -
TypeError at /cart/ 'Product' object is not subscriptable
I'm creating cart model in RESTful API project. For each product in request by using for statement I want to save each product, cauz in one request may appear more than one product in cart. Below is my serializers.py: from rest_framework import serializers from main.serializers import ProductDetailsSerializer from main.models import Cart, Product, CartProduct # создаем сериализатор orderproduct class CartProductSerializer(serializers.ModelSerializer): class Meta: model = CartProduct fields = ('product', 'count') class CartProductRepresentationSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='product.id') title = serializers.CharField(source='product.title') class Meta: model = CartProduct fields = ('id', 'title', 'price', 'count', 'product') class AddProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id') class CartSerializer(serializers.ModelSerializer): items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа class Meta: model = Cart fields = ('count', 'items') # передаем все эти поля сюда def get_total_cost(self, obj): return obj.get_total_cost() # здесь мы добавляем total cost (def get_total_cost(self. obj)) def create(self, validated_data): request = self.context.get('request') items = validated_data.pop('items') cart = Cart.objects.create(**validated_data) if request.user.is_authenticated: cart.user = request.user cart.save() for product in items: product = product['product'] # print(product) product_id = request.GET.get('product') CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count']) product.save() def to_representation(self, instance): representation = super().to_representation(instance) representation['user'] = instance.user representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data return representation Here is the models. I create Cart and CartProduct … -
Django Admin site 'int' has no len() error on model form submit
When trying to submit a model form (/add/) in the Django admin site, I get the following error: TypeError object of type 'int' has no len() Models.py: class Card(models.Model): visible = models.BooleanField(default=True, verbose_name="Visible to Customers?") software = models.ForeignKey(Software, default=1, on_delete=models.CASCADE) product = ChainedForeignKey( Product, chained_field="software", chained_model_field="software", auto_choose=True, show_all=False, sort=True, default=0,) utility = models.ForeignKey(Utility, verbose_name='Utilities', default=1, on_delete=models.CASCADE) function = ChainedForeignKey( Function, chained_field="utility", chained_model_field="utility", auto_choose=True, show_all=False, sort=True, default=0,) error_code = models.ForeignKey(ErrorCode, default=0, on_delete=models.CASCADE, help_text="Please only use for error codes, if no code, leave empty.") message = RichTextUploadingField(default="", help_text='Message can include markdown for styling.') tags = RichTextUploadingField(default="", blank=True, null=False, help_text='Add Text that can be used as tags for searching for this card.') encountered = models.ManyToManyField(Encountered, default=0, verbose_name='Encountered in', help_text='Version or Year. Select "N/A" if unknown.') resolved = models.ForeignKey(Resolved, default=0, on_delete=models.CASCADE, verbose_name='Resolved in', help_text='If not resolved, enter "N/A".') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) card_created_by = models.ForeignKey( 'auth.User', related_name='card_created_by', on_delete=models.CASCADE, verbose_name='Created by', null=True) last_edited_by = models.ForeignKey( 'auth.User', related_name='last_edited_by', on_delete=models.CASCADE, verbose_name='Last edited by', null=True) card_view_count = models.IntegerField(default=0) class Solution(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE, null=True) cause = RichTextUploadingField(blank=False, help_text='Message can include markdown for styling.') cause_solution = RichTextUploadingField(blank=False, verbose_name='Solution', help_text='Message can include markdown for styling.') solution_edited_by = models.ForeignKey( 'auth.User', related_name='solution_edited_by', verbose_name='Last edited by', on_delete=models.CASCADE, blank=True, null=True ) … -
How to only accept date inputs of more than 18 years ago in Django
I have a form that allows users to update their birthday on their profile. I want it to only be valid if the user is at least 18 years of age. Here's what I've tried: models.py class Profile(models.Model): birthday = models.DateField() forms.py from django import forms from datetime import datetime from .models import Profile class ProfileUpdateForm(forms.ModelForm): birthday = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) def clean_birthday(self): dob = self.cleaned_data['birthday'] age = (datetime.now() - dob).days / 365 if age < 18: raise forms.ValidationError('You must be at least 18 years old') return dob class Meta: model = Profile fields = ('birthday',) Upon submit I am getting the TypeError unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' Here is my view: @login_required def update_my_profile_view(request): profile = Profile.objects.get(user=request.user) form = ProfileUpdateForm(request.POST or None, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() return redirect('users:my_profile') Can somebody please explain what I've done wrong? -
update django models column based on other column
I have a model like class tbl_payment(models.Model): document_id = models.ForeignKey(tbl_invoice, on_delete=models.CASCADE) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date = models.DateField(blank=True, null=True) status = models.CharField(max_length=50) Now what I want to do is whenever a new record is added, or an existing record changes, balance should be updated as the difference between total_amount and paid_amount (simple maths), and based on my balance column, I want to save status as Paid, Partial or Unpaid. I want to refrain from calculating the balance in my views and then saving in the database, instead, I want to handover this part to my models so that my models take care of the balance and I may avoid errors which I am subconsciously afraid of. I came to know that this is done something like this class tbl_payment(models.Model): document_id = models.ForeignKey(tbl_invoice, on_delete=models.CASCADE) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date = models.DateField(blank=True, null=True) status = models.CharField(max_length=50) @property def balance(self, value): return self.total_amount - paid_amount but what should I pass in place of value?? also when I … -
Why do I get: save() missing 1 required positional argument: 'self'
If I put to this endpoint, I get the following error: save() missing 1 required positional argument: 'self' Can anyone understand why? If any addiotional information is needed, please let me know. @api_view(['GET', 'PUT']) def qc_demux_detail(request, demux_qc_id): qc_demux_results = DemuxQCResult.objects.filter(demux_qc_id=demux_qc_id) if request.method == "GET": serializer = QCDemuxResultSerializer(qc_demux_results, many=True) return Response(serializer.data) if request.method == "PUT": serializer = QCDemuxResultSerializer(DemuxQCResult, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
string dictionary converted into json form
I have a textarea where input is in this format { "access_token": "#TOKEN_ACCESS_TOKEN", "tickets": [ { "hr_remarks": "#TOKEN_HR_REMARKS", "status": "#TOKEN_STATUS", "ticket_id": #TOKEN_TICKET_ID } , { "hr_remarks": "#TOKEN_HR_REMARKS", "status": "#TOKEN_STATUS", "ticket_id": #TOKEN_TICKET_ID } ] } I want to convert this data into json form. I try to use through json.load() it cause an error: Json decoder Error -
django check_password return false with correct password
i have this custom user with email backend and as you can see i'm using set_password before saving but its still not matching with correct password on this user.check_password(password) in emailbackend and i'm creating user with drf backend.py: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: print('this is user right', user, password) if user.check_password(password): return user return None serializers.py: class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) user.save() return user -
How to use more than one _base.html file using django-two-factor-auth?
Django-two-factor-auth library requires one to use the two_factor/_base.html to customize the styling when integrating into your website. The base for my login page is however different to that for the dashboard of a logged in user. How can I use a different _base.html for the login page instead of using the same base for all the two factor pages? -
Django getattr by name for related field call query with select_related and prefetch_related
I have a class with multiple relations like this: class Object() -> class TT() -> -> class User() -> class Actor() -> -> class Type() -> class Type() Need to get Object attributes and relation attributes by dinamic names like "tt__name" / "tt__user__type" / "actor__type__date" and oth. For querying i'm using select_related and prefetch_related('xxxx',...), but when i use getattr like this: if '__' not in model_field: cell_value = getattr(qs_object, model_field, None) else: r_class, r_field = model_field.split('__', maxsplit=1) related_object = getattr(qs_object, r_class, None) while '__' in r_field: r_class, r_field = r_field.split('__', maxsplit=1) related_object = getattr(related_object, r_class, None) cell_value = getattr(related_object, r_field, None) Django call query for each getattr with relation. How to realize this another way or force Django to get attr from fetched values? Halp -
Create a django home page
How to create django home page , with base.html , I ask for a simple sample, and routing ? I have already tried , to chreate sample code for home how to continue Thankyou, -
django-ratelimit stack keys. Not the intended behaviour
I think my understanding of django-ratelimit is incorrect. I am using v3.0.0 but v2.0 produces the same results. Lets say I have this code: @ratelimit(key='post:username', rate='5/h', block=True) @ratelimit(key='post:tenant', rate='5/h', block=True) @csrf_exempt def index(request): print(request.POST["username"]) print(request.POST["tenant"]) print("") return HttpResponse('hallo', content_type='text/plain', status=200) Let's say tenant A submits username "Antwon" 6 times, then tenant A will be blocked for 1 hour, which is good. But, lets say tenant B also has a user "Antwon", then that user for tenant B will not be able to log in. I would assume that Antwon for tenant B should still be able to log in, otherwise tenant A can DOS other tenants? Is this intended behavior or is my implementation incorrect? -
Django Template: Csrf token invalid for multiple post request in the same form
Im working on a Django project and got stuck in a problem that involve csrf token. I have a form that i handle the submit with javascript function, because in the same form i need to perform 2 POST. Form is something like that: <form> {% csrf_token %} <input name="field_1" type="text"> .... .... <input name="file" type="file"> <button onclick="send_form()"> Send data </button> </form> the send_form() method performs two post request with axios. The first send the textfields and the second the file. I need to do this because the server two different api for manage the text data and the file. The problem is that the first post succeeds and then the second fail, giving 403 error and in the header i can see the error "CSRF Failed: CSRF token missing or incorrect." There is a way to do this in a single form? I read that someone apply the csrf to the entire body of the page but i can't figure out how to do it. Thank you for any answers. -
Django Database QuerySet
I'm trying to work with Databases using Django's ORM. I'm looking to retrieve a value from a specific column in a database and then convert it from a QuerySet type to a Int or String so I can then work with this data. So my question is, how can I convert a QuerySet to a usable data type? -
setting a django object column-field to None & how to access an object field's name
I'm trying to set a django object field/column to null using a function in my views.py. This is the model. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) RB1 = models.CharField(max_length=80, null=True) WR = models.CharField(max_length=80, null=True) TE = models.CharField(max_length=80, null=True) D = models.CharField(max_length=80, null=True) K = models.CharField(max_length=80, null=True) this is the views.py. It's not actually a "delete" function as I've learned you can't delete object fields, but you can set them to None. def delete_player(request, id, col_name): player = Myteam.objects.get(id=id) setattr(player, col_name, None) player.save() return redirect('show') I'm looping through the object's fields and displaying them as html table rows, but to get this views.py function working, I need to get the "col_name" from the respective column/field. I understand that django will set a default field name but I can't find how to access it. Various sources say to use "field.name" but I've tried testing this out with a print statement and django gives me an attribute error/no such attribute as 'name' for example. team = Myteam.objects.all() for t in team: print(t.WR, t.id, t.name) So, how can you access/pass a field's name? I got some interesting advice on this earlier from another user