Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React .map function not working after Django backend GET with axios
I am trying to make a simple React frontend while using Django Rest Framework as a backend. When I make the call to Django and then try to use the .map function to display the data, I get an "Uncaught (in promise) TypeError: this.state.users.map is not a function". I am a React noob so it is definitely something I am doing. import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { users: [] } componentDidMount() { axios.get('http://127.0.0.1:8000/api/users/') .then(res => { const users = res.data; this.setState({ users }); }) } render() { return ( <ul> { this.state.users.map(user => <li>{user.username}</li>)} </ul> ) } } export default App; -
Likes, Dislikes & Views using Django Rest Framework
I'm working on a News Model where I want to perform the likes, dislikes & no of views functionality using the Django Rest Framework(ModelViewset). I have created a model for it Models.py class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views') likes = models.ManyToManyField(User, related_name='Likes') dislikes = models.ManyToManyField(User, related_name='Dislikes') status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py class PostAPI(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer I have tried a lot of ways,but i'm not able to like, dislikes or view the post by multiple users. When a post is liked or disliked by one user & try to like or dislike by another user, it says Like with this post already exist Is there anything that I have left out. Please help it would be a great support. Thanks alot. -
How do I remove the ticks or inner circles of my polar area chart Chart.js
I have written the code for my chart in Jquery and I am using the chart to display data on my Django Web Page, I want to remove the inner circles which I think are called ticks along with the small numbers that are displayed with them. I have tried to use the ticks:{ display: false, } and scale:{ display: false, } but have had no luck with either I am not sure how to do it. Code for Chart: new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fill: true, pointRadius: 1, {# borderColor: backgroundColors_{{ t.pk }} ,#} backgroundColor: backgroundColors_{{ t.pk }} , data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: false, }, scale: { ticks: { display: false, }, gridLines: { display: false, lineWidth: 7, tickMarkLength: 30// Adjusts the height for the tick marks area }, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} {% endblock %} -
How to fix urls patterns testing views in django?
testviews.py class StudentsDetailsViewTest(TestCase): def test_query_search(self): query_set=StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') url=(reverse('api/Student_Details', args=(query_set))) response=self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) output: django.urls.exceptions.NoReverseMatch: Reverse for 'Student_Details' with arguments '(<StudentDetails: Demon>, <StudentDetails: Stefen>, <StudentDetails: james>)' not found. 1 pattern(s) tried: ['api/students\Z'] Ran 1 test in 0.248s FAILED (errors=1) Destroying test database for alias 'default'... I'm trying to testing my query_set views and to figure out testing passing or not, that showing not found pattern i don't get that error means, is there any error near line url? can anyone suggest me what went missing in code? -
Many to one and many to many relationship between same models in django
I am working on a project in django. There are two models similar to users and courses where any user can create multiples course and other users can join any of the courses. So this leads to two relation between the models(users and courses), one to many for creater of a course and many to many for users who join the course. Django gives error on defining two relations on the same models. Currently I have defined foreignkey field in courses table for reference to creater(user) and a third model with foreign key of both the user and courses to keep track of users who join the courses. I just want to know is there a better known way to do this in django. -
Image is not saving in database django
form.html <form> {% csrf_token %} <table> <tr> <td> <label for="name">NAME: </label> <input type="text" data-bind="value: $data.name" name="name" class="form-control" id="name" placeholder="name of product"> </td> </tr> <tr> <td> <label for="price">PRICE </label> <input type="text" name="price" data-bind="value:$data.price" class="form-control" id="price" placeholder="price"> </td> </tr> <tr> <td> <label for="description">DESCRIPTION: </label> <textarea cols="10" rows="5" name="description" data-bind="value:$data.description" class="form-control" id="description" placeholder="product description"></textarea> </td> </tr> <tr> <td> <label for="image">IMAGE: </label> <input type="file" class="form-control-file" id="image" name="image" required> </td> </tr> <tr><td><button type="button" id="submit" data-bind="click : save" class="btn btn-success">Submit</button></td></tr> </table> </form></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <!-- <script type="application/javascript" src="static/js/knockout-file-bind.js"></script> --> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> // $(document).on('click', '#submit', function(e) { var ViewModel = function () { var self = this; self.name = ko.observable(""); self.price = ko.observable(""); self.description = ko.observable(""); self.image = $(document).on('click', "#submit", function(e) { formdata = new FormData(); $('#image').get(0).files[0]; formdata.append('image', image); }); // self.image =$('#image').get(0).files[0]; // formdata = new FormData(); // formdata.append("image", image); // console.log(formdata.get("image")); var PerData = { name: … -
Passing an ID parameter to the Django Channel connect handler for single channel layers
I am setting up a Single Channel websocket layer as documented here https://channels.readthedocs.io/en/stable/topics/channel_layers.html#single-channels But the problem is I need to pass a meta data parameter into the connect method from client-wide websocket initilization because otherwise there is no way to reference it outside of the Consumer. E.g. imagine I want to use a SESSION_ID as the channel name lookup key. Only the client knows the SESSION_ID. I want to be able to do something like: client.js (pass the session id to the websocket connection somehow) monitorWS = new WebSocket('ws://localhost:9000/ws/api/monitor/?SESSION_ID=762123') consumer.py (save the session id with the auto-generated channel name) class ChatConsumer(WebsocketConsumer): def connect(self): # Make a database row with our channel name Session.objects.create(channel_name=self.channel_name, id=[SESSION_ID]) How can I pass that ID parameter so that my code outside the Consumer can pick up the single channel name so that I can do something like this: elsewhere.py from channels.layers import get_channel_layer channel_layer = get_channel_layer() session=Session.objects.get(id=762123) # get the session object in the example await channel_layer.send(session.channel_name, { "type": "chat.message", "text": "Hello there!", }) -
is it possible to prevent/bar more than one person from accessing a page with Django?
Is it possible to prevent/bar more than one person from accessing a page with Django? For example: I have an editing screen for a product, and if someone is accessing that page, for that product, I don't want anyone but can enter that url, to be clearer, let's say I'm editing a product called "smartphone " and his route is http://localhost:8000/product/edit/smartphone, when someone tries to edit this product, he cannot enter the page. That's my question. I don't know if it was very clear, but I ask that whoever knows can help me. -
htmx and django: display feedback on successful/failed request
So I'm trying to display a feedback message saying "added" or "failed" when a form is submitted with HTMX to my Django backend. Basically what I have right now is a form that performs an hx-post, and the reply is a div containing the updated information, which is swapped with the current contents of the div. <div id="list"> <!-- The stuff in here is loaded through another template, which is the result of a successful myApp:add operation. --> </div> <form hx-post="{% url 'myApp:add' eid=e.id %}" hx-swap="outerHTML" hx-target="#list"> <!-- Some stuff in here --> </form> <div id="result"> <!-- Here I should print a message saying correct or incorrect depending on the HTMX result (if the entry was added or there was any kind of error, even connection errors) --> </div> The thing is, in case of an error in the form or in the request itself, the list will remain the same, but I would like for it to print something like "error" in the result div. In case the new entry is added correctly I would like to print a "success" message in the result div. I'm also using Alpine.js, if that's any help. -
What is the best way to collect a log of C++ Application, Running in k8s + django Server?
I've tried searching through Google, but I'm confused which one is the best way. There are ways to use stdout and stderr, but I would like to use a more convenient framework. Is there any tip or standardized way you can give me? -
is that possible to add mutiple images save in one column in mysql using dajngo framework
iam a beginner in the field. i currently doing a ecommerce website which sells samrtphone. 1 .I want to add mulitple product images. In order to add the images do i need more columns for every image. How to add mutiple ram and price for product. Samrtphone have mutiple ram according to ram price varies.user can choose ram of the product. How to add this in to my project using mysql. Do ineed more columns for every ram. -
ModuleNotFoundError: No module named 'base'
every time I try to run my program using python manage.py runserver the same error comes up. I have already added my Django app in my settings.py. this error first came up after starting my Django project and installing my Django app. The error: > Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\config.py", line 211, in create mod = import_module(mod_path) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked … -
what technology to use to make a chatapp?
what technologies would be best to add a chat app to your website? Like, I see a live customer support chat box on many websites. I think php and ajax are a common way of doing it. I also think django could be commonly used. However, I was wondering if there's a better or "best" way to do this sort of thing? Such as using javascript like next.js, reactjs, and preactjs. There's twilio and plivo. What's a modern and like high quality approach to accomplish adding a live chat pop-up window to a website? My other related inquiry is what to use for creating a website like omegle or a random chat website? -
How to properly connect models in Django?
In my project I want to have global database of ingredients. I also want for each User to have a possibility to add a ingredient to his own Fridge model but with additional field "numOf". I've stumbled upon errors with PATCH request and im thinking that my database is wrongly connected. Does anyone maybe have a better idea how to arrange my models? Ingredient models class Ingredient(models.Model): name = models.CharField(max_length=100) class UserIngredient(models.Model): ingredient = models.OneToOneField(Ingredient, unique=True, on_delete=models.CASCADE) numOf = models.IntegerField(default=1) Fridge model class Fridge(models.Model): owner = models.OneToOneField(User, related_name='fridge', on_delete=models.CASCADE) ingredients = models.ManyToManyField(UserIngredient, blank=True) def __str__(self): return self.owner.username + "'s Fridge" def save(self, *args, **kwargs): super().save(*args, **kwargs) For example, let 1st user have 2 Apples, 2nd 3 Apples and 3rd 4 Apples in their Fridge. Then in UserIngredient table I have 3 records: Apple 2, Apple 3, Apple 4 which all point to a single Apple Ingredient. How can I avoid this redundancy and just point to a Ingredient instance? -
GDAL path issues in macOSX High Sierra
Had GDAL installed and working on my machine (macOS running 10.13.6) for a Django project running python 3.6.5. Didn't have any issues for 2+ years and haven't changed anything (to my knowledge), but now running into an issue when I try to execute a manage.py command where it will err out with OSError: dlopen(libgdal.so, 6): image not found Trace: Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/options.py", line 214, … -
How to integrate any company SSO to my Django app?
I have an app for businesses and one of their main requests is to integrate their SSO (some uses Okta, others use Azure). Currently we use python-social-core, but to add a new company we have to modify code. Do you know a better and simpler way to do this? Like a library that allows me to generate the SAML2.0 url or the redirect link of OIDC, without messing with ENV variables on my app. -
Django form not saving to database via ModelForm
I am trying to add my form to the database using the ModelForm but it's not going through or even printing the form in the view, i have also tried doing each field alone in the view via cleaned data still nothing inserted in the database my view.py def index(request): component = Component.objects.all() form = ComponentModelForm() if request == 'POST': form = ComponentModelForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('/maintenance') else: form = ComponentModelForm() context = { 'components': component, 'form':ComponentModelForm(), } return render(request, 'maintenance/index.html', context) models.py class Component(MPTTModel): name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.CharField(max_length=255) price = models.IntegerField() note = models.TextField() parent = TreeForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return f"{self.id}, {self.name}" forms.py class ComponentModelForm(forms.ModelForm): class Meta: model = Component fields = ("name", "manufacturer", "model", "serial_number", "price", "note", "parent",) the template: <div> <form method='POST' action=''> {% csrf_token %} {{form.as_p}} <input type="submit" value='Create'/> </form> </div> -
How to correctly design a django database?
I have been learning Django recently, before, I used to design the ER models and all that stuff by myself, although I'm not an expert on databases. I have some questions that I couldn't find anywhere. In terms of designing the database, does a Django developer use only the UML diagrams related to the models or does he/she designs the ER models and then the tables? If the developer only uses the UML diagrams, is database normalization necessary or even applicable in this case? In my ignorance I opted to design the models as UML because I like to have diagrams and it seemed appropriate to me. Is this the right approach? UML diagram of django models Thank you. -
my Django website style broken after upload on shared hosting
My site can't locating where it's static and media file after upload on shared hosting. Here is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/project32/rootfolder/media/' STATIC_ROOT = '/home/project32/rootfolder/static/' ** root urls.py** urlpatterns = [ path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) where I am doing mistake? why my web site not location the static folder of my shared hosing ? I also run python manage.py collectstatic -
How can I stream a local video in a Django view, in loop?
I am streaming a local video in a Django Response using StreamingHttpResponse and this code, but I am not sure how can I loop the video so it replays after finishing. -
Django APIView data format from AJAX
I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format: const data = { group_designation: [ {id: 1}, {id: 2}, {id: 3}, ] } I run an insomnia app and it only accepts this kind of format: { "group_designation": [ {"id": 1}, {"id": 2}, ] } However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab: group_designation[0][id]: 1 group_designation[1][id]: 2 group_designation[2][id]: 3 In Django, this is the request.data result: <QueryDict: { 'group_designation[0][id]': ['1'], 'group_designation[1][id]': ['2'], 'group_designation[2][id]': ['3'] }> My code in Django: def post(self, request): temp_objects = [] new_data_format = {'group_designation': temp_objects} serializer = GroupSerializer(data=new_data_format, many=True) if serializer.is_valid(raise_exception=True): group_data_saved = serializer.save() return Response({ "success": "success!!!" }) I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you! -
Use pipenv with django heroku
So I began to code a project with python, and I was using a tutorial that told me to use a pip environment as my virtual environment. A problem arose, however, when I performed the git push heroku master command. It could not find the package django-heroku! I was confused, because when I ran python manage.py runserver, the server on my computer ran. I later realized that the problem was that the pip environment was located in a .virtualenvs folder that was outside of the folder I was pushing to heroku. I then changed to a python environment, which was located in the directory I was pushing to heroku. The problem was solved! The virtual environment, and consequently the installed packages, were inside the directory being pushed to git, and I could use them in my website! But the question still remains: can you use a pip environment for a django project being pushed to git? Thanks! -
How to display error when using is_active for Login
I set a user.is_active to false so they can't login. user.is_active=False user.save() I would like to override the login section to show that the account has been disabled. Currently it shows on disabled accounts. Please enter a correct username and password. Note that both fields may be case-sensitive. I am using the auth login path('accounts/', include('django.contrib.auth.urls')), with a simple template {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Log In</h2> <form method="POST" action="."enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> <button><a href="{% url 'signup' %}">Sign up</a></button> </form> {% endblock %} -
Manager isn't available; 'auth.User' has been swapped for 'reg.User'
I can't seem to find a solution for the error I'm getting when trying to save a user. I wish to save different users. I have searched for previuosly answered questions with the similar problems, and have tried to use get_user_model but the error still clings. Kindly Check my code and guide to the solution. Manager isn't available; 'auth.User' has been swapped for 'reg.User' Here is my Models file from enum import unique from django.db import models from django.db.models.fields import DateField from django.db.models.fields.related import OneToOneField from django.urls import reverse from django.contrib.auth.models import AbstractUser, BaseUserManager, PermissionsMixin import datetime import os from django.db.models.deletion import CASCADE, SET_NULL class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Email Address Required') email = self.normalize_email(email) user = self.model(username=username, email=email, password=password) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): is_agent = models.BooleanField(default=False) is_coordinator = models.BooleanField(default=False) is_regional_director = models.BooleanField(default=False) is_national_director = models.BooleanField(default=False) objects = CustomUserManager() class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() #Views from django.shortcuts import render,redirect from django.http import HttpResponse from django.views.generic import CreateView … -
How to prevent Django save action to avoid repetitive DB calls on already existing data
My current code for saving articles saves new articles and prints 'The Post Already Exists!' if a duplicate is found, but it's still making DB calls and so now I have ID gaps in my articles table because of the false saves caused by duplicate articles not being saved. How can I improve my code to prevent the save action if a duplicate is found to preserve consistency in my article IDs? if not Posts.objects.filter(title=post_title, slug=post_slug).exists(): post = Posts( title = post_title, link = post_link, summary = post_summary, image_url = image_link, slug = post_slug, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_link = channel_feed_link, feed_description = channel_feed_desc, source_id = selected_source_id, category_id = selected_category_id ) post.save() for i in range(len(article_list)): post_tags = post.tags.add(article_list[i]) else: print("The Post Already Exists! Skipping...") I keeping getting such errors: django.db.utils.IntegrityError: duplicate key value violates unique constraint "Posts_posts_slug_key" DETAIL: Key (slug)=() already exists.