Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my API runs properly in local device but once I run it in production with HTTPS I encounter an server error 500
This is the code for my views.py class FetchCustomerUsingQRView(APIView): authentication_classes = [JWTAuthentication] def get(self, request): code = request.data.get('unique_code') try: customer = Customer.objects.get(unique_code=code) print(customer) if customer.already_claimed == True: return Response({ 'message': 'You have already claimed', }, status=status.HTTP_400_BAD_REQUEST) data_serializer = CustomerSerializer(customer) return Response({"data": data_serializer.data}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'message': 'invalid unique code', }, status=status.HTTP_400_BAD_REQUEST) this is working properly in localhost and I also try to run it in my virtual machine localhost and works perfectly but I receiving an error when running in production. my Settings already set to DEBUG = False ALLOWED_HOSTS = ['*'] -
Django: time data '2022-09-02 11:13 am' does not match format '%Y-%m-%d %H%M%S.%f'
I am trying to format DateTime in the views.py file. But I am getting this error while converting data to DateTime. Here is my code. FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").date() FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").strftime('%Y-%m-%d') I have tried both ways to convert data but it is not working for me. I am new to python Django. Grateful for the help in advance. -
Adding columns to pandas not working with Django ORM
I am trying to add columns to existing pandas DataFrame. The added column gets data using Django ORM. My approaches are like the following: 1. df['name'] = User.objects.get(id=df['id']) df['name'] = df.assign(name=lambda x: User.objects.get(x.id)) But for both the approaches, I am getting the following error: TypeError: Field 'code' expected a number but got 0 1 1 18 Name: code, dtype: int64. The field is expecting a number but getting a pandas Series instead. How shall I approach this? -
How to access static variable inside instance method
So i am using a GenericAPIView when my post method is hit function gets called and perform certain action like creating and completing some objects in my class. so i am using a static method here but in exception i am not being able to refer to variable named var used in static method to use in my post method exception class MyApiView(GenericAPIView): @staticmethod def my_custom_method(arg): if condition1 and condition2: var = Class1(arg=arg) var.create() var = Class2(arg=arg) var.complete() if condition4 or condition3: var = Class3(arg=arg) var.create() def post(self, request): try: my_cust_method(arg) except Exception: logger.error(f"{var.__class__}", exc_info=True) Unresolved reference var -
DateTimeField throwing datetime is not serializeable
I have added a new Datetime field in my model. class MyModel: valid_upto = models.DateTimeField(auto_now=True, blank=True, null=True) and my serializer code is class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' When i am updating one instance i am getting TypeError: Object of type datetime is not JSON serializable the value that can come in valid_upto is None or a datetime value which i am getting from timezone.now() -
How to change error messsage I am getting in django for foreign key
Below is my code funding = models.ForeignKey(TblHcrMasterLookupOptions, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_funding',) tpa_for_reference_year = models.ForeignKey(TblHcrVendors, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_tpa') pbm_for_reference_year = models.ForeignKey(TblHcrVendors, models.DO_NOTHING, null=True,blank=True, related_name='%(class)s_pbm') I am getting this error message "renewal_month": [ "Incorrect type. Expected pk value, received str." ], "funding": [ "Incorrect type. Expected pk value, received str." ], "pbm_for_reference_year": [ "Incorrect type. Expected pk value, received str." ], I want to change the error message and want my custom error message -
Implement RDKit and Postgres in Django
I started to use rdkit and try to implement in Django with postgres. So I installed rdkit in my django virtualenv with pip install rdkit-pypi and also installed django-rdkit(https://github.com/rdkit/django-rdkit). This command: python3 -c "from rdkit import Chem; print(Chem.MolToMolBlock(Chem.MolFromSmiles('C1CCC1')))" works fine to me. But when I run migrate, it failed. The error is : django.db.utils.OperationalError: could not open extension control file "/usr/share/postgresql/12/extension/rdkit.control": No such file or directory It seems failed to create cartridge rdkit with postgres. Anyone can help me find the problem and solution (better not with Conda, cause I never use it before)? Thank you very much! -
React and Django google login
I am working in backend to create google login service and this login will be seen in react.I have seen many resources but none make me understand cause I am not familiar with react js. I need user to login from frontend and get access and refresh token and save them in db so user could be always logged till the access token expires and then using refresh token he gets again access token and one more service I need to do is using this access token I should get calender events list. -
How to extend the data in Django Plotly Dash?
I have this existing Django plotly app and it's also updating Realtime. It looks like this my project. Every three seconds the graph is updating but, the problem is it's updating the whole traces not adding a new traces. Is it possible to add the next data to graph? like extendTraces function. I just started learning plotly dash bear with me app = DjangoDash("SimpleExample") app.layout = html.Div( html.Div([ dcc.Graph(id='live-update-graph'), dcc.Interval( id='interval-component', interval=1*3000, # in milliseconds n_intervals=0 ) ]) ) @app.callback(Output('live-update-graph', 'figure'), Input('interval-component', 'n_intervals')) def update_graph_live(n): data = { 'time': [], 'PH': [], 'CON': [], 'TOTAL': [], 'VOLATILE': [], } # Collect some data for i in range(9): time = datetime.datetime.now() - datetime.timedelta(seconds=i*20) ph = random.randint(8, 13) con = random.randint(10, 20) total = random.randint(1, 5) volatile = random.randint(5, 10) data['PH'].append(ph) data['CON'].append(con) data['TOTAL'].append(total) data['VOLATILE'].append(volatile) data['time'].append(time) # Create the graph with subplots fig = plotly.tools.make_subplots(rows=2, cols=2, vertical_spacing=0.2) fig['layout']['margin'] = { 'l': 30, 'r': 10, 'b': 30, 't': 10 } fig.add_trace({ 'x': data['time'], 'y': data['PH'], 'name': 'PH', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) fig.append_trace({ 'x': data['time'], 'y': data['CON'], 'name': 'Conductivity', 'mode': 'lines+markers', 'type': 'scatter', }, 2, 1) fig.append_trace({ 'x': data['time'], 'y': data['TOTAL'], 'name': 'Total Suspended Solids', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 2) … -
Using a Boolean to set a condition to make form appear
I have added boolean to my Model as Active where I want to be defaulted as FALSE and if the user change it to TRUE as in active to make a form appear. Here is what I have done so far. I have created a views for the boolean: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p return context def change_activity (request): if request.is_ajax() and request.method=='POST': log = Log.objects.get() log.active = True if request.POST.get('active') == 'true' else False log.save() data = {'status':'success', 'active':log.active} return JsonResponse(data, status=200) else: data = {'status':'error'} return JsonResponse(data, status=400) and I have added the urls: path('changeactivity', change_activity, name="change_activity"), Here is the template for changing the active option: <div> <button {% if not p.active %} {% endif %} id="customSwitches" onclick="start();" type="button"> Start the activity </button> </div> <script type="text/javascript"> $(document).ready(function() { // send request to change the active state on customSwitches toggle $("#customSwitches").on("change", function() { $.ajax({ url: "{% url 'my_gym:change_activity' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", active: this.disabled // true if checked else false }, type: "POST", dataType : "json", }) // $.ajax().done(), … -
Is there a way to customize the value of specific field in a model in django when adding a new data?
I have a model here which I want to specify the value of unique_code everytime I'm adding a new data . model.py class Customer(models.Model): LastName = models.CharField(max_length=45, blank=True) FirstName = models.CharField(max_length=45, blank=True) MiddleName = models.CharField(max_length=45, blank=True) ExtensionName = models.CharField(max_length=45, blank=True) GenderID = models.ForeignKey(Gender, on_delete=models.CASCADE) id_pic = models.ImageField(null=True, blank=True, upload_to=upload_path) otp = models.CharField(max_length=6, blank=True) unique_code = models.CharField(max_length=8, blank=True) verified = models.BooleanField(default=False) already_claimed = models.BooleanField(default=False) email = models.CharField(max_length=45, blank=True) Birthdate = models.CharField(max_length=45, blank=True, null=True) cellphone_number = models.CharField(max_length=45, blank=True, null=True) agreement1 = models.BooleanField(null=True) agreement2 = models.BooleanField(null=True) agreement3 = models.BooleanField(null=True) I try to override the save method to do that and here is my code def save(self, *args, **kwargs): self.unique_code = uuid.uuid4().hex[:8].upper() super().save(*args, **kwargs) but the problem with this approach is that the unique_code change everytime I update the data. and I want the unique_code to not change once the data has been save to database. so is it possible to specify its value here in view.py data = request.data serializer = CustomerSerializer(data=data) how to add unique_code = uuid.uuid4().hex[:8].upper() in this serializer = CustomerSerializer(data=data) -
Getting total in cart
Guys in my cart part of my project I have registered two people and first is working good, but the second one is getting first user's total sum and it is not changing when i add new product or delete other product -
How can i take user input validate the input using values in a dictionary and then add the corresponding value to the querystring in the API
I am building a web app that takes users' input and then returns the result using Google Finance API. My problem is I do not know how to write this in my views.py file that way when a user types in a currency. someapp/coins.py coins = [ {"Ethereum": "ETH-USD"}, {"Bitcoin": "BIT-USD"}, {"Litcoin": "LIT-USD"}, {"Solona": "SOL-USD"}, {"Binance": "BNB-USD"}, {"Ripple": "XRP-USD"}, {"XRP": "XRP-USD"}, {"Cardano": "ADA-USD"}, {"Dogeoin": "DOGE-USD"}, {"Chainlink": "LINK-USD"} ] this is the file that has the tickers needed to get results from the google finance api. So I am trying to check the users input with one of the keys in this list and then add the value which is the ticker needed for the search api to the querystring used in the the GET request. someapp/views.py from django.shortcuts import render import requests from django.views import generic from django.views.generic import TemplateView from django.http import HttpResponse from coins import coins # Create your views here. def index(request): return render(request, 'index.html') def news(request): if request.method == 'POST': crypto = 'POST' if crypto == coins[0:]: querystring.append() # not sure if this is the right thing to do else: pass url = "https://google-finance4.p.rapidapi.com/ticker/" **querystring = {"t":"ETH-USD","hl":"en","gl":"US"}** headers = { "X-RapidAPI-Key": "31c5541e87msh0684494d7f7396fp117984jsn574856ff6d0c", "X-RapidAPI-Host": "google-finance4.p.rapidapi.com" } response … -
Django celery task repeats every hour, it should be executed only once per day
The course_message_schedule_task runs every day at 04:00:00. In it, we register the course_message_send_task to run at 10:00:00 every day. However, if you look at the log below, course_message_send_task repeats every hour from 04:00:00 to 10:00:00. (businessletter_send_task is being repeated in the same way.) It should be run once every day, I don't know why this task is repeating. settings # ... settings.CELERYBEAT_SCHEDULE.update( { "send-emon-data-task": { "task": "klms.emon_api_task.send_emon_data_task", "schedule": crontab(hour="*", minute="0"), "kwargs": {}, }, "course-message-schedule-task": { "task": "klms.tasks.course_message_schedule_task", "schedule": crontab(hour="4", minute="0"), "kwargs": {}, }, "create-coursereport-task": { "task": "klms.tasks.create_coursereport_task", "schedule": crontab(hour="5", minute="0"), "kwargs": {}, }, "businessletter-schedule-task": { "task": "klms.tasks.businessletter_schedule_task", "schedule": crontab(hour="6", minute="0"), "kwargs": {}, }, } ) # ... tasks @shared_task(base=LoggedPersistOnFailureTask, default_retry_delay=30) def course_message_send_task(): """ today's messages """ # default 10:00:00 time_part = settings.COURSE_MESSAGE_SENDING_SCHEDULE_TIME.split(":") schedule_time = localtime().replace( hour=int(time_part[0]), minute=int(time_part[1]), second=int(time_part[2]), microsecond=0, ) # filter ids = list( MessageService.objects.filter(schedule=schedule_time) .exclude( status__isnull=False, ) .values_list("id", flat=True) ) # send! MessageService.status_handler(ids) @shared_task(base=LoggedPersistOnFailureTask, default_retry_delay=30) def course_message_schedule_task(): """ schedule course messages """ enrollmentinfo = ( EnrollmentInfo.objects.message_context() .filter( # 학습 시작일, n주차, 종료일, 종료 다음날 Q(days_from_study_start=1) | Q(ordinal_in_week=1) | Q(days_to_study_end__in=[0, -1]), # 종료되기 전 과정 days_to_study_end__gt=-1, ) .exclude(email_notification=False, text_notification=False) .distinct() ) messages = [] # default 10:00:00 time_part = settings.COURSE_MESSAGE_SENDING_SCHEDULE_TIME.split(":") schedule_time = localtime().replace( hour=int(time_part[0]), minute=int(time_part[1]), second=int(time_part[2]), microsecond=0, ) for … -
f string changing into multiple variable stiring
params = {"id": f'{[product.id,product2.id]}'} currently output of params is : {'id': "('5', '6')"} but I would like to change it so that it can be ids can be used as /?id=5,6 in a parameter of a url. I think this would be currently used as /?id=('5','6'). How would I change this as such. -
django form not saving to database(no error message)
First of all, I apologize for using a translator because I am not familiar with English. My Views.py def my_create_view(request): if "reg" in request.method == 'POST': first_form = FirstRegForm(request.POST, prefix='firstform') second_form = SecondRegForm(request.POST, prefix='secondform') if all([first_form.is_valid(), second_form.is_valid()]): form = first_form.save(commit=False) form.created_name = request.user.user_name form.save() formm = second_form.save(commit=False) formm.shop_seq = form formm.save() return redirect('someview') else: first_form = FirstRegForm(prefix='store') second_form = SecondRegForm(prefix='input') return render(request, 'app/template.html', {'first_form': first_form, 'second_form': second_form}) My Models.py from django.db.models import Max class My_user(AbstractBaseUser): shop_seq = models.ForeignKey('My_shop', null=True, blank=True, on_delete=models.SET_NULL, db_column="shop_seq") user_name = models.CharField(max_length=50) class My_shop(models.Model): shop_seq = models.CharField(primary_key=True, editable=False, max_length=5) shop_name = models.CharField(max_length=20, null=True) shop_code = models.CharField(max_length=15, null=True, unique=True) shop_address = models.CharField(max_length=40, null=True) shop_tel = models.CharField(max_length=20, null=True) created_name = models.CharField(max_length=100, null=True) def save(self, **kwargs): if not self.shop_seq: max = Rate.objects.aggregate(shop_seq_max=Max('shop_seq'))['shop_seq_max'] + 1 self.shop_seq = "{:05d}".format(max if max is not None else 1) super().save(*kwargs) class My_model(models.Model): model_id = models.BigAutoField(primary_key=True) my_field = models.CharField(max_length=20, null=True) some_field = models.CharField(max_length=20, null=True) shop_seq = models.ForeignKey('My_shop', on_delete=models.SET_NULL, null=True, db_column="shop_seq", related_name="shop_model") My Forms.py class FirstRegForm(forms.ModelForm): class Meta: model = My_shop fields = ('shop_name', 'shop_code', 'shop_address', 'shop_tel',) class SecondRegForm(forms.ModelForm): class Meta: model = My_model fields = ('my_field', 'some_field',) My Template.py <form method="post">{% csrf_token %} {{ first_form.shop_name }} {{ first_form.shop_code }} {{ first_form.shop_address }} {{ first_form.shop_tel }} {{ … -
How to add another chart in Django Plotly Dash app?
So, I have this existing code that generates number of data and updating Realtime. Is it possible to create a new chart like another scatter in the same file or app? I just started using Plotly dash, I'm familiarizing it. app = DjangoDash('SimpleExample') app.layout = html.Div([ # html.H1('Square Root Slider Graph'), dcc.Graph(id='slider-graph', animate=True, style={"color": "#15803D", 'color': '#000000'}), dcc.Interval( id='interval-component', interval=1*2000, # in milliseconds n_intervals=0 ) ]) @app.callback( Output('slider-graph', 'figure'), [Input('interval-component', 'n_intervals')]) def display_value(n_intervals): data = {} now = datetime.now() data["temperature"] = random.randint(23, 25) data["tss"] = random.randint(5, 8) data["vss"] = random.randint(1, 4) data["bod"] = random.randint(1, 7) data["doc"] = random.randint(8, 13) data["cod"] = random.randint(5, 12) data["ph"] = random.randint(2, 13) data["turbidity"] = random.randint(1, 5) data["conductivity"] = random.randint(1, 7) date = now.strftime("%Y/%m/%d %H:%M:%S") gg = list(range(0, len(data))) x = gg y = list(data.values()) graph = go.Scatter( x=x, y=y, # name='Manipulate Graph' ) layout = go.Layout( paper_bgcolor='#ffffff', plot_bgcolor='rgba(0,0,0,0)', xaxis=dict(range=[min(x), max(x)]), yaxis=dict(range=[min(y), max(y)]), font=dict(color='black'), ) return {'data': [graph], 'layout': layout} -
Refresh a page without reloading with Django
I'm making a system to detect presence by QR Code with Django, and I need a way to display a image and text when a QR Code is detected without having to reaload the page, i saw something about HTMX but i couldn't do much with it. There isn't much in the internet about using a if statement to do this. views.py from datetime import datetime from django.http import JsonResponse, StreamingHttpResponse from django.shortcuts import render import cv2 import numpy as np from pyzbar.pyzbar import decode from django.views.decorators import gzip from .models import * def camera_feed(request): stream = CameraStreamingWidget() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') class CameraStreamingWidget: def __init__(self): self.camera = cv2.VideoCapture(int(os.environ.get('CAMERA'))) self.media_path = os.path.join(os.getcwd(), "media", "images") # create "media/images" folder if doesn't exist if not self.media_path: os.mkdir(self.media_path) def get_frames(self): while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) # Add text on top of the barcode if there is a barcode in the stream using opencv # convert camera frame to numpy array color_image = np.asanyarray(frame) # decode numpy array to check if there is a barcode in color_image # you can add a custom check here to verify … -
FileNotFound error when trying to download a file in django website
in my index.html I create a link to download a file <ul> {% for fil in listFiles %} <li><a href="{{ fil.csv_file.url }}" download class="btn btn-dark float-right"> {{ fil.csv_file.name }} </a></li> {% endfor %} </ul> the listFiles object is generated from this model from django.db import models from django.conf import settings class CsvDFile(models.Model): csv_file = models.FileField() file_path = models.TextField(max_length=200) userID = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) In the html page the url is like this <li><a href="/uploads/test.csv" download class="btn btn-dark float-right"> test.csv </a></li> However, when I click on it I get this error Not Found: /uploads/test.csv I checked the folder and the file is in there and the folder 'uploads' is inside my app directory Also in settings.py I set MEDIA_URL = 'uploads/' and MEDAI_ROOT = os.path.join(BASE_DIR, 'myapp/uploads') And my urls.py looks like this from django.conf import settings from django.conf.urls.static import static urlpatterns = [..My views..] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) I don't know why it's not recognizing the file -
Django, render with link or remove template dirs when render in view
hai i am newbie in django and sorry for grammar mistake first i have some project to upload file extension .html to AWS S3, so in views.py i want to render a link i've already uploaded to AWS S3. ex: render(request, 'somelink.com', context) , it possible? or any other solution? and also i want to send context parameters why i not using media_url upload to local? cause i have limited disk, and other problem when i do production i cant load media_url, ignore this case, cause i already try many solution -
How do i install exiftool on heroku
i have tried the buildpack but non worked. i got these error when trying to install https://github.com/velizarn/heroku-buildpack-exiftool Installing exiftool 11.36 Fetching https://123456.mycdn.org/downl/Image-ExifTool-11.36.tar.gz gzip: stdin: unexpected end of file tar: Child returned status 1 tar: Error is not recoverable: exiting now ! Push rejected, failed to compile exiftool app. ! Push failed please can someone assist me. my django needs exiftool before it can work. -
get list of all folders in firebase storage using python
i'm using django app and firebase-admin and i have a files and sub folders(nested folders) as shown in image each folder has its own files and folders. i want to get a List of all folders and files inside each root folder , my code is : service_account_key = 'mysak.json' cred = firebase_admin.credentials.Certificate(service_account_key) default_app = firebase_admin.initialize_app(cred, { 'storageBucket': 'myBucketUrl' }) bucket = storage.bucket() blob = list(bucket.list_blobs()) #this is returning all objects and files in storage not for the folder i want for example i want all files in first_stage/math so i can get a url for each file i have also read the docs about firebase storage and there is no such a method -
How can I serialize None from db to empyt object?
I have the following models: class ContentUpload(BaseModel): ... status = models.ForeignKey(CourseStatus, on_delete=models.CASCADE, related_name="content_status", null=True, blank = True) class CourseStatus(BaseModel): status_name = models.CharField(max_length=250) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.status_name) super(CourseStatus, self).save(*args, **kwargs) def __str__(self): return str(self.status_name) The following serializers: class CourseStatusListSerializers(serializers.ModelSerializer): class Meta: model = CourseStatus fields = ('id', 'status_name', 'slug') def get_status(self, obj): return CourseStatusListSerializers(obj.status, context={"request": self.context['request']}).data When the ContentUpload.status is None it returns the following: "status":{"status_name":"","slug":""} My question is that how can I do it to give back an empty object? What is your best practice for this? "status":{} -
django template for loop if nothing found for specific hostname create a blank cell
I am aggregating multiple outputs from models into the same table. So I am looking for a hostname_id, which ties the models together, and then displaying the output. The problem is there may not be data to display which throws off the alignment of the table so I need to create blank cells. {% for y in cpuAverageReport %} {% if x.id == y.hostName_id %} <td>{{ y.average | floatformat:0}}%</td> <td>{{ y.maximum | floatformat:0}}%</td> {% endif %} {% endfor %} So if, at the end of the loop, the if argument is never matched I want to create two blank cells. I tried using {% with var="something" %} to tag when the if argument is matched but the {% endwith %} tag must be before the endif tag rendering it useless... -
Import "taggit.managers" could not be resolved
Im currently learning django with the book "Django 2" by Antonio Melé. I got an error when I import "from taggit.managers import TaggableManager". I already install django-taggit and django-extensions. I also already added 'taggit' to INSTALLED_APPS. Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', 'taggit', My models.py (There are more classes but I put the one that im working on): from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class Post (models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=150) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() Image of the error, just in case I ran python manage.py shell and after the following: from blog.models import Post post = Post.objects.get(id=1) post.tag.add('post1', 'blogpost', 'tag1') post.tags.all() And the tags were added successfuly.