Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load bootstrap styles in Django
ingestion-dashboard/ ├── apps │ ├── adapter │ ├── authentication | |__init__.py │ ├── static │ │ ├── assets │ │ │-- css │ │ │── img │ │ │── scss │ │ │── vendor │ └── templates │ ├── accounts │ ├── home │ ├── dashboard │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └───staticfiles ├── assets │── css │── img │── scss │── vendor settings.py CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ingestion-dashboard STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) With this layout, django works fine with local server with proper loading of bootstraps and styles. But when i ran this on kubernetes/nginx , the app is working fine but missing bootstraps, styles. The staticfiles dir in ingestion-dashboard/dashboard/staticfiles is being populated by command django-admin manage.py collectstatic. Any help is appreciated. I have loaded styles as <script src="/static/assets/vendor/@popperjs/core/dist/umd/popper.min.js"></script> works fine with local development. -
i want a validation in my Django model that question field would not accept an integer i try but it's not working..How can i do that?
Here this is my Code #models.py from django.db import models class Question(models.Model): question = models.CharField(max_length=200, null= True) option1 = models.CharField(max_length= 200, null= True) option2 = models.CharField(max_length= 200, null= True) option3 = models.CharField(max_length= 200, null= True) option4 = models.CharField(max_length= 200, null= True) answer = models.CharField(max_length=200, null=True) def __str__(self): return self.question #views.py from django.shortcuts import render,redirect from .models import * from .forms import QuestionForm from django.views import View from django.urls import reverse class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid(): forms.save() print("i was in If ") return redirect(reverse('home')) else: print("i was in else ") context = {'forms': forms} return render(request, 'file/addQuestion.html', context) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) -
How to create a cluster of links, then feed it to scrapy to crawl data from the link based on a depth and crawling strategy set by user from browser
We need help doing this project for our junior year software engineering project. So, our web app is supposed to: Login/Register/Authenticate via google : (we have completed this using Django Allauth.) Then, users will be able to create a cluster of links in a new cluster creating page, there the users will be able to provide information about the clusters. They will provide: cluster name, links to crawl data from, set a depth for each link they provide. (By depth I mean, following the links and webpages associated with the website) Finally, the users will be able to provide a crawling strategy to what to crawl, for this instance(we do not want to crawl any non textual data) : non HTML text data, pdf, doc files. Then, we need to crawl the data and store it in a database or a service (We intend to use Apache Lucene here). So, the data is searchable for the end user from a cluster that they had created. For now, how can we implement all of the things mentioned in point 2? Can someone please help by debunking this step by step on exactly what we need to do? We are a bit … -
Django SECRET_KET on VPS
I'm working on a Djnago app that needs to be uploaded on a VPS. I already have moved my SECRET_KET from settings.py and placed it inside .env file that I created and addedthis .env file to .gitignore. When I'm uploading the project to my VPS, Django isn't able to locate my SECRET_KEY because obviously the .env file is not found inside my project directory on the VPS. What should I do in this case and how am I supposed to call the SECRET_KEY on the server? -
How to reset password in Django by sending recovery codes instead of sending link
Can anybody explain how to use the recovery codes to reset the password using recovery codes instead of recovery links like of Facebook ,Gmail etc. I'd like to reduce the pages user have to open. Here're what I want: instead the reset link, send to user the key only -
Nasa Insights Api
I am trying to make a weather app using Nasa insights Api. But when i am workig with api's first key i.e., "sol_keys" which is a list of sol's, But when i am printing this sol_keys list, I am gettting an empty list. Now, what to do, and how to use this api. Url = "https://api.nasa.gov/insight_weather/?api_key="+mars_api_key+"&feedtype=json&ver=1.0" mars_weather = requests.get(Url) mars_weather = mars_weather.json() Present_sol = mars_weather['sol_keys'] print(Present_sol) I am getting "[]" this as an output. But what I am expecting is the seven sol string like -> ["256","257","258","259","300","301","302"] -
How to include a CSRF token inside a hardcoded form post
I have the following AJAX datatable: $('#ittFileUploadTable').DataTable( { responsive: true, autowidth: false, destroy: true, deferRender: true, ajax: { url: '/project_page_ajax/', type: 'GET', data: {}, dataSrc: "" }, columns: [ {"data": "fields.filename"}, {"data": "fields.uploaded"}, {"data": "fields.updated"}, {"data": "fields.user"}, {"data": "pk"}, ], columnDefs: [ { className: 'text-center', targets: [1] }, { targets: [0], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<a href="/media/'+data+'" target="_blank">'+data+'</a>'; return buttons; } }, { targets: [-1], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<form method="post" action="delete_file/'+data+'/"><button type="submit" class="btn btn-danger"><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="white" class="bi bi-trash-fill" viewBox="0 0 16 16"><path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/></svg></button></form>'; return buttons; } }, ], order: [ [0, 'asc'] ], "pagingType": "numbers", dom: 'rt' }); The function in … -
Validation error in Django 'POST' request
I'm a beginner with Django Rest Framework I've created a model and serializer for it. There it goes: models.py class Car(models.Model): make = models.CharField(max_length=15) model = models.CharField(max_length=15) def __str__(self): return self.make class CarRate(models.Model): rate = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE) serializers.py class CarRateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CarRate fields = ('rate') class CarSerializer(serializers.HyperlinkedModelSerializer): rates = CarRateSerializer(many=True) '''rates = serializers.PrimaryKeyRelatedField( many=True, read_only=False, queryset=CarRate.objects.all() )''' def create(self, validated_data): rates_data = validated_data.pop("rates") car = Car.objects.create(**validated_data) for rate_data in rates_data: CarRate.objects.create(car=car, **rate_data) return car class Meta: model = Car fields = ('id', 'make', 'model', 'rates') What I want to do is to add a rate for a Car with a specific ID with a POST method and JSON, but when I do it multiple times it stores all the rates for that one object. I will add a rate like that: { "id":2, "rate":4 } So here is my POST method, but it gives a response Car id not found so it doesn't pass validation. views.py @api_view(['POST']) def car_rate(request): if request.method == 'POST': rate_data = JSONParser().parse(request) rate_serializer = CarSerializer(data=rate_data) if rate_serializer.is_valid(): ''' Code that checks if a rate is from 1 to 5 ''' return JsonResponse({'message': 'Car id not found!'}) So what I think might be … -
how to save parent , child and grand child forms in one submit - django
i'm building an application for a mobile trading company , the is the scenario : every invoice has an unique invoice number and every unique date has several phone models and every phone models have a number of IMEI here is how i designed the database model class Collection(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) company = models.ForeignKey(Company,on_delete=models.PROTECT) invoice_no = models.IntegerField(unique=True) collection_date = models.DateTimeField(default=timezone.now) class MobileCollection(models.Model): collection = models.ForeignKey(Collection,on_delete=models.PROTECT,related_name='collections') mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) i have to submit all of them in one go ! i'm not sure how to build its view , while the MobileCollection model should increase dynamically , and with the qnt field in MobileCollection the Imei forms should increase , for example if the qnt=10 we should add 10 Imei forms , i thought about inlineformset_factory but i its not work in my case . please is there a better approach to achieve that ? thank you in advance -
How can I build share option like facebook or youtube using Django?
I am building a social website using Django. I want to implement the share function for users to data between other users. Can someone give me brief idea about that? How can I do this or How to implement the code. -
Override helptext in Wagtail EditView
I am trying to override the helptext that is set in my model in the wagtail admin (an edit view). I have tried the code below but the text is not changed, why is that? class MemberRegistrationEditView(EditView): def get_form(self): form = super().get_form() form.base_fields.get("own_email").help_text = "Test" return form -
Executing a function right before\after revoking a task in celery
For the demonstration, I have a class that does something like this: class Writer: def __init__(self, num): self.num = num def write(self): for i in range(0, num): with open("/outfile", "w") as o: o.write(i) def cleanup(self): # should be executed when write has not finished os.system('rm -rf /outfile') Im using a shared task in celery to execute it like: @shared_task def mytask(): w = Writer(100) w.write() return "Done" Im using django and DRF, and i have an endpoint api that recieves a task_id and revokes the task using revoke(task_id, terminate=True) My goal is to run the cleanup function from the Writer class when the revoke happens. The reason I cannot just run cleanup after the revoke as a regular function is because it needs to access the attributes of its class (in the real senario and not this example), and each class might have a different cleanup function. how can i detect the revoke in mytask() ? Is there a solution using something like try except? Moving the task to a class based task? Have not found anything online or in the docs. Thanks in advance. -
Django-Rest-Framework can't override serializer unique error_messages
I have the following model: class PersonDiscount(models.Model): user = models.OneToOneField('backend.Customer', related_name='discount', on_delete=models.CASCADE, error_messages={ 'unique': _('A discount setting is already set up for this customer.')}) discount = models.IntegerField(default=0) discount_auto = models.IntegerField(default=0) auto = models.BooleanField(default=True) class Meta: ordering = ['-id'] And a following serializer for the model: class PersonDiscountPostSerializer(serializers.ModelSerializer): class Meta: model = PersonDiscount fields = '__all__' extra_kwargs = { 'user': { 'error_messages': { 'unique': _('A discount setting is already set up for this customer.') } } } When i tried to create a PersonDiscount instance with existed user from the api i'm not getting the custom error message which i set in both model and serializer. { "user": [ "This field must be unique." ] } I had already looked up in the docs and can't find any other way to understand why the override error_messages not getting applied. I also restarted the django runserver several times already Hope someone can help me with this problem -
Django : FOREIGN KEY constraint failed on delete, but I don't have any Foreign Key on my model
Here is my model which objects I can't delete : class Broker(models.Model): code = models.CharField(default="", max_length=100, blank=True) name = models.CharField(default="", max_length=100, blank=True) email = models.CharField(default="", max_length=100, blank=True) city = models.CharField(default="", max_length=100, blank=True) address = models.CharField(default="", max_length=100, blank=True) postal_code = models.CharField(default="", max_length=100, blank=True) brokerage = models.FloatField(default=0.00) class Meta: verbose_name = 'Broker' verbose_name_plural = 'Brokers' ordering = ['name'] def __str__(self): return str(self.name) Here is what creates my error (he occurs on the line where I make rem.delete()): if request.POST.get('action') == 'remove_element_selected': element_selected = request.POST.getlist('element_selected[]') for element_id in element_selected: rem = Broker.objects.get(id=element_id) rem.delete() return JsonResponse({}) And here is my error : Internal Server Error: /brokers/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/lucas/Desktop/myapp/app/views/views.py", line 636, in brokers rem.delete() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 880, in delete return … -
Django-Rest-Framework 3.0 ImproperlyConfigured at /api/users/ Field name `is_owner` is not valid for model `User`
have some strange bug in my project. I was remove is_owner field from user's model, made migrations and now when i'm sending post request to my user's endpoint i have this exception. django.core.exceptions.ImproperlyConfigured: Field name is_owner is not valid for model User. But i can't found any place in project, using Ctrl Shift F, where old i_owner field can be called. In ruquest i using this field nowhere too. enter image description here -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Unable to figure out my error. Below is my settings.py Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. import category.context_processors BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-(@pq@&r(t2tm_m8ci@$%z_z^l+kbnxdyd5#_+h8ckafos&8b5*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'store', ] 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', ] ROOT_URLCONF = 'greatkart.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'category.context_processors.menu_links', ], }, }, ] WSGI_APPLICATION = 'greatkart.wsgi.application' AUTH_USER_MODEL = 'accounts.Account' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Django - Return all objects in table where attribute A is in list B OR attribute C is in list D
So below I have this code where the request has the current User object. A User can have "followers" which are represented by FollowUser and they can follow another user's goal, which is represented by FollowGoal. I want to return all the posts that the current user which is represented by request.user. I want to be able to get all posts where the creator is someone the current user is following or is a goal the current user is following. As you can see below I generate a list of UUID for both the followees of the current user (people they are following) as well as a list of UUID for the goals the current user is following. Then I do <attribute>__in, but for some reason it's returning an empty list. Even if I just filter by followees or follow goals. Not sure why it's returning an empty list. I generated fake data that represent both the cases of posts created by followees of the current user and goals the current user is following. The Post object should filter if the creator is by someone the current user is following OR the goal is a goal the currrent user is … -
Unable to deploy Django app on Heroku, getting Traceback on `python manage.py collectstatic`
I was going to deploy my app on heroku. I have set all of the paths such as STATIC_ROOT, STATIC_URL and STATICFILES_DIRS correctly. I am still getting the error. Anyone knows whats wrong? Traceback error remote: Traceback (most recent call last): remote: File "/tmp/build_64cf714d/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_64cf714d/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect remote: for original_path, processed_path, processed in processor: remote: File "/app/.heroku/python/lib/python3.9/site-packages/whitenoise/storage.py", line 148, in post_process_with_compression remote: for name, hashed_name, processed in files: remote: File "/app/.heroku/python/lib/python3.9/site-packages/whitenoise/storage.py", line 88, in post_process remote: for name, hashed_name, processed in files: remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 399, in post_process remote: yield from super().post_process(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 231, in post_process remote: for name, hashed_name, processed, _ in self._post_process(paths, adjustable_paths, hashed_files): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 288, in _post_process remote: content = pattern.sub(converter, content) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 187, in converter … -
Is nginx required to deploy a gatsby front end beside a django REST backend?
I'm currently trying to deploy a Django REST backend and a React/Gatsby frontend to Heroku (using the steps outlined in this article https://dev.to/mdrhmn/deploying-react-django-app-using-heroku-2gfa), and I'm having some issues sending requests from the front end to the back end. GET Instruction useEffect(() => { fetch('http://127.0.0.1:8000/ljwe/symbol/?freq=monthly&symbol_id=1') .then(res => res.json()) .then(data => setOptions(data)) .catch((err) => {console.error(err)}) }, []); CORS_ALLOW_ALL_ORIGINS = True in settings.py "proxy": "http://localhost:8000" in both gatsby-config.js and package.json files Locally, everything works fine and the database is successfully queried, returning the proper information Unfortunately, when I push my changes to Heroku, the data is no longer displayed. I'm using the following build packs: heroku/node.js https://github.com/heroku/heroku-buildpack-static heroku/python When I run heroku run psql <heroku_app> I can query the app's database and see relevant entries in the tables. In addition, when I manually enter my API endpoints on the Heroku-hosted version, they work as intended. My Heroku logs also seem to show the request going through fine. Browser Console Output -
How i transfer data(variables) from one html page to another page, here i am using html & django framework
here in my code i am displaying elements from a database using a loop at the the user click buy button, i want to pass the particular product id to another page. how i get the product id & how it passed to another page... HTML page {% for product in products %} <div class="col-md-3"> <div class="card"> <img src="{{product.product_image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{product.product_name}}</h5> <p class="card-text">₹{{product.product_price}}</p> <a href="{% url 'buy' %}" class="btn btn-primary"> Buy</a> </div> </div> </div> {% endfor %} -
Connection refused when accessing Nginx container from React container
I'm trying to run the Django-React application inside the docker, when I start testing the React application, this error appears. FetchError: request to http://localhost/media/filer_public/03/58/0358cfac-1ac5-4caa-8b6b-bd20361dd878/import_filesa0a0b76730363b11ebb8a73cf86249c70c_b167f69b364a11ebb8a73cf86249c70c.jpg failed, reason: connect ECONNREFUSED 127.0.0.1:80 Pay attention to _next As I understand it, there is a request for localhost:80 inside the React container, but since there is no such address in this container, this exception is raised. Images that are just a request to localhost:80/media/filer.../ receive a response. Example of an image request that works <img src="http://localhost/media/filer_public/03/58/0358cfac-1ac5-4caa-8b6b-bd20361dd878/import_filesa0a0b76730363b11ebb8a73cf86249c70c_b167f69b364a11ebb8a73cf86249c70c.jpg" /> At the moment I am passing the api address in a similar way via .env file BACKEND_ADDRESS=localhost:80 Is it possible to pass the address of the Nginx container to the React container? Or are there any other ways to solve the problem? docker-compose.yml version: "3.8" services: nginx: restart: unless-stopped build: context: . dockerfile: ./nginx/Dockerfile ports: - 80:80 volumes: - media:/code/media/ - static:/code/staticfiles/ - ./nginx/conf:/etc/nginx/conf.d depends_on: - app networks: - backend db: image: postgres:latest volumes: - db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres networks: - backend app: container_name: django_app build: . command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 --reload --workers=4 --threads=4 --access-logfile - ports: - 8000:8000 volumes: - .:/code - media:/code/media/ - static:/code/staticfiles/ depends_on: - db networks: - backend redis: … -
Why isn't Django Rest Framework Token Authentication working?
I am currently using Django rest framework and trying to implement a Token Authentication system. Currently, my settings.py looks like this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] } and rest_framework.authtoken is in installed_apps. My urls.py looks like this: urlpatterns = [ ... url('^v1/users/$', views.users_view), ... ] My views.py looks like this: @authentication_classes((TokenAuthentication,)) @api_view(['PUT', 'POST']) def users_view(request): ... I'm working in postman to test the API and regardless of whether I put the token in the Bearer Token authorization field, the API works as intended. What do I need to change for the token authentication to work as intended? -
query set too many objects to unpack expected(2) in django templateView
I have written a view to show open,completed,accepted and closed tickets on dashboard on clicking which goes into particular url to display the tickets accordingly and am switching the templates according to their status,I am quering the ticket status and i get the following error too many objects to unpack (expected 2) models.py class Ticket(models.Model): ticket_title = models.CharField(max_length=200) ticket_description = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( ('Opened','Opened'), ('Accepted','Accepted'), ('Completed','Completed'), ('Closed','Closed') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,default = 'Opened') closed_date = models.DateTimeField(blank=True,null=True) completed_date = models.DateTimeField(blank=True,null=True) accepted_date = models.DateTimeField(blank=True,null=True) opened_date = models.DateTimeField(blank=True,null=True) accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.ticket_title Views.py class DeveloperTicketView(TemplateView): def get_template_names(self): ticket_type = Ticket.objects.filter('status') if ticket_type == "Opened": template_name = 'app/open_tickets.html' elif ticket_type == 'Accepted': template_name = 'app/dev_accepted_ticket.html' elif ticket_type == 'Completed': template_name = 'app/dev_completed_tickets.html' else: template_name = 'app/dev_closed_tickets.html' return template_name def get_context_data(self, **kwargs): context = super(TemplateView,self).get_context_data(**kwargs) context['open_tickets'] = Ticket.objects.filter(status = 'Opened') context['accepted_tickets'] = Ticket.objects.filter(status = 'Accepted',accepted_by = self.request.user) context['completed_tickets'] = Ticket.objects.filter(status = 'Completed',accepted_by = self.request.user) context['closed_tickets'] = Ticket.objects.filter(status = 'Closed',accepted_by = self.request.user) return context -
Django - Can't read media files
I'm using Django to create a website where you can upload an image on that website and check if the image contains Moire pattern. Here is the project structure: In file settings.py, I specified the following directory for media files: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and in file views.py, I implemented the API that will receive the image and detect moire pattern like this: from django.core.files.storage import default_storage def index(request): if request.method == 'POST': f = request.FILES['sentFile'] response = {} fname = 'pic.jpg' fname2 = default_storage.save(fname, f) file_url = default_storage.url(fname2) image = Image.open(file_url) pred_label = moire_detect(image) response['label'] = pred_label return render(request, 'frontpage.html', response) else: return render(request, 'frontpage.html') However, when I try to open the image using Image module of Pillow, I got this error "No such file or directory: '/media/pic_O1TOyCK.jpg'". I don't really understand what is happening here, because the path is correct. Any help would be really appreciated. -
Add total pages to the Django Rest Framework response when using pagination
At the Django Rest Framework Documentation you can add pagination according to the document at this link: https://www.django-rest-framework.org/api-guide/pagination/#modifying-the-pagination-style class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 and the response will look like: HTTP 200 OK { "count": 1023 "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } How can I add "total_pages" to the response? HTTP 200 OK { "count": 1023 ==>"total_pages": 12 "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } I looked into the DRF code and saw the PageNumberPagination class has a "num_pages" property. But I'm not sure how to call it in the StandardResultsSetPagination class. https://github.com/encode/django-rest-framework/blob/0323d6f8955f987771269506ca5da461e2e7a248/rest_framework/pagination.py