Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete the first name and last name columns in django user model?
I created a custom user model just like the docs said, when I ran the makemigrations I went to the folder of migrations and deleted the first name and last name columns inside the 0001_initial.py and then I ran the migrate command, but when I ran the createsuperuser command it throwed an error in the terminal that django.db.utils.OperationalError: no such column: myapp_usermodel.first_name How can I fix this? EDIT: this is the user model from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractUser # Create your models here. class usermodel(AbstractUser): email = models.EmailField(max_length=60) username = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=20) def __str__(self): return self.username -
Django - cooperation of two users
I'm developing a Django web app and have run into the following problem. The idea I have is to allow two users to perform an action together on the certain page - when first one enters the page the "session" is created and the server is waiting for the second user to enter. After 2nd user enters the page, they can perform a certain action together. (Basically they will take turns choosing items from available item pool, so that in the end everyone has his "basket") Could you share any resources on how to achieve this functionality with Django? Any documentation/tutorials/materials/tips what to look for will be useful. I wasn't able to find anything, but I probably don't name the problem properly. -
Access first value in tuple in Django Template HTML
I am creating a website in Django and need to display a value that the user had chosen from a choice field - their user_status which is stored in a tuple. The first and second values are identical, but they can be 'Member' or 'Expert'. At first I tried this in my HTML: {{ user.user_status }} This was the result: ('Member', 'Member') What I wanted was this: Member Next, I tried {{ user.user_status.Member }} The result was nothing: Finally I tried {{ user.user_status.Member.0 }} The result was the first character in ('Member', 'Member') ( How can I access either the first or second value of this tuple and display it in my HTML? -
Set cookies for ajax request, when "JsonResponse" is returned
When I use normal (not ajax) request, I do: from django.shortcuts import redirect response = redirect('/some_page') response.set_cookie(key='key1', value='value1', max_age=3600) response.set_cookie(key='key2', value='value2', max_age=3600) return response and it works and cookies are set, though, when I use ajax request, my view returns something like: JsonResponse({'res': 'success'}) and i'm not figured out, how I can set cookies, when JsonResponse is returned? -
form.is_valid () always returns False in Django
I got a strange bug. I am failing validation if I add an email field. If validation for only 1 username field, then everything works fine. Tell me please, what am I doing wrong? file forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=False) def __init__(self, user, *args, **kwargs): self.user = user super(UserUpdateForm, self).__init__(*args, **kwargs) if 'label_suffix' not in kwargs: kwargs['label_suffix'] = '*' self.fields['username'].widget = forms.TextInput(attrs={'class':'input-text'}) self.fields['email'].widget = forms.EmailInput(attrs={'class':'input-text'}) class Meta: model = User fields = ("username","email",) file views.py: def get_context_data(self, request): self.object = get_object_or_404(Profile,slug=self.kwargs['slug']) ctx={} ctx['UserUpdateForm']=UserUpdateForm(request.POST if "UserUpdateForm" in request.POST else None,instance=request.user) сtx['comments']=Comments.objects.filter(profile=self.object) return ctx def post(self, request, *args, **kwargs): if request.method=='POST': if "UserUpdateForm" in request.POST: form=UserUpdateForm(request.POST) if form.is_valid(): user=User.objects.get(username=self.request.user) user.username=form.cleaned_data.get('username') user.email=form.cleaned_data.get('email') user.save() obj=Profile.objects.get(user__username=user.username) return HttpResponseRedirect(reverse_lazy('profile',kwargs={'slug': obj.slug},)) return render(request,self.template_name,self.get_context_data(request)) -
The view xxx didn't return an HttpResponse object. It returned None instead
I have an error I do not understand because the logic I use in my view has not changed and works for my other project. And when I read the Django doc, my logic's view is conform: https://docs.djangoproject.com/fr/2.2/topics/forms/#the-view We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required. In my form, I have validation control. My clean method below have 3 validations controls and the control #2 raised errors <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Ce patient ne peut être randomisé dans ce site. Veuillez vérifier votre saisie.</li></ul></li></ul> So in my understanding of the doc, it should be redirected to the completed form with errors message display (as it do usually in my project) even if there is no else condition for no valid form in my view(is_valid() == False). What is wrong? views.py def randomization_edit(request): if request.method == "POST": print("request", request.POST.dict()) form = RandomizationEditForm(request, data=request.POST or None) if form.is_valid(): # do stuff return redirect('randomization:confirmation', pk=randomisation.pk) else: if request.session.get('user_can_randomize'): form = RandomizationEditForm(request) return render(request, … -
How to listen to remote SQS queue in Django app?
I have a remote SQS queue I would like to listen to in my Django app. When a new message is published on the SQS queue, I would like my Django app to pick it up and do something with it (like parse it and insert a record into the database). I'm having a bit of confusion about the best tools for accomplishing something like this. I've mainly been spinning my wheels trying to get this to work using Celery. The part I'm not able to figure out with Celery is how can I trigger a task when a new message is published. I've followed these guides from Celery: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html https://docs.celeryproject.org/en/stable/getting-started/brokers/sqs.html However, the part that is not apparent to me is how a task is called when an SQS message is published. When I fire up celery via celery -A test worker -l INFO and publish a message in AWS to my SQS queue, I can see it printed in my console. I can also see that it picked up the task I defined in Django. Now, whenever it detects a new message, I want it to call my debug_task below. import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "camp.settings") app … -
How to access fetched data in Ajax response using Django?
i am trying to access data from view function to ajax response.here i am Getting data in my Views.py and i want to access that data in ajax Response. i don't know hoe to do that? Hare is my Code in My Views.py This is My views.py. i am calling this function via ajax. def myfunction(request): if request.method=='POST': id=request.POST['id'] result=MyModel.objects.filter(id=id) # in result variable i am getting all data like fname,,lname etc here is my AJAX Call $.ajax({ url: '/myfunction', method: 'POST', data: { 'id' : id, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(result) { alert(result); // here i want to access values } }); in My view.py function , I am getting all data in variable 'result'. i Want to access the all values like fname,lname in my ajax response. 'result' variable is contain a multiple records.i will be thankfull if anyone can help me with this issue. -
How to calculate sum in django models/views
I'm trying to make result app for student, there are two models one is for subject one for course, every course have more than one subject with subject credit, so I want to sum all subject credits depends on the course, now I'm getting single course's total subject credit, but is it possible to have all course's subjects credit total? because he/she could have more than one course. for example one course's subject total credit = 12 another one credit = 8 .......so total = 20 credits please see the images and what will be better approach for second image model design models.py class Subject(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) code = models.PositiveIntegerField(unique=True) credit = models.IntegerField(blank=True) files = models.FileField(upload_to='course/materials/', blank=True) status = models.CharField(max_length=15, choices=Subject_Status, blank=True) def __str__(self): return self.name class Meta: db_table = '' managed = True verbose_name = 'Subject' verbose_name_plural = 'Subjects' class Course(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, unique=True) prefix = models.CharField(max_length=20) code = models.CharField(max_length=20) subject = models.ManyToManyField('Subject', related_name='subject_list', blank=True) faield = models.ManyToManyField(Subject,related_name='failed_subject_status', blank=True) passed = models.ManyToManyField(Subject,related_name='passed_subject_status', blank=True) nerver = models.ManyToManyField(Subject,related_name='never_subject_status', blank=True) current = models.ManyToManyField(Subject,related_name='curent_subject_status', blank=True) program = models.ForeignKey('Program', related_name='program_course', on_delete=models.CASCADE, blank=True, null=True) views.py class Program_structure(generic.View): def get(self, *args, **kwargs): … -
How to enctype django username field in auth model?
I want to encrypt the username data before save in django auth User model, and decrypt the username data. we are using model like this class Profile(models.Model): user = models.OneToOneField(User,related_name='profile_data',on_delete=models.PROTECT) Regarding this Any solution reference pls -
How to use annotate and KeyTextTransform and KeyTransform to extract first element of nested array?
I am using Django 2.2 and postgres I have a jsonb field called actions And this is test value actions={ "accept": [ { "id": 123, # some random action id "created": "{:%Y-%m-%dT%H:%M:%S.%f%z}".format(datetime.now()), "user_id": 247, # some random user id } ] }, SO I want to use values_list and annotate. I do not know how to just get the actions.accept.0.created WHat I tried .annotate(first_accept=KeyTextTransform(0, KeyTextTransform("accept", "quotation__actions"))) This fails. I get the error django.db.utils.DataError: invalid input syntax for integer: "accept" LINE 1: ...te_type", ("sometable"."actions" #>> ARRAY['accept',0.. .annotate(accept_actions=KeyTextTransform("accept", "quotation__actions")) This works but it gives me '[{"id": 123, "created": "2020-10-16T12:28:16.452071", "user_id": 247}]' as a string. I can subsequently parse that string yes, but I prefer to directly access the created of the first element of the array. How do I do that? -
installing django-rest-knox with Anaconda Env
I am new to django. Trying to install django-rest-knox into anaconda env but its not working. can you please let me know the right command to install it. Thank you. -
Configure postgres database on a docker-compose first build for "background_tasks" use
I have a Django project that works great. The database is not registered in the repository. So when I do a docker-compose up from scratch, the project can't find the tables corresponding to "background tasks"... Task is refered in urls.py por immediate read on django project start. What would be the way to launch the project without previously editing the code calls to this table? docker-compose: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" volumes: - ./postgres-data:/var/lib/postgresql/data web: build: . command: bash -c " python manage.py runserver 0.0.0.0:8000 & python manage.py migrate & python manage.py process_tasks" volumes: - .:/code ports: - "8000:8000" - "5555:5555" depends_on: - db Log error: db_1 | 2020-10-16 11:48:35.090 UTC [32] ERROR: relation "background_task" does not exist at character 24 db_1 | 2020-10-16 11:48:35.090 UTC [32] STATEMENT: SELECT (1) AS "a" FROM "background_task" WHERE "background_task"."verbose_name" = 'zmq_puller' LIMIT 1 db_1 | 2020-10-16 11:48:35.090 UTC [33] ERROR: relation "background_task" does not exist at character 24 db_1 | 2020-10-16 11:48:35.090 UTC [33] STATEMENT: SELECT (1) AS "a" FROM "background_task" WHERE "background_task"."verbose_name" = 'zmq_puller' LIMIT 1 web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, … -
django website creates the model object but does not upload files to aws s3
i'm using a django 1.11 with Mysql im trying to but when i submit the form the object is created but no files this is only when i added aws s3 setting everything works fine when i store files locally so the problem is not in the form or the saving process also i tried to implement the same setting of aws s3 on a different website and it works fine so i think the settings for aws s3 are correct the only thing that i could not verify is the the data base the working website has a default sqlite db and the not working website has a My Sql database so is there additional steps that i have to do if im working with a non sqlite db to the aws s3 settings? this is my aws s3 settings #====== aws3 settings=============== AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '***************************' AWS_STORAGE_BUCKET_NAME = 'new-test-django2' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my course_db settings in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'course_db', 'USER': 'root', 'PASSWORD': '******', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', … -
How to compare columns of a 2 different tables in Django views?
I have 2 tables Questions and Answers. 2 tables having answer column. I want to compare Questions table answer column with answers table answer column and show the result using session. Please guide me to solve this. def result(request): if request.method=="POST": user_ans = Answers.objects.get(answer=answer) ques_ans = Questions.objects.get(answer=answer) result = 0 if ques_ans == user_ans: reslut +=1 else: result -=0.33 return render(request, 'result.html', {'result': result}) else: return render(request, 'result.html') -
'ObtainAuthToken' object has no attribute 'request'
I am trying to create a Login ViewSet in django and I've used ObtainAuthToken to get the token. Here is my code snippet for this class LoginViewSet(viewsets.ViewSet): serializer_class = AuthTokenSerializer def create(self, request): return ObtainAuthToken().post(request) But it is raising the error as 'ObtainAuthToken' object has no attribute 'request' Thank you in advance. -
Error in Django while adding a table on admin page
I'm making a simple booking app in Django. I've made a model where I'll store booking data for each day of the week and tried to add a table based on it on admin page. But when I click "save", I receive an error: Traceback (most recent call last): File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (no such table: baseapp_bookingmodel) was the direct cause of the following exception: File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1580, in _changeform_view self.save_model(request, new_object, form, not add) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line … -
Heroku adds an extra "/checkout" in the URL when completing order with Stripe using Django
I have a small ecommerce project hosted on Heroku that I've built using Django, when clicking "complete order" on the checkout page I should be taken to the template "checkout_success" but instead I get stuck on the same page due to the URL trying to find a path with an extra "/checkout". I've posted some screenshots below to further explain. Checkout app URLS.py: from django.urls import path from . import views from .webhooks import webhook urlpatterns = [ path('', views.checkout, name='checkout'), path('checkout_success/<order_number>', views.checkout_success, name='checkout_success'), path('cache_checkout_data/', views.cache_checkout_data, name='cache_checkout_data'), path('wh/', webhook, name='webhook'), ] Heroku Logs Error: **notice the extra "/checkout" in the POST URL. Same in the browser console URL I've tried an array things from adding and taking away "/" in my settings.py file and other URL paths. I'm sure this is something im overlooking but i've been stuck with this bug for days now. If anyone could help that would be great! And if any additional info is needed i'll be happy to provide. Thanks! -
Returned a template response with no `template_name` attribute set on either the view or response (drf-yasg2)
I setup everything as per the docs of drf-yasg2 but I'm getting this error and I can't find whats causing it. I went through the docs and there is nothing I can use from there. It looks like every response is falling back to the TemplateHTMLRenderer instead of using drf-yasg2 ReDoc or SwaggerUI renderers. def render(self, swagger, accepted_media_type=None, renderer_context=None): if not isinstance(swagger, Swagger): # pragma: no cover return TemplateHTMLRenderer().render( swagger, accepted_media_type, renderer_context ) self.set_context(renderer_context, swagger) return render_to_string( self.template, renderer_context, renderer_context["request"] ) This condition will never return false if not isinstance(swagger, Swagger): because the Response class from djangorestgramework (response.py) is calling this method with the self.data instead of a rendered as a parameter: ret = renderer.render(self.data, accepted_media_type, context) I have no idea what I'm doing wrong here. In my project I use: drf-yasg2==1.18.5 djangorestframework==3.8.0 Django==2.0.1 urls.py from rest_framework import permissions from drf_yasg2.views import get_schema_view from drf_yasg2 import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), settings.py -> INSTALLED_APPS INSTALLED_APPS = [ 'rest_framework', 'myappname', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django', 'storages', 'colorfield', 'drf_yasg2', ] The error Internal Server Error: /swagger/ … -
Heroku - Django App Crased Error H10 status
heroku logs --tail --app the-milky-way-airlines 2020-10-16T10:26:30.053966+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [INFO] Booting worker with pid: 9 2020-10-16T10:26:30.059087+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [ERROR] Exception in worker process 2020-10-16T10:26:30.059088+00:00 app[web.1]: Traceback (most recent call last): 2020-10-16T10:26:30.059088+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-16T10:26:30.059089+00:00 app[web.1]: worker.init_process() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-16T10:26:30.059089+00:00 app[web.1]: self.load_wsgi() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-16T10:26:30.059090+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.callable = self.load() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-16T10:26:30.059091+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-16T10:26:30.059091+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-16T10:26:30.059092+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/init.py", line 127, in import_module 2020-10-16T10:26:30.059092+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 961, in _find_and_load_unlocked 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 973, in _find_and_load_unlocked 2020-10-16T10:26:30.059094+00:00 app[web.1]: ModuleNotFoundError: No module named 'the_milky_way_airlines' 2020-10-16T10:26:30.059216+00:00 app[web.1]: [2020-10-16 … -
Django - document.querySelector finds the base.html tags only
I have the django app with traditional base.html approach, which is extended in every other template. However, I have a problem with reaching out html tags which are outside the base.html template. var myHeading = document.querySelector(".contentfont"); console.log(myHeading); gives me: <div class="contentfont"> <!-- JS --> <script src="/static/js/squad_picker.js" type="text/javascript"></script> <h1 id="test" class="heading test"> test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> </div> but when I try for example var myHeading = document.querySelector(".contentfont > h1"); it always gives me null. The same happens while trying to access anything which is not inside base.html directly by id or class. I add the part of base.html: <div class="contentfont"> {% block content %} {% endblock %} </div> and the html which is extending it: {% extends 'my_app/base.html' %} {% load static %} {% block content %} <!-- JS --> <script src="{% static 'js/squad_picker.js' %}" type="text/javascript"></script> <h1 id='test' class="heading test">test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> {% endblock %} -
Can't get django pagination work with related fk set
I'm a django beginner and i'm trying to build a website using only generic CBV. In my models i have a class called Project and another class called ProjectFile as follow: class Project(models.Model): STATUS = ( ('Ongoing', 'Ongoing'), ('Ended', 'Ended'), ('Abandoned', 'Abandoned'), ) name = models.CharField(max_length=200, unique=True, error_messages={'unique':"This project name already exists"}, null=True) description = models.TextField(null=True) status = models.CharField(max_length=100, null=True, choices=STATUS) start_date = models.DateField(null=True) end_date = models.DateField(blank=True, null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return self.name class ProjectFile(models.Model): file = models.FileField(upload_to='project_files/') date_created = models.DateTimeField(auto_now_add=True, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) I've created a CBV view to list all the projects called ProjectList as follow: class ProjectList(ListView): model = Project context_object_name = 'projects' paginate_by = 5 def get_queryset(self): return Project.objects.all().order_by('name') def get_context_data(self, **kwargs): ctx = super(ProjectList, self).get_context_data(**kwargs) ctx['projects_count'] = self.get_queryset().count() ctx['ongoing_count'] = Project.objects.filter(status='Ongoing').count() ctx['ended_count'] = Project.objects.filter(status='Ended').count() return ctx and i added the pagination in template like this: {% if is_paginated %} <nav class="pagination is-centered is-rounded"> {% if page_obj.has_previous %} <a class="pagination-previous" href="?page= {{ page_obj.previous_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}"><i class="fa fa-hand-o-left"></i>&nbsp;{% trans "Previous" %}</a> {% else %} <a class="pagination-previous" disabled>{% trans "Previous" %}</a> {% endif %} {% if page_obj.has_next %} <a class="pagination-next" href="?page={{ page_obj.next_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}">{% trans "Next" %}&nbsp;<i … -
Django - ListView url not connecting to desired view
I am new to Django and have hit a wall with a certain part of my project and I hope someone can help. I have two ListViews in my views.py file which I would like to work similar to published/draft posts (I'm actually using sanitised and unsanitised reports). Currently, every time I try to access the "Unsanitised" list view (unsanitised_list.html), it just directs me to the the sanitised list view (intelreport_list.html) views.py: class IntelReportListView(ListView): model = IntelReport context_object_name = 'all_logs' def get_queryset(self): return IntelReport.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class UnsanitisedListView(LoginRequiredMixin, ListView): login_url = '/login/' redirect_field_name = 'intel_db/unsanitised_list.html' model = IntelReport def get_queryset(self): return IntelReport.objects.filter(sanitised__isnull=True).order_by('-create_date') models.py class IntelReport(models.Model): gpms_choices = ( ***REDACTED*** ) gpms = models.CharField(max_length=20, blank=True, null=True, choices=gpms_choices) officer = models.CharField(max_length=50) create_date = models.DateTimeField(auto_now_add=True) sanitised = models.BooleanField(default=False) source_eval_choices = ( ***REDACTED**** ) source_eval = models.CharField(max_length=50, blank=True, null=True, choices=source_eval_choices) intel_eval_choices = ( ***REDACTED*** ) intel_eval = models.CharField(max_length=100, blank=True, null=True, choices=intel_eval_choices) report = models.TextField(max_length=5000, blank=True, null=True) def sanitised_log(self): self.sanitised = True self.save() def get_absolute_url(self): return reverse('log_details', kwargs={'pk':self.pk}) def __str__(self): return str(self.pk) urls.py from django.urls import path from intel_db import views urlpatterns = [ path('welcome/', views.AboutView.as_view(), name='about'), path('logs/', views.IntelReportListView.as_view(), name='log_list'), path('logs/<int:pk>/', views.IntelReportDetailView.as_view(), name='log_detail'), path('logs/new_log/', views.IntelReportCreateView.as_view(), name='new_log'), path('unsanitised/', views.UnsanitisedListView.as_view(), name='unsanitised'), path('logs/<int:pk>/sanitise_log/', views.sanitsed_report, name='sanitised_report'), ] and on my landing … -
How to handle django application having multiple databases in celery
I am using multiple databases in my django application and the database is selected on the basis of url. All the views are working properly and use the database as required. Now, I have an API which exports the data into excel and I am trying to shift main logic of this API to a background tasks using celery. The issue I am facing is that celery is using default database for querying which is not required. So how can I make celery use database based on url. I am using python 3.7, django 2.2.11, django rest framework 3.11.0, celery 4.4.3. Any help would be appreciated. Thanks in advance! -
How to save for a simple model I need to save the User key automatically How to get objects owned by a user? in Django
i have such a model class Summaries(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) father_name = models.CharField(max_length=60, blank=True) myfile = models.FileField(upload_to="document") class Summary_Createes(models.Model): suser = models.ForeignKey(Summaries, on_delete = models.CASCADE) for the active, current user "Summary_Createes" The user who saved this model should only see it for himself how can i filter such data i need filter