Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google oAuth2 getting Internal Server error after redirected to url
In the Django web application, I followed all the neccessary steps for login using google. But after login in through a google account, it will redirect to my local URL but get an Internal server error. I think my google cloud platform settings are right. Because I used same client key and secret key same in another demo Django project, it works fine for that. in google cloud platform redirect URL is -- http:localhost:8000/oauth/complete/google-oauth2/ How to fix these? -
DRF File Upload, How can I solve File missing Error?
400 Error {"detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter."} I want to upload file via DRF FileUploadParser But Error occurs below Bad Request: /api/activities/40/chapter/1/upload [09/Nov/2021 16:44:33] "POST /api/activities/40/chapter/1/upload HTTP/1.1" 400 109 And my codes in views.py about that error are this. class FileView(APIView): parser_classes = (FileUploadParser,) def post(self, request, format=None, *args, **kwargs): if 'file' not in request.FILES: raise ParseError("Empty content") f = request.FILES.get('file') print(f) print(dir(request)) print(request.__dict__) addAttr = request.data.dict() file_name = request.data['filename'] new_file_full_name = file_upload_path(file_name.name) file_path = '/'.join(new_file_full_name.split('/')[0:-1]) #model Attr addAttr['activityid'] = request.parser_context['kwargs']['pk'] addAttr['chapterid'] = request.parser_context['kwargs']['chapterid'] addAttr['filepath'] = file_path addAttr['filename'] = file_name addAttr['fileext'] = os.path.splitext(file_name.name)[1] addAttr['create_date'] = datetime.datetime.now() addAttrDict = QueryDict('', mutable=True) addAttrDict.update(addAttr) fileSerializer = ChapterfileSerializer(data = addAttrDict, files=request.FILES) if fileSerializer.is_valid(): fileSerializer.save() print(fileSerializer.data) return Response(status=status.HTTP_201_CREATED) else: print(fileSerializer.errors) return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST) If I add a parameter "filename", 500 error occured. TypeError: post() missing 1 required positional argument: 'parameter' [09/Nov/2021 16:48:35] "POST /api/activities/40/chapter/1/upload HTTP/1.1" 500 86716 ReactJS page sends File to my Django API Server. activityid and chapterid are Board and Post ID. SO, I need these insert to DB. How can I solve this? -
How do I change stroke fill color (RGB) in python
how do I change stroke fill color (RGB) in python Showing Error: TypeError: color must be int or single-element tuple from PIL import Image from PIL import ImageDraw from PIL import ImageFont, ImageOps label2 = "VIKRAM" font = ImageFont.truetype('D:/vikram/pythonProject/fonts/B5______.TTF', 120) line_height = sum(font.getmetrics()) fontimage2 = Image.new('L', (font.getsize(label2)[0], line_height)) ImageDraw.Draw(fontimage2).text((0, 0), label2, stroke_width=10, stroke_fill=(0, 0, 0), fill=255, font=font)-------->stroke fill in (RGB) fontimage2 = fontimage2.rotate(330, resample=Image.NEAREST, expand=True) orig = Image.open('F:/desktop/sunshine girl/PSI Sunshine Theme Girl Personalized Eye Mask.png') orig.paste((220, 32, 37), box=(400, 200), mask=fontimage2) orig.show() -
unique_together does not prevent duplicate records
I have two models like this : class Preference(models.Model): lat = models.DecimalField(max_digits=25,decimal_places=15) lng = models.DecimalField(max_digits=25,decimal_places=15) name = models.CharField(max_length=150,null=True) address = models.TextField(max_length=350,null=True) type = models.CharField(max_length=150,blank=True,null=True) class PrefenceOfUser(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) place_detail = models.ForeignKey(Preference, on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = ('user', 'place_detail',) this is the json i post to my apiview : { "lat": "29.621142463088336", "lng": "52.520185499694527", "name":"cafesama1", "address":"streetn1", "type":"cafe" } in views.py : class PreferedLocationsOfUsers(APIView): def post(self, request, format=None): serializer = PreferLocationSerializer(data=request.data) if serializer.is_valid(): location= Preference(**serializer.data) location.save() user_perefeces = PrefenceOfUser(user=request.user,place_detail=location) user_perefeces.save() return Response({'location saved'},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i want to prevent the user to save dublicated records in database but when location object is saved in PrefenceOfUser unique_together does not prevent dublicating. any idea why? -
How to implement Angular with Django
I have requirement for creating an application using Angular(TypeScript) as frontend and Django as Backend, where I will be working only on Django (backend). Is that creating an REST API only enough to communicate with front end. Is that only possible in the backend in this case? Normally while working in Django I used to work in forms, views and will renders in the html and create API for it but in this case where I have no idea how angular would work even. Just creating an API only sufficient when communicating with Angular -
Custom Serializer for Django Rest Framework
I'm searching for a solution to create a serializer / API Endpoint to represent data in a custom order. When adding serializers and viewsets to DRF, I only get the fields associated with that Model. But what I like to have is a custom structure of all my models together. As an example: I have a model called season, a model called evenings and a model called events. Now I'd like to have an API Endpoint to have that all together, like so: { "requestTime": "2021-11-09 08:20", "requestURL": "/all", "requestMethod": "GET", "responseCode": 200, "season": "2021/2022", "evenings": [ { "evevning_id": 0, "day": "", "date": "2021-11-11", "event_count": 2, "events": [ {}, {} ] } ] } For data structure in the models I have some ForeignKeys like: season | evening | event Any suggestions how to achieve this? -
Django-set only one review per user and movie
models.py from django.db import models from django.contrib.auth.models import User class Play(models.Model): title = models.CharField(max_length=150) plot = models.TextField(max_length=900) slug = models.SlugField(unique=True, null=True) cast = models.CharField(max_length=500, default=0) category = models.CharField(choices=CATEGORY_CHOICE, max_length=10) image = models.ImageField(upload_to='movie') year = models.DateTimeField() author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) def __str__(self): return self.title class Review(models.Model): user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) movie = models.ForeignKey(Play, blank=True, null=True, on_delete=models.CASCADE) text = models.TextField() likes = models.ManyToManyField(User, related_name='blog_comment') def count_likes(self): return self.likes.count() def __str__(self): return f"{self.movie.title} 'User:' {self.user}" views.py from django.shortcuts import render, redirect, reverse from .models import Play, Review from django.contrib.auth.decorators import login_required from . import forms from django.http import HttpResponseRedirect def movies_list(request): article = Play.objects.all().order_by('year') return render(request, "articles/movies_list.html", {"articles":article}) def movies_detail(request, slug): articles = Play.objects.get(slug=slug) all_reviews = Review.objects.all().order_by('movie') isReviewAllowed = check_user_review(request, slug) return render(request, "articles/movies_detail.html", {"articles":articles,'all_reviews': all_reviews, 'isReviewAllowed': isReviewAllowed}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == "POST": form = forms.CreatePlay(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect("movies:home") else: form = forms.CreatePlay() return render(request, "articles/article_create.html", {"form":form}) @login_required(login_url="/accounts/login/") def sub_review(request, slug): form = forms.CreateReview(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user show = Play.objects.get(slug=slug) instance.movie = show instance.save() return redirect("movies:detail", slug=slug) else: form = forms.CreateReview() return render(request, "articles/review.html", {"form":form, "slug":slug}) def check_user_review(request, slug): check = Review.objects.values_list('user', 'movie') test = … -
Tiny MCE Text editor gives html in front-end [closed]
I am using Django in the backend and react.js in the frontend. The Tiny MCE Text editor gave me HMTl in the frontend. the blog is written tiny Mce text editor is correct but it gives in HTML instead of text in frontend -
IndexError on Django/MySQL after ordery_by an union queryset
I am using Django on ubuntu ec2 and MySQL on RDS. I try to obtain 3 random objects satisfying condition 1 (is_shoes=True, is_bag = False) and 2 random objects from the same model with different condition (is_shoes=True, is_bag = True) and union it in a random order. I tried using operator |, but it was now allowed in MySQL. Here is my source code and Error Message. Is there any solution? queryset = Store.objects.filter(is_shoes=True, is_bag = False).order_by('?') queryset_sample1 = queryset[:3] queryset2 = Store.objects.filter(is_shoes=True, is_bag = True).order_by('?') queryset_sample2 = queryset2[:2] queryset_sample = queryset_sample1.union(queryset_sample2, all=True) store_serializer = StoreSerializer(queryset_sample, many=True) response = Response({ 'store_list' : store_serializer.data }) return response Internal Server Error: /api/req/ Traceback (most recent call last): File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/generics.py", line 242, in post return self.create(request, *args, **kwargs) File … -
how to update all the record at once in Djnago
I want to display all the created department in one view using a for loop and update all the record at once. the problem is it is taking only the first record and updating all the record with the value entered at the first field I tried using .getlist() but still taking only the first record. how to update each record with reference to its id and if the field is empty keep that record untouched. Views.py def department(request): departments = Department.objects.all() value1 = request.POST.getlist('BUID') value2 = request.POST.getlist('GBUID') print(value1) print(value2) Department.objects.update( BUID=request.POST.get('BUID'), GBUID=request.POST.get('GBUID'), ) context = {'departments': departments} return render(request, 'employee/department.html', context) models.py class Department(models.Model): DepartmentID = models.IntegerField() <------will be Entered by the admin Name = models.CharField(max_length=200) <------will be Entered by the admin BUID = models.CharField(max_length=200, blank=True) <------to be updated in the view GBUID = models.CharField(max_length=200, blank=True) <------to be updated in the view templates <form action="" method="POST"> {% csrf_token %} <h3>Manage Departments</h3> <input class="btn btn-primary" type="submit" value="Submit"> {% for department in departments %} <div class="col-sm-6"> <label>Department ID: {{department.DepartmentID}}</label> </div> <div class="col-sm-6"> <label>Department Name: {{department.Name}}</label> </div> <label>BU/Department Manager Id:</label> <div class="col-sm-3"> <input name="BUID" class="form-control"> </div> <label>GBU/Group Department Manager Id:</label> <div class="col-sm-3"> <input name="GBUID" class="form-control"> </div> </form> {% endfor %} -
type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' (Exception is being thrown while fetching data)
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error class Product { int? id; String? title; String? price; String? description; Category? category; bool? favorites; Product( { this.id, this.title, this.price, this.description, this.category, this.favorites}); Product.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; price = json['price']; description = json['description']; category = json['category']; favorites = json['favorites']; category = json['category'] != null ? new Category.fromJson(json['category']) : null; favorites = json['favorites']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['price'] = this.price; data['description'] = this.description; if (this.category != null) { data['category'] = this.category!.toJson(); } data['favorites'] = this.favorites; return data; } } class Category { int? id; String? categoryName; String? createDate; Category({this.id, this.categoryName, this.createDate}); Category.fromJson(Map<String, dynamic> json) { id = json['id']; categoryName = json['category_name']; createDate = json['create_date']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['category_name'] = this.categoryName; data['create_date'] = this.createDate; return data; } } Flutter is giving the unhandeled exception while fetching the data This … -
Is partial form a good practice in Django?
I'm new in Django and I try to find out if saving partial forms is a good practice or not. For example, I have Poll App and Candidate model with four fields: name, surname, targets andbiography. And I have a form where I have to fill all these fields. But if user only finished fill name, surname and targets, but even din't start filling biography field, how can I save his draft to user can finish it later and don't make any security mess? I will be happy to see all ideas. -
How to save model in Django with unique but null fields
How can I save a model that should be unique but also allowed to be null in Django. For instance I have the following model... class PetOwner(models.Model): """Model representing a pet owner.""" user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, help_text="Enter owner's first name") last_name = models.CharField(max_length=50, help_text="Enter owner's last name") email = models.EmailField( max_length=50, blank=True, unique=True, help_text="Enter owner's email" ) phone_number = models.CharField( max_length=15, blank=True, unique=True, help_text="Enter owner's phone number" ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) I want my app to work the following way. A PetOwner can sign up but when they do they initially only sign up with a username, password, a confirmation password, and first_name, and last_name. I want my to have a profile page which will allow for updating the PetOwner to include their phone_number but I do not necessarily want to make this a requirement. I decided that I'd make phone_number field null=True and blank=True but as soon as I register a second user I get a django.db.utils.IntegrityError: UNIQUE constraint failed: app_petowner.phone_number error. I believe it is because when I register a user for some reason instead of phone_number being None even when I did not actually add a phone number at … -
how to upload multiple images properly
I have a simple model which has four different fileFields for uploading different files and images. this is my models: class DocumentInfo(models.Model): id = models.AutoField(primary_key=True) certificate = models.FileField(upload_to="documents", null=True) id_card = models.FileField(upload_to="documents", null=True) service_certificate = models.FileField(upload_to="documents", null=True) educational_certificate = models.FileField(upload_to="documents", null=True) users need to simply upload some images in four individual fields so, I created a simple form and passed it to views like this: class DocumentForm(forms.ModelForm): class Meta: model = DocumentInfo fields = ['certificate','id_card','service_certificate','educational_certificate'] views.py: def document_info(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('document') if 'delete' in request.GET: return delete_item(DocumentInfo, request.GET['id']) else: form = DocumentForm() documents = DocumentInfo.objects.filter(user=request.user) context = { 'form': form, 'documents': documents, } return render(request, 'reg/documents.html', context) it works just fine at first but I cant reupload anything! the uploaded image neither gets saved the second time around nor deleted. what am I doing wrong? -
docker-compose Error... [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started
docker-compose.yml version: "3.7" services: db: platform: linux/x86_64 image: mysql:5.7 volumes: - ./db_data1:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}" MYSQL_DATABASE: "${DB_DATABASE}" MYSQL_USER: "${DB_USER}" MYSQL_PASSWORD: "${DB_ROOT_PASSWORD}" ports: - 3306:3306 command: - --character-set-server=utf8mb4 - --collation-server=utf8mb4_unicode_ci web: build: dockerfile: ./Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./web_data1:/app ports: - 8000:8000 environment: DJANGO_DB_HOST: db:3306 DJANGO_DB_NAME: "${DB_DATABASE}" DJANGO_DB_USER: "${DB_USER}" DJANGO_DB_PASSWORD: "${DB_ROOT_PASSWORD}" my_setting.py DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': "${DB_ROOT_PASSWORD}", 'HOST': 'db', 'PORT': '3306', } } SECRET = 'django-insecure-#kb%p45em8hdhja^+2jal#(*mzw1c3jk5gvsx(_cn@q^u@u&b0' ALGORITHM = 'HS256' Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "--bind", "0.0.0.0:8000", "docker_train.wsgi:application"] .env DB_ROOT_PASSWORD=password DB_DATABASE=test DB_USER=root I run docker-compose up but got this error. How can I approach it to solve the problem? error docker-training11-db-1 | 2021-11-09 05:14:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started. docker-training11-web-1 | Watching for file changes with StatReloader docker-training11-web-1 | Performing system checks... -
How to properly design django related model
I'm designing models base on a csv file: PATIENT ID,PATIENT NAME,EVENT TYPE,EVENT VALUE,EVENT UNIT,EVENT TIME 1,Jane,HR,82,beats/minute,2021-07-07T02:27:00Z 1,Jane,RR,5,breaths/minute,2021-07-07T02:27:00Z 2,John,HR,83,beats/minute,2021-07-07T02:27:00Z 2,John,RR,14,breaths/minute,2021-07-07T02:27:00Z 1,Jane,HR,88,beats/minute,2021-07-07T02:28:00Z 1,Jane,RR,20,breaths/minute,2021-07-07T02:28:00Z 2,John,HR,115,beats/minute,2021-07-07T02:28:00Z 2,John,RR,5,breaths/minute,2021-07-07T02:28:00Z 1,Jane,HR,66,beats/minute,2021-07-07T02:29:00Z 1,Jane,RR,15,breaths/minute,2021-07-07T02:29:00Z 2,John,HR,107,beats/minute,2021-07-07T02:29:00Z There are only 2 patients in this data, but the details of their HR and RR update every minute. This how I designed the model: from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class Event_type(models.Model): """ Event_type is like a category model for patient, datebase relationship is one to many """ name = models.CharField(max_length=40) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30, blank=True, null=True, verbose_name='patient_name') event_type = models.ForeignKey(Event_type, on_delete=models.CASCADE, blank=True, verbose_name='event type') event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=True, verbose_name='event time') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name However I guess while loading the data into database I may have the ununique error. Any better design ? Any friend can help? -
Django Session Form (save form temporarily)
I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page. So the flow will be like this : User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved) I want the form they have filled in automatically saved after they login. How to do that? My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code Can anyone explain a bit what a django session is like? and how to write code to handle this problem? -
Digital Ocean PWA Manifest Icons failing to fetch
I have my django pwa on digital ocean. I used django-pwa to convert to a pwa. My icons are failing to load. The path the manifest.json is my absolute path. But I have all my images and icons in a space on digital ocean, and for some reason, manifest is not trying to request the icons from that location. Can someone help me? -
Run idle using pen drive python
Is there a way to import libraries from one devices to another or any way to run python idle from pen drive to any other device -
Apache Airflow 2 does not execute the task after upgrading from 1.1
I upgraded to Airflow 2.0 today (docker) and since then, I am not able to execute any tasks (they fail successfully, but get stuck at the green with the below error). airflow_worker | airflow_worker | airflow_worker | airflow command error: argument GROUP_OR_COMMAND: celery subcommand works only with CeleryExecutor, your current executor: SequentialExecutor, see help above. airflow_worker | usage: airflow [-h] GROUP_OR_COMMAND ... airflow_worker | shows all the options here airflow_worker | -h, --help show this help message and exit airflow_worker exited with code 2 I used the standard docker-compose and made minor changes to suit my need. This is my docker-compose.yml version: '3' x-airflow-common: &airflow-common # In order to add custom dependencies or upgrade provider packages you can use your extended image. # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml # and uncomment the "build" line below, Then run `docker-compose build` to build the images. image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.2.1} # build: . environment: &airflow-common-env AIRFLOW__CORE__EXECUTOR: CeleryExecutor AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://xxx:xxx@db/xxx AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://xxx:xxx@db/xxx AIRFLOW__CELERY__BROKER_URL: redis://:redispass@redis:6379/1 AIRFLOW__CORE__FERNET_KEY: '' AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true' AIRFLOW__CORE__LOAD_EXAMPLES: 'false' AIRFLOW__API__AUTH_BACKEND: 'airflow.api.auth.backend.basic_auth' _AIRFLOW_WWW_USER_USERNAME: airflow _AIRFLOW_WWW_USER_PASSWORD: airflow _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-} volumes: - ./airflow/dags:/opt/airflow/dags - ./airflow/logs:/opt/airflow/logs - ./airflow/plugins:/opt/airflow/plugins user: "${AIRFLOW_UID:-1000}:0" depends_on: &airflow-common-depends-on redis: condition: service_healthy db: condition: service_healthy services: … -
DJANGO error. Reverse for 'receipt' with arguments '('',)' not found. 1 pattern(s) tried: ['receipt/(?P<pk>[^/]+)/$'] trying to use ID:PK
Lots going on here, the last row in inventory.Html is suppose to link to a product page using the id from PRODUCTS in views.py. I am trying to create a page for each product using the ID but the path isn't working. inventory.html code {% for i in items %} <tr> <td>{{i.Name_of_the_Material_per_specification}}</td> <td>{{i.Site_Material_Code }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'receipt' products.id %}">View</a></td> </tr> {% endfor %} RECIEPT.HTML <div class="col-md"> <div class="card card-body"> {% csrf_token %} {% for i in products %} <p>Name: {{products.Name_of_the_Material_per_specification}}</p> {% endfor %} </div> </div> URLS.PY from django.contrib import admin from django.urls import path, include from inventory import views urlpatterns = [ path('main', views.inventory, name='inventory'), path('receipt/<str:pk>/', views.products, name="receipt") views.py from django.shortcuts import render, HttpResponse from django.template import loader from django.shortcuts import redirect from .models import * from .forms import * # Create your views here. def inventory(request): items = materialForm.objects.all() return render(request, 'website/inventory.html', {'items': items}) def products(request, pk): products = materialForm.objects.get(id=pk) context = {'products':products } return render(request, 'website/receipt.html', context ) -
Testing custom action on a viewset in Django Rest Framework
I have defined the following custome action for my ViewSet Agenda: class AgendaViewSet(viewsets.ModelViewSet): """ A simple viewset to retrieve all the Agendas """ queryset = Agenda.objects.all() serializer_class = AgendaSerializer @action(detail=False, methods=['GET']) def get_user_agenda(self, request, pk=None): print('here1') id = request.GET.get("id_user") if not id: return Response("No id in the request.", status=400) id = int(id) user = User.objects.filter(pk=id) if not user: return Response("No existant user with the given id.", status=400) response = self.queryset.filter(UserRef__in=user) if not response: return Response("No existant Agenda.", status=400) serializer = AgendaSerializer(response, many=True) return Response(serializer.data) Here, I'd like to unit-test my custom action named "get_user_agenda". However, when I'm testing, the debug output("here1") doesn't show up, and it always returns 200 as a status_code. Here's my test: def test_GetUserAgenda(self): request_url = f'Agenda/get_user_agenda/' view = AgendaViewSet.as_view(actions={'get': 'retrieve'}) request = self.factory.get(request_url, {'id_user': 15}) response = view(request) self.assertEqual(response.status_code, 400) Note that: self.factory = APIRequestFactory() Am I missing something? Sincerely, -
Django Allauth TypeError at /accounts/confirm-email/
I'm using django-allauth for my django authentication and while confirming the email i get TypeError at /accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/ argument of type 'bool' is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/ Django Version: 3.2.9 Exception Type: TypeError Exception Value: argument of type 'bool' is not iterable Exception Location: /home/ali/.local/lib/python3.9/site-packages/django/shortcuts.py, line 136, in resolve_url Python Executable: /usr/bin/python Python Version: 3.9.7 Python Path: ['/home/ali/Projects/Jobs', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/ali/.local/lib/python3.9/site-packages', '/usr/lib/python3.9/site-packages'] Server time: Mon, 08 Nov 2021 13:56:20 +0000 as I searched answers were in the cause of using django-rest-allauth and here I'm not using any rest api and facing this issue. some configs in my settings.py file INSTALLED_APPS = [ ... # allauth "django.contrib.sites", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", "allauth.socialaccount.providers.facebook", "allauth.socialaccount.providers.twitter", "allauth.socialaccount.providers.telegram", "allauth.socialaccount.providers.instagram", "django_extensions", ... ] ... # all auth config AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ] SITE_ID = 1 # required to hand over an e-mail address when signing up ACCOUNT_EMAIL_REQUIRED = True # "optional" or "None" unverified email login allow ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_LOGIN_ON_PASSWORD_RESET = True SOCIALACCOUNT_PROVIDERS = { ... } -
HOW RO CODIFY IN VIEWS USING DJANGO CODE, AS I WANT TO PREVENT THE FURTHER UPDATE ALL ROW FIELDS OF POSTGRESQL TABLE BASED , IF ONE FIELD IS UPDATED
HERE IS MY MODELS CODE ''' `class defectrecord(models.Model): # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date=models.DateTimeField() natureofwork=models.CharField(max_length=100, null= True, blank=True) element=models.CharField(max_length=100, null= True, blank=True) defectobserved=models.CharField(max_length=500) repemployee=models.CharField(max_length=100) appemployee=models.CharField(max_length=100, blank=True) defappempremark=models.CharField(max_length=500, blank=True) defallocemp=models.CharField(max_length=100, blank=True) rectdetail=models.CharField(max_length=500, blank=True) rectdate=models.DateTimeField(null=True,blank=True) permit=models.BigIntegerField(null=True,blank=True) workcarried=models.CharField(max_length=500, blank=True) rectemployee=models.CharField(max_length=100, blank=True) rectappemployee=models.CharField(max_length=100, blank=True) rectappempremark=models.CharField(max_length=500, blank=True) image=models.ImageField(max_length=100, null= True, blank=True) class Meta: get_latest_by='id' ''' IF LAST 'OBJECT FIELD 'rectappempremark' IS UPDATED THEN SOME CODE IN VIEWS.PY TO PREVENT FURTHER UPDATE OF ALL MODELS FIELDS OF THAT PARTICULAR ROW (IDENTIFIED BY id). Above model contains save function and update functions based on permission code in views.py -
use for loop with JavaScript template literal function
I have a web app, frontend using normal HTML5, backend using Django. In the frontend page, I have a JavaScript template literal function. Which is supposed to render all the individual value into a selection box of a queryset passed from backend to a bootstrap table. view.py: def view_material(request): query_results_publisher = Publisher.objects.all() return render(request, 'material/index.html', context={'Publisher':query_results_publisher}) index.html(bootstrap table + javascript template literal function): ... <th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>... <script> var Publisher = "{{ Publisher }}"; var publisher = ''; function renderPublisher(value) { return `select style="width: 7em" name="" id=""> for (publisher in ${Publisher}) { <option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}> publisher</option>}</select>}` </script> But my for loop in javascript template literal function is not working, seems like I have some problem with the template literal usage in for loop. How to correct my function?