Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a difference between (eg) 'ListView' and 'generic.ListView'?
Please help clarify some basic concepts. Googling leads to answers about the difference between two different views, eg, ListView vs DetailView, but not where my confusion is: The official Django docs has two import versions: from django.views import generic class IndexView(generic.ListView): And from django.views.generic.detail import DetailView class ArticleListView(ListView): Are the two interchangeable? I have had the following seemingly with no ill effect: from django.views import generic class IndexView(ListView): # insteald of `generic.ListView` -
How to manipulate CharField as a string Django
I have a charfield in which the user inputs a range of numbers which will correspond to a list of numbers. For example the user should be able to input '1, 2, 3, 4, 5' or '1-5', and I want to be able to convert that into a list of all those numbers in the range. When I grab the field's cleaned_data in the views.py, however, the value does not behave like a string. The .split() does not convert to a list, and the for loop loops through individual characters. How can I convert the field into a usable string? In the views.py: def my_view(request): if request.method == 'POST': if form.is_valid(): nums = form.cleaned_data['numbers'] nums.split(',') num_list = [] for item in nums: if '-' in item: item.split('-') for x in range(item[0], item[1]): num_list.append(x) else: num_list.append(item) If the input is '1-160', I get an error because the single character '-' can't be split into two items and be indexed. The expected num_list is a list of all the integers between 1 and 160. If the input is '1,2,3' num_list is a list of all the characters, not just the numbers. -
How can I implement a checkbox in django from my database
I need to make a project for faculty administration. I made a project that selects 3 tables from my database. I have 3 ModelChoiceField and a submit button on my page. When I click submit I need to be redirected to a new page that has a list of checkboxes that are related to my choices from the 3 choiice fields. models.py: class An(models.Model): an_studiu = models.SmallIntegerField(primary_key=True) class Meta: managed = False db_table = 'an' def __str__(self): strAni = ["0", "I", "II", "III", "IV", ] return strAni[self.an_studiu] class Disciplina(models.Model): id = models.CharField(primary_key=True, max_length=256) denumire = models.CharField(max_length=256, blank=True, null=True) an_studiu = models.ForeignKey(An, models.DO_NOTHING, db_column='an_studiu', blank=True, null=True) id_program_studii = models.ForeignKey('ProgramStudii', models.DO_NOTHING, db_column='id_program_studii', blank=True, null=True) pondere_evaluare = models.FloatField(blank=True, null=True) nr_lucrari = models.IntegerField(blank=True, null=True) nr_teme = models.IntegerField(blank=True, null=True) nr_evaluari = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'disciplina' class Incadrare(models.Model): semigrupa = models.ForeignKey('Semigrupa', models.DO_NOTHING, db_column='semigrupa', blank=True, null=True) id_disciplina = models.ForeignKey(Disciplina, models.DO_NOTHING, db_column='id_disciplina', blank=True, null=True) id_profesor = models.ForeignKey('Profesor', models.DO_NOTHING, db_column='id_profesor', blank=True, null=True) class Meta: managed = False db_table = 'incadrare' class ProgramStudii(models.Model): id = models.CharField(primary_key=True, max_length=256) abreviere = models.CharField(max_length=256, blank=True, null=True) denumire = models.CharField(max_length=256, blank=True, null=True) nr_ani_studiu = models.SmallIntegerField(blank=True, null=True) def __str__(self): return self.abreviere class Meta: managed = False db_table = 'program_studii' class … -
how do i delete a file from azure blob based on file path in Django
MODELS.PY class FilesHistory(models.Model): filename = models.CharField(max_length=100, blank=False, null=False) file = models.FileField(upload_to='upload/%y/%m/%d/',null=False,blank=False) sentGroupId = models.CharField(max_length=100,blank=False) uploaded_at = models.DateTimeField(auto_now_add=True,blank=True) def delete(self, using=None, keep_parents=False): self.file.storage.delete(self.file.path) super().delete() this delete function is working for removing files from the media folder based on the file path. -
CustomUser created through Django Admin cannot login (Django Rest Framework)
I created a register/login system through DRF by overriding dj_rest_auth If registering an user with Postman, by firing on the endpoint, that user can be used for login through endpoint However, if creating an user through Django Admin, that user cannot be used for login through endpoint, and notably, if seen through Django Admin, the password is not hashed serializers.py class CustomLoginSerializer(LoginSerializer): def validate_auth_user_status(self, user): request = self.context.get('request') if not request.data.get('role'): msg = 'Role is missing from the payload.' raise exceptions.ValidationError(msg) if not user.groups.filter(name=request.data.get('role')).exists(): msg = 'Invalid role for the user.' raise exceptions.ValidationError(msg) def create(self, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def update(self, instance, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway class CustomRegisterSerializer(RegisterSerializer): name = serializers.CharField() def get_cleaned_data(self): super().get_cleaned_data() return { 'email': self.validated_data.get('email', ''), 'password1': self.validated_data.get('password1', ''), 'name': self.validated_data.get('name', '') } def create(self, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def update(self, instance, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def save(self, request): user = … -
creating objects in PostgreSQL and Django
I'm trying to create rows inside my PostgreSQL using scraped data from a website. I'm pretty sure my approach is wrong. here is tasks.py inside one of my Django apps which is supposed to do the scraping and then add the scraped data to db: from models import Movies from bs4 import BeautifulSoup import requests url = 'any url' r = requests.get(url).text soup = BeautifulSoup(r, 'lxml') title = soup.find('a', class_='movie_name') year = soup.find('span', class_='year') rating = soup.find('p', class_='rate') Movies.objects.create( title = 'the movie name', year = 2020, rating = 8.7) and this is my models.py : class Movies(models.Model): title = models.CharField(max_length=20) year = models.IntegerField(max_length=4) rating = models.FloatField(max_length=10) What's the best way to scrape data and add it automatically to the database? -
Image Render Problems [Pillow]
I'am trying to make image resize service with Pillow.The images saved in the cache folder look completely correct. But when I look at the browser, there is a small white box instead of resized image. http://127.0.0.1:8000/media/images/Test_image.jpg it look like https://prnt.sc/12sy9it Here is my code. from io import BytesIO import requests from PIL import Image from django.http import HttpResponse from django.conf import settings def image_downloader(url): filename = url.split("/")[-1] response = requests.get(url) print(response.headers) if response.status_code == 200: print('Image sucessfully Downloaded: ', filename) return response.content else: print('Image Couldn\'t be retreived') return None def image_resizer(img_content): img = Image.open(BytesIO(img_content)) img.thumbnail((960, 640), Image.ANTIALIAS) return img def image_provider(request): _url = 'https://upload.wikimedia.org/wikipedia/en/9/95/Test_image.jpg' _filename = _url.split('/')[-1] image = image_downloader(_url) resized_image = image_resizer(image) print(settings.BASE_DIR + "/cached_files/" + _filename) print(resized_image.get_format_mimetype()) resized_image.save(settings.BASE_DIR + "/cached_files/" + _filename, optimize=True, quality=60) # resized_image.seek(0) response = HttpResponse(resized_image, content_type='image/jpeg') return response -
How to login with both phone and email in this Django program?
I want to login with both email and phone . Currently Iam able to login using phone , I need to login with email also .I am using CustomUser.Please let me know in the comments if anymore details are needed,I am not sure about this method , please suggest correct method if this is wrong. class loginn(TemplateView): model = CustomUser form_class = LoginForm template_name = "../templates/Customer/loginn.html" context = {} def get(self, request, *args, **kwargs): self.context['form'] = self.form_class return render(request, self.template_name, self.context) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) phone = request.POST.get('phone',False) password = request.POST.get('password',False) email = request.POST.get('email',False) try: obj = CustomUser.objects.get(phone=phone) except: obj = CustomUser.objects.get(email=email) user = authenticate(username=obj.username, password=password,backend='Customer.backends.CustomerBackend') if user is not None: login(request, user) if user.is_authenticated: obj1=CustomerProfile.objects.all() if obj1.exists(): for datas in obj1: if request.user==datas.user: return redirect('index') if request.user != datas.user: return redirect('customerprofilecreate') else: return redirect('customerprofilecreate') else: messages.error(request,"Invalid Credentials") return redirect('loginn') -
Cannot use Locust as a library in Django test framework
I want to use Locust as a library in Django's Unittest framework, because I want Django to create a temporary database for me to do the testing. However, I receive the following error: Traceback (most recent call last): File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/PycharmProjects/django_lfs_port/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_manage.py", line 104, in handle failures = TestRunner(test_labels, **options) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_runner.py", line 254, in run_tests return DjangoTeamcityTestRunner(**options).run_tests(test_labels, File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/runner.py", line 695, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/runner.py", line 614, in setup_databases return _setup_databases( File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/test/utils.py", line 170, in setup_databases connection.creation.create_test_db( File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/creation.py", line 57, in create_test_db self.connection.close() File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 285, in close self.validate_thread_sharing() File "/Users/PycharmProjects/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 552, in validate_thread_sharing raise DatabaseError( django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 4487204352 and this is thread id 4528855696. I don't seem to be able to even import Locust, for example, the following test_locust.py, which does nothing, can already reproduce the error: from django.test import TransactionTestCase, override_settings … -
Objects from Listview won't display when using for loop on template - Django
I am trying to display all of the objects from Company, in a Listview by using a for-loop on the template(landingpage.html) but it comes out empty. The tricky part for me is that the Model class (Company) comes from a different directory than where the listview is created. I am importing the Model class (Company) in views.py but it still shows up empty on the template. Any ideas on why this might be? event/views.py from company.models import Company class LatestCompanyView(ListView): model = Company template_name = "event/landingpage.html" event/urls.py from .views import LatestCompanyView urlpatterns = [ path('event/landingpage/', LatestCompanyView.as_view(), name='landingpage'), ] event/landingpage.html </div> {% for Company in company_list %} <h3> {{ Company.description }} </h3> {% empty %} Nothing is here! {% endfor %} </div> company/models.py class Company(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, default = None) description = models.TextField() def __str__(self): return '{} {}'.format(self.user, self.description) -
How to solve "didn't return an HttpResponse object" error?
I have a delete button. I use the same structure in other views and it is working correclty. But in this page it did not work. When I want to delete a comment there is an error: ValueError at /comment/18/analysis/ The view ocr.views.delete_approval_comment didn't return an HttpResponse object. It returned None instead. It deletes the comment but gives this error. How can I solve it? views.py def delete_approval_comment(request,id): comment = CommentFromOthers.objects.get(id=id) comment.delete() redirect('ocr', comment.doc_id.id) ocr.html ... <a href="{% url 'delete_app_comment' comment.id %}" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this?')" > <i class="fa fa-trash" aria-hidden="true"></i> </a> ... urls.py ... url(r'^ocrs/(?P<id>\d+)/analysis/$', views.ocr, name="ocr"), url(r'^comment/(?P<id>\d+)/analysis/$', views.delete_approval_comment, name="delete_app_comment"), ... -
Missing icalendar package in Django app on docker
In my Django project on docker I'm using icalendar package. On the top of the file I have from icalendar import Calendar, Event. When I tried to run my app with command sudo docker-compose up --remove-orphans I have error like this: web_1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import web_1 | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load web_1 | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 680, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 790, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed web_1 | File "/code/greip_app/__init__.py", line 28, in <module> web_1 | from icalendar import Calendar, Event web_1 | ModuleNotFoundError: No module named 'icalendar' When I want to use pip install icalendar I have this message: Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: icalendar in /home/mnruser/.local/lib/python3.9/site-packages (4.0.7) Requirement already satisfied: pytz in /usr/lib/python3.9/site-packages (from icalendar) (2020.5) Requirement already satisfied: python-dateutil in /usr/lib/python3.9/site-packages (from icalendar) (2.8.1) Requirement already satisfied: six>=1.5 in /usr/lib/python3.9/site-packages (from python-dateutil->icalendar) (1.15.0) I tired to add icalendar to my requirements.txt file like this: Django>=3.0,<4.0 sycopg2-binary>=2.8 icalendar but the error is still the same. When I try to use icalendar … -
Can i divide view in django like that?
Can i divide view in django like that? And do i need additional urls in my urls.py? def profile(request): if(option) return view1(request) else return view2(request) -
Django invitations giving error This chandansblog.pythonanywhere.com page can’t be foundThis page may have been moved or deleted. HTTP ERROR 410
I have setup my django app on pythonanywhere.com I have installed django-invitations module and I am able to create my invitations from admin backend. The problem is when I recieve my mail and the link to my site, I get the following error: This chandansblog.pythonanywhere.com page can’t be foundThis page may have been moved or deleted. HTTP ERROR 410 It was working prior to changing my sitename to example.com When I changed my site name to chandansblog.pythonanywhere.com - the link stopped working. What is the problem? -
Do we need to add files (in the folder) that White Noise creates to the gitignore list?
I have a django project and using whitenoise for static files serving. When we run py manage.py collectstatic whitenoise, that create lot of files in selected folder in STATIC_ROOT object of settings.py file. It takes up a lot of volume. Do I have to add the folder name I specified in settings.py(STATIC_ROOT) to the gitignore list? Is this true and safe? And it does not make a problem? -
Django AWS-S3 cant start new thread
I set up the project based on here. Everything works fine but whenever I want to upload a larger file (more than 50Mb) using Django admin this error occurs: File "/opt/alt/python37/lib64/python3.7/concurrent/futures/thread.py" in submit 172. self._adjust_thread_count() File "/opt/alt/python37/lib64/python3.7/concurrent/futures/thread.py" in _adjust_thread_count 193. t.start() File "/opt/alt/python37/lib64/python3.7/threading.py" in start 852. _start_new_thread(self._bootstrap, ()) Exception Value: can't start new thread The server is working fine and the resources are enough. On the localhost everything is OK and there is no error. -
URL append with previous URL
In one app (name: loginsystem) I have urlpatterns = [ path('logout/', views.UserLogoutView.as_view(), name='logout'), path('profile/', views.ProfileView.as_view(), name='profile'), path('login/', views.UserLoginView.as_view(), name='login'), path('password_change/', views.UserPasswordChangeView.as_view(), name='password_change'), path('password_reset/', views.UserPasswordResetView.as_view(), name='password_reset'), path('password_reset_done/', views.UserPasswordResetDoneView.as_view(), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', views.UserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password-reset-complete/', auth_view.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] In the other app of urls file I was trying to include these urls and wrote this line path('accounts/', include('loginsystem.urls')), but when i'm trying to access login url from html its append with previous url like this http://127.0.0.1:8000/#/accounts/login/ its add # sign before the url my html <a href="#{% url 'login' %}" class="btn btn-warning">Login</a> this html not in loginsystem app this is in other app -
Django cannot patch in json
Hi I have a model with FileField. I can POST request and fill the field of course using multipart. However, I also have some fields which are non-file for ex. BooleanField. I cannot patch non-file fields when I am using format='json', it needs to be 'multipart' too. How do I enable patch for non-file using json? and Why I am having the error below? class Foo(models.Model): is_published = models.BooleanField(default=False) file = models.FileField(...) class FooSerializer(serializers.ModelSerializer): is_published = serializers.BooleanField( required=False) file = serializers.FileField( use_url=True, required=False) def partial_update(self, request, pk=None): data = request.data.copy() serializer = FooSerializer( pk, data=data, partial=True, ) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) response = self.client.patch( '/apps/foo/1/', data={'is_published': True}, format='json') response: {'detail': 'Unsupported media type "application/json; charset=None" in request.'} -
Django form changing required field depending on another field
I have a django form InstellingenForm that has a few input fields. All should be required. But depending on the input of "spelmodus", either "tijd" or "woorden" should turn to required=False. (if "tijd" is selected in "spelmodus", the "woorden" form should change to required=False and vice versa) I tried to do this with a clean() function, but I can't seem to figure out how to exactly do this. from django import forms SPELMODUS = [ ("", ""), ('tijd', 'Tijd'), ('woorden', 'Woorden'), ] TIJD = [ ("", ""), ('een', '1 minuut'), ('twee', '2 minuten'), ('vijf', '5 minuten'), ] WOORDEN = [ ("", ""), ('vijftig', '50 woorden'), ('honderd', '100 woorden'), ('honderdvijftig', '150 woorden'), ] TALEN = [ ("", ""), ('nederlands', 'Nederlands'), ('engels', 'Engels'), ] MOEILIJKHEID = [ ("", ""), ('makkelijk', 'Makkelijk'), ('gemiddeld', 'Gemiddeld'), ('moeilijk', 'Moeilijk'), ] class InstellingenForm(forms.Form): naam = forms.CharField(label="Naam", max_length=10, required=True, widget=forms.TextInput(attrs={'class': 'input-container'})) spelmodus = forms.ChoiceField(label="Spelmodus", choices=SPELMODUS, required=True, widget=forms.Select(attrs={'class': 'input-container', 'id': 'spelmodus', 'onchange': 'hideShow(this.value)', })) tijd = forms.ChoiceField(label="", choices=TIJD, widget=forms.Select(attrs={'class': 'input-container', 'id': 'tijdClass'})) woorden = forms.ChoiceField(label="", choices=WOORDEN, widget=forms.Select(attrs={'class': 'input-container', 'id': 'woordenClass'})) taal = forms.ChoiceField(label="Taal", choices=TALEN, required=True, widget=forms.Select(attrs={'class': 'input-container'})) moeilijkheid = forms.ChoiceField(label="Moeilijkheid", choices=MOEILIJKHEID, required=True, widget=forms.Select(attrs={'class': 'input-container'})) def clean(self): if self.data.get('spelmodus', 'tijd'): self.fields['woorden'].required = False elif self.data.get('spelmodus', 'woorden'): self.fields['tijd'].required = False super(InstellingenForm, … -
How do I know what functions are run in Generic Views?
I am new to Django and scratching my head with the following question how do I know which function is run in specific processes? for example in below view, retrieve function is executed. I flipped the documentation, however, could not find anything named retrieve to overwrite class ProfileRetrieveAPIView(RetrieveAPIView): serializer_class = ProfileSerializer def retrieve(self, request, username, *args, **kwargs): print("hey yo i am running 01") try: profile = Profile.objects.select_related('user').get( user__username=username ) except Profile.DoesNotExist: raise serializer = self.serializer_class(profile) return Response(serializer.data) -
'QuerySet' object has no attribute 'pk' , how I can get the Id of the post from home view?
How I can get the pk of objects in home view, I try to make personal blog with posts and this posts include comments, I tried to get the post pk in order to get the comments that related to this post but I failed Firstly I tried to get th pk by add it in def home_view(request, pk) but this template in home page www.mywebsite.com that's mean as I know, I cann't pass pk to the url so that's failed with me My qustion is how I can get the Id of the post from home view? My home View post = [] for u in users: p = Account.objects.get(username=u) posts = p.post_set.all() post.append(posts) if len(video): video = sorted(chain(*video), reverse=True, key=lambda video: video.created_date) # here I tried to get the pk comma = Post.objects.all() our_post = Post.objects.get(pk=comma.pk) comment = PostCommentIDF.objects.filter(post=our_post) My Post Model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) My Comment Model class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) The Home View Url path('', home_screen_view, name='home'), -
Django: How to group queryset by timestamp
I have these two models class Blog(models.Model): title = models.CharField(unique=True, max_length=255) class Tag(models.Model): blog = models.ForeignKey(Blog) tag = models.CharField(max_length=255) timestamp = models.DateTimeField(db_index=True) class Meta: constraints = [ models.UniqueConstraint( fields=["blog_id", "timestamp"], name="Timestamp per blog must be unique"), ] Let's say the IDs of some of the blog is [1,2,3,4,5] I want to query and group the tags in such a way that the results is grouped by timestamp. an example output will be like [ {'timestamp': '2021-04-13 15:35:26+00:00', [title_of_blog_id_1]: "hello", 'tag': 'Hello', [title_of_blog_id_2]: "new title", 'tag': 'new'} {'timestamp': '2021-04-13 15:55:26+00:00', [title_of_blog_id_1]: "hello next", 'tag': 'next', [title_of_blog_id_2]: "new updated title", 'tag': 'UP'} ] Explanation of the output: I want a situation in which the Tags are grouped by the timestamp and for each timestamp, it fetches all the blog title and corresponding tag for that timestamp. -
How can I bring the django filters for filtering and searching in a APIView instead of ListAPIView?
Given below was a code written in ListAPIview and now I have to change it to APIView. How can I bring the search, filtering and ordering in this? Please let me know in the comments if any more details are needed. Thanks in advance. class DiscussionView(APIView): pagination_class = DiscussionPagination filter_backends = [OrderingFilter, SearchFilter] search_fields = ['title'] ordering_fields = ['id'] def get(self, request, format=None): query = Discussion.objects.all() serializer = DiscussionSerializer(query, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = DiscussionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django annotation queryset for Sum of datetime
i have a model below class UserAttemptQuiz(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz_user') quiz = models.ForeignKey(QuizMcqDetail, on_delete=models.CASCADE, related_name='quiz_detail') start_time = models.DateTimeField() end_time = models.DateTimeField() language = models.ForeignKey(QuizLanguage, on_delete=models.SET_NULL, null=True) score_count = models.PositiveIntegerField() now i wants to sort the users with their time taken to attempt a quiz so i wrote a code by using annotaion function day_ranking_obj = UserAttemptQuiz.objects.filter().values('user').annotate(score=Sum("score_count"),time_taken=Sum( 'start_time') - Sum('end_time')).order_by('time_taken') but i am getting an error below: function sum(timestamp with time zone) does not exist\nLINE 1: ...quiz_userattemptquiz\".\"score_count\") AS \"score\", (SUM(\"quiz_...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\n -
Django Unknown column 'table_name.fieldname_id' in 'field list'
I'm in production mode and using Django==3.1.5 and MySQL and trying to find a way to add a field named author to a model named news without the need to delete the whole database and recreate it. This is the news model and the field: from account.models import User class News(models.Model): ... # The user database is a custom user I've defiend author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='auth_news') Finally, every time I restart the gunicorn service, I end up facing this error: I've tried so many ways to fix this error but no luck! Some of them are: ❌ Deleting the migrations folder, login to MYSQL and DELETE FROM django_migrations; ,then makemigrations and migrate the News model ❌ Facing with a deprecated package named South ❌ using python manage.py migrate news --fake ❌ using python manage.py migrate news zero --fake then remigrate ❌ using python manage.py migrate --run-syncdb --fake ❌ Make initial migrations with --fake-initial When I tried these jobs, all of them worked but none of them added the column author to the news_news table strangely! Then I tried to add it manually: Run python manage.py sqlmigrate news 0001 logging in to the SQL database with command mysql …