Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sorting by a category and pagination combining both in one function view
I'm trying to sort my projects by categories: all, css, HTML, Django, and so on. and also trying to add pagination when showing all projects have a limit of 6 projects per page. I'm stuck and have trouble combining either the pagination work or the filter/ sorting the items work, here's my code. Please Help :) models.py class Category (models.Model): category_name = models.CharField(max_length=150) slug = models.SlugField(unique=True) class Meta: ordering = ('-category_name',) def __str__(self): return self.category_name def get_absolute_url(self): return reverse('mainpages:project_by_category', args=[self.slug]) class Project(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True) title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) proj_url = models.URLField(max_length=200, blank=True) blog_link = models.URLField(max_length=200, blank=True) image = models.ImageField(default='post-img.jpg', upload_to='proj-img') class Meta: ordering = ('-title',) def __str__(self): return self.title view.py def portfolioView(request, category_slug=None): # added category = None categories = Category.objects.all() # filtering by project projs = Project.objects.all() # paginator added projects = Project.objects.all() paginator = Paginator(projects, 3) page = request.GET.get('page') try: projects = paginator.page(page) except PageNotAnInteger: projects = paginator.page(1) except EmptyPage: projects = paginator.page(paginator.num_pages) # added if category_slug: category = get_object_or_404(Category, slug=category_slug) projs = projs.filter(category=category) # return render(request, 'mainpages/portfolio.html', { 'category': category, 'categories': categories, 'projects': projects, 'page': page, 'projs': projs, }) def projectDetail(request, pk): project = Project.objects.get(pk=pk) context = { … -
Passing variables in django browser string
I am doing a search on the page with the ability to filter. It is necessary to pass the selected fields to form the correct queryset. What is the best way to do this? I am creating str variable in urls. But what if you need to pass 10 or more filter conditions? how to organize dynamically passed variables? urls from django.urls import path from .views import * urlpatterns = [ path('', OrdersHomeView.as_view(), name='orders_home'), path('filter/<str:tag>', OrdersFilterView.as_view(), name='orders_filter'), ] I understand what to do through ?var=&var2=, as in php, but I can't figure out how? it is possible to just process the string str, but maybe there is some django magic? -
Context value for the variable {{ media }} in django views
There is a {{ media }} variable used in some of the django admin templates. delete_confirmation.html, change_form.html , and delete_selected_confirmation.html . This variable adds several javascript files including jQuery library to the templates. I want to know what is the value passed to the context variable in the views that call those templates. My purpose is to use the same javascript files in the templates that I create for the custom views in the django admin. Thank you. -
DJANGO : error updating cart shipping cost
Thankyou to everyone that has helped to date. I have completed my project and built a functioning ecom cart. I still have one error, when updating the checkout values the cart adds the shipping cost twice for each line item rather than based on total cart items. That is, if there are three widgets only it will charge 9.95 but if there 3 widgest and 1 watzet the shipping is charged at 19.90(i.e. 2 line items and 2 x 9.95) PLEASE HELP!! The code is below: MODELS.PY from django.db import models from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) short_desc = models.CharField(max_length=255) long_desc = RichTextField(blank=True, null=True) product_image = models.ImageField(null=True, blank=True, upload_to ="images/") product_image_2 = models.ImageField(null=True, blank=True, upload_to ="images/") product_image_3 = models.ImageField(null=True, blank=True, upload_to ="images/") red_hot_special = models.BooleanField(default=False) feature_product = models.BooleanField(default=False) weekly_special = models.BooleanField(default=False) tax_exempt = models.BooleanField(default=False) options_sched = [ ('1', 'exempt'), ('2', 'two'), ('3', 'three'), ('4', 'four'), ] schedule = models.CharField(max_length = 10,choices = options_sched,default='1') def … -
Serializer not working correctly when trying to incorporate username of user
I have a serializer, I'm trying to add an additional field, from a different model. The goal is to add the username from the user who requested the data. Here is my serializer, I try to accomplish my goal using the username variable and adding it to fields. class BucketListSerializer(serializers.ModelSerializer, EagerLoadingMixin): stock_count = serializers.SerializerMethodField() username = serializers.CharField(source='User.username', read_only=True) model = Bucket fields = ('id','username','category','name','stock_count', 'stock_list','owner','admin_user', 'guest_user','about','created','slug', 'bucket_return', 'bucket_sectors','bucket_pos_neg') def get_stock_count(self, obj): if obj.stock_count: return obj.stock_count return 0 There aren't any syntax errors with this serializer, however the username field is not working. There is no data in the dictionary returned with the key username User model: class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, last_name, password, **other_fields) def create_user(self, email, username, first_name, last_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) if not username: raise ValueError(_('You must provide a username')) if not first_name: raise ValueError(_('You must provide your first name')) if not last_name: raise ValueError(_('You must provide your … -
Django - Passing a variable to class based views
In a function based view I can pass on a variable like so: def zip(request): check_for_zipcode = request.user.profile.location zipcodes = { 'check_for_zipcode' : check_for_zipcode } return render(request, 'front/post_form.html', zipcodes) Then I'll be able to access check_for_zipcode in my HTML. But how would I do that in a class based view? Let's say I have the following class based view. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'post_image', 'title2', 'content2', 'post_image2'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) How would I pass on check_for_zipcode = request.user.profile.location in to that class based view? -
what changes are required in VS COde And Django for the following script of python?
Actually I am working on the python script in VS Code by using django framework. I am using phpMyAdmin this is the script. ''' dates=str(datetime.datetime.now().date()) #dates1=str((datetime.datetime.now()-datetime.timedelta(days=1)).date()) f1=open('let\hhh\html\WB/'+dates+'.csv','w') f1.write('ID, Name, add, p, c) db = MySQLdb.connect("localhost","user","","meta") cursor = db.cursor() sql = "select ID from meta where ........ cursor.execute(sql) results=cursor.fetchall() ''' what changes required in VS Code and Django to implement the script? What to write in models? I am using phpMyAdmin -
How to use base_template variable in Django login.html
I have a very simple Django 3.1 project that uses the basic login-authentication found in the Mozilla tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication). It works great, but I'd like to change the extends base_generic line to a variable. For example, logged_out.html, currently looks like this: {% extends "base_generic.html" %} {% block content %} <p>Logged out!</p> <a href="{% url 'login'%}">Click here to login again.</a> {% endblock %} I'd like it to look like this: {% extends base_template %} <-- Here's the change I'd like to make {% block content %} <p>Logged out!</p> <a href="{% url 'login'%}">Click here to login again.</a> {% endblock %} I've been able to do this successfully for all the templates that I create, but I can't figure out how to do this for the "built-in" login-authentication pages, such as login.html, logged_out.html, password_reset_form.html, etc Thank you! -
How do you properly protect a multitenancy model from the tenants in Django (using django-schemas)?
I'm kind of at a loss here. I'm setting up a multi-tenant project for practice with Django and I decided to use django-tenants because it has the most active Github repo. The problem I've run into has to do with exposing the tenant model to all the tenants. I don't want the tenants to see who the other tenants are. They cannot add, edit or remove any of them but they can see them. I don't want that. What I've tried doing was making two admins (admin and masteradmin) then only registering the tenant model with the master admin. However, if a tenant goes to /masteradmin/ the same problem persists. I figure that django.contrib.admin doesn't know about the tenants and this is why but I'm stuck. What do I do to solve this problem properly? I'm out of resources to read and options to try. Project settings.py apps: SHARED_APPS = ( 'django_tenants', # mandatory, should always be before any django app 'customers', # you must list the app where your tenant model resides in 'website', 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'biller_customers', ) TENANT_APPS = ( 'django.contrib.contenttypes', # your tenant-specific apps 'biller_customers', ) Tenant app models.py file: from … -
How to create or save Data using RestFramework viewsets.?
I created two models that are interlinked with each other. class Company(models.Model): company_name = models.CharField(max_length=50, unique=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company_name class Order_Placement(models.Model): company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True) product_quantity = models.IntegerField() product_price = models.FloatField() product_total_price = models.FloatField(blank=True, null=True) other_cost = models.FloatField() cost_of_sale = models.FloatField(blank=True, null=True) advance_payment = models.FloatField() remaining_payment = models.FloatField(default=0.0, blank=True) date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.product_total_price = self.product_price * self.product_quantity self.cost_of_sale = self.product_total_price + self.other_cost self.remaining_payment = self.cost_of_sale - self.advance_payment super(Order_Placement, self).save(*args, *kwargs) def __str__(self): return str(self.company) + ' : ' + str(self.date.date()) I am trying to create a view that will help me to create an object or instant of the Order_placemen model But when I try to post Data it rises an error while saving with post request: Here I created a serializer for both company and Order_placement class CompanySerializer(s.ModelSerializer): class Meta: model = m.Company fields = '__all__' class Order_PlacementSerializer(s.ModelSerializer): class Meta: model = m.Order_Placement fields = '__all__' def to_representation(self, instance): response = super().to_representation(instance) response['company'] = CompanySerializer(instance.company).data return response and I created a view for OrderPlacement using Django rest_framework.viewsets.ViewSet class OrderProccessViewset(viewsets.ViewSet): def create(self, request): try: serializer = s.Order_PlacementSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Order Save Successfully"} except: dict_response … -
Configuring CSRF tokens with apollo client and graphene-django
I am having trouble properly setting up csrf tokens in the authlink header. const authLink = setContext((_, { headers }) => { const token = localStorage.getItem(AUTH_TOKEN) return { "headers": { 'X-CSRFToken' : getCookie('csrftoken'), "Authorization": token ? `JWT ${token}` : '', ...headers, }, }; }); The request being sent looks ok from the browser devtools, as you can see at the bottom the csrf token looks right? I cleared my browser data to make sure it wasn't old, but I'm not sure if that's effective anyways. accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization Connection: keep-alive Content-Length: 505 content-type: application/json Host: localhost:8000 Origin: http://localhost:3000 Referer: http://localhost:3000/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63 X-CSRFToken: LsV83sz3Rb5RRIlNcRN3AgnniodwsSMpvXwMGquPGRbvoPpISfKv6MBEf86rVzVp The error I get through the site is CSRF verification failed. Request aborted my django server shows Forbidden (CSRF cookie not set.) -
Learning Backend Development
I am looking to create a courses website similar to https://brilliant.org/courses/ which allows users to create accounts and register for premade courses. I would like for each student to have their own dashboard which displays various statistics like how much time they spent on a course and what courses they are enrolled in. This is for a nonprofit organization aimed at elementary through early high school students. Currently, I know the very basics of frontend development (HTML, CSS, JS) and some python however I am unsure where to start to learn backend development to actually create user accounts and courses. Since I am learning python on the side I would prefer to use Django, where is a good place to start for someone with absolutely no prior computer science or web dev experience? -
Django __iregex crashing for regular expression ^(\\. \\.)$
When I try to make an __iregex call using the regular expression '^(\\. \\.)$' I get: DataError: invalid regular expression: parentheses () not balanced I am using PSQL backend so the django documentation states that the equivalent SQL command should be SELECT ... WHERE title ~* '^(\\. \\.)$'; When I run this query manually through the PSQL command line it works fine. Is there some bug with Django that I don't know about that is causing this to crash? -
When I am trying to add an object or update any objects, Django gives null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, pbkdf2_sha256$150000$nZ78tMu3I9nQ$auiF+N/RUqIHgVBMUL6kjAX8zjPPyc..., null, f, dude, , , , f, t, 2021-03-31 19:16:57.392614+00). enter image description here -
Exception Value TodoList matching query does not exist
I am using SQLite as backend db for django application. I have one table in the DB called TodoList having around 101 records. When I am triggering delete action from HTML, entries between id 1-9 are getting deleted, however, ids more than 9 having no effect. If i try to delete 101th entry i am getting the following error in the browser. Is there any limit with django or sqlite on number of database table records? DoesNotExist at / TodoList matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:7000/ Django Version: 3.0.13 Exception Type: DoesNotExist Exception Value: TodoList matching query does not exist. Exception Location: C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\db\models\query.py in get, line 415 Python Executable: C:\My_Data\Rapid\.venv\py3.9.0\Scripts\python.exe Python Version: 3.9.0 Python Path: ['C:\\My_Data\\Rapid\\Experiences\\Coding\\Python\\Hands-On\\00.django_hands_on\\todoapp', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0\\Scripts\\python39.zip', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0\\lib\\site-packages', 'C:\\Users\\ramesh.petla\\AppData\\Roaming\\Python\\Python39\\site-packages', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\lib\\site-packages'] Server time: Wed, 31 Mar 2021 19:30:22 +0000 Environment: Request Method: POST Request URL: http://127.0.0.1:7000/ Django Version: 3.0.13 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = … -
Create Table in Python-docx with Merge and Split functionality
Currently I am working on the project in which I am taking number of rows and column at frontend and Inserting data into it and sending JSON at backend. Tables have Merge and Split functionality How to create table on python docx enter image description here for example : enter image description here -
Django-Heroku: Data in models not persistent
I have deployed a web app with Heroku and developed using Django. Problem: Every time the app goes to sleep, and when it wakes up, objects in the Django models get reset to their original state (empty model). I am not entirely sure what is the problem I am facing here. What I suspect: db.sqlite3 file does not get updated when I make any changes. App resets to original state after waking up from sleep. Procfile gets run again. What have I tried: Searching Google for any leads on what might be the problem. Updating model locally before redeploying on Heroku. -
cv2.cvtColor mysteriously kills python worker without throwing exception
I'm getting very mysterious behavior when trying to run some basic functions in a python worker (using Django RQ). I am using a function (nested deep 8 to 10 stack frames in from the viewset's route) that results in the following error: "Work-horse was terminated unexpectedly (waitpid returned 11)" The image itself is an ordinary image with 1000 by 700 pixel with 3 channels. I'm not sure why this method is throwing this strange error in the code (cv2.cvtColor() I know this because I stepped through it and it ends at the same spot every time), and not even generating any kind of exception. There is a BaseException clause that attempts to catch this, but it fails, the worker just deems the job as having failed and moves it to the FailedJobRegistry and exits the entire stack frame. I attempted to increase my environment's memory that the worker is running in (PyCharm) to 5GB, but it still results in this error. Then I reinstalled opencv-contrib-python and it failed. My team needs to use the opencv-contrib-python repository because we make use of SIFT. How can I diagnose what this obtuse error message means? I can't see anything in the logs that … -
Concat Nested Dictionary value to string
Would like to convert dictionary_list = { hello_world = { 'Hello': 'World' }, myName = { 'Im': 'Harry' } } to Hello world Im Harry I am looping through the nested dictionary by using the following for loop: for key, value in dictionary_list.items(): Just need to concat value into an empty string. -
Trying to execute django-admin makemessages in windows 10
I´m trying to generate translation file using command django-admin makemessages -l pt-br in Windows 10 but unfortunately the files aren´t generated. Here the steps that I followed: Installed gettext library from mlocati. I also tried several options from django i18n: Make sure you have GNU gettext tools , this process is more manual. As the result when i run django-admin makemessages -l pt-br looks like that Django is executing something but the directory is not generated in the end. Here are some peace of code that I have views.py from django.shortcuts import render from django.utils.translation import gettext as _ def index(request): context = { 'hello': _('Hello!') } return render(request, 'index.html', context) settings.py """ Django settings for translation_example project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3^*d$5b7$r2$t-0cxmef22l5_)t^cn9i-xkq48zen$u*67)tvm' # SECURITY WARNING: don't run with debug turned on in … -
Start Django modelformset with values from instances?
This question asks about initializing a Django model formset with instances. The answer is: use the queryset argument. But what if I want a new formset with a copy? That is, all the values of those instances, but not the instances themselves (i.e., they'll be extra and not yet bound). My current solution is to make the call to formset partial (so I can fill in "extra"), and copy over all the values. I don't love this, because if we add fields to Item, then we have to go and add those fields to the copy. Is there a better way? import functools PartialItemFormset = functools.partial( forms.modelformset_factory, Item, formset=BaseItemFormSet, fields=('name', 'description')) EmptyItemFormset = PartialItemFormset(extra=2) the_items = Items.objects.filter(...) copy_formset = PartialItemFormset(extra=len(the_items))( queryset=Item.objects.none(), # TODO: Is there a better way than copying all the fields? initial=[{'name': item.name, 'description': item.description} for item in the_items]) -
forms in Django does not register the data in the database
I'm stuck I try a lot of things to make it work, but always the same problem the form dose note save the data at all and the any error that I get is the message error (what I writ in the message) all i get is a change in the url like this http://127.0.0.1:8000/appointement/create_appointement_2?patient=patient+12&initial-patient=patient+12&doctor=2&date=2021-04-02&start_time=16%3A30 is there anything that can show me the error or if anyone have this problem be for a few hits will be awesome? this is my models .py class Appointment(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointment') patient = models.CharField(null=True,max_length = 200, default=defaultTitle) doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.DateField(null=False, blank=False, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) and this is my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) # patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), input_formats=settings.DATE_INPUT_FORMATS) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'}), input_formats=settings.TIME_INPUT_FORMATS) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') and this is the views.py @login_required def create_appointement_2(request): user = get_user_model() patients = User.objects.filter(type_of_user=TypeOfUser.PATIENT) form_appointment_2 = AppointmentForm_2(request.POST or None) if request.user.is_doctor() or request.user.is_reception(): if request.method=='POST': form_appointment_2 = AppointmentForm_2(request.POST or None) user = get_user_model() if form_appointment_2.is_valid(): form_appointment_2.save(commit=False) form_appointment_2.user_ho_add = request.user # form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) start_time = form_appointment_2.start_time future_time … -
Django HTML page returns the same id object from database
I have a few objects on my database, and my html page should open a new tab with the respective “id’s” when I click on the objects. But when I click on them It opens a new tab always with the “id:1”, even if I click on the second object, it returns me the “id” of the first item, instead of the second one. How can I make it to display the respective ‘id’ of the item when I click on it? Here is the screenshoot of the page Here is the openned tab after I click on the 2nd object, displaying the 'id' of the first object. Here is the HTML code of the page uploaded: https://github.com/khavro21/my_html/blob/main/index.html I can´t find out what is missing on my code, do you have any idea? Thank you! -
Can't migrate after makemigrations on django
everyone. I newbie in this field. So, After I finished makemigrations. then I migrate this error code occurs. I try to solve it but still stuck. please guide, I attach my error code as below. (venv) C:\Users\hp\Desktop\Taskly_App\src>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, house, oauth2_provider, sessions, social_django, task, users Running migrations: Applying task.0002_auto_20210331_2329...Traceback (most recent call last): File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "task_tasklist" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) … -
Django Post Save Signal goes on looping
The below code goes on looping , after processing the value for profile_pic my use case: when the value for profile_pic is passed while saving the model , I need to perform some operations on it and then save it , if the value is null nothing should happen @receiver(post_save,sender=User) def resize_image(sender,instance,created,*args,**kwargs): if instance.profile_pic: ###### doing some operations on profile_pic ###### instance.profile_pic=image_process(image) instance.save()