Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Anotation in Serializer not working correctly
suppose [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": false, "saved": false, "seen": false}, "liked": true, "saved": true, "seen": false}, ] How do i convert it to [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": true, "saved": true, "seen": false}, ] models class Post(models.Model): content = ... ... class SavedPost(models.Model): user = models.ForeignKey(User,...) post = models.ForeignKey(Post,...) class LikedPost(models.Model): user = models.ForeignKey(...) post = models.ForeignKey(Post,...) Serializer i am using class SavedPostSerializer(serializers.ModelSerializer): seen = serializers.BooleanField(default=True, read_only=True) liked = serializers.BooleanField(default=False, read_only=True) saved = serializers.BooleanField(default=True, read_only=True) post = PostSerializer(read_only=True) class Meta: model = SavedPost fields = ("folder", "post", "liked", "saved", "seen") view @login_required() def GetSavedPost(request): obj = SavedPost.objects.select_related("post").annotate( liked=Exists(LikedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))), saved=Exists(SavedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))) ).filter(user_id=request.user.id) serializer = SavedPostSerializer(obj, many=True) result = JsonResponse(serializer.data, safe=False) return result All i want is to show some anotation field using a defined serializer and extra field i.e. cs. Thanks in advance! -
Django override query set method
I am trying to override get_queryset in a django ViewSet class but I am getting a router error : extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' Here is my ViewSet class : class InvestmentViewSet(NestedViewSetMixin, ModelViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions for Investments. """ model = Investment serializer_class = InvestmentSerializer queryset = Investment.objects.all() def get_active_investment(self): """Get active investment Only One investment/startup is active """ queryset = Investment.objects.all() active = self.request.query_params.get('active') if active is True: queryset = queryset.filter(investment_status=active) return queryset Here is how I am calling it with router : from django.conf import settings from django.contrib import admin from django.urls import path, re_path from django.views.static import serve from rest_framework_extensions.routers import ExtendedSimpleRouter from back import views router = ExtendedSimpleRouter() ( router.register(r'api/startups', views.StartUpViewSet, basename='startup') .register(r'investments', views.InvestmentViewSet.get_active_investment, basename='startups_investment', parents_query_lookups=['startup']) ) urlpatterns = [ path('admin/', admin.site.urls), *router.urls, re_path(r'media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] -
Hosting Angular and Django on a VPS
I've already hosted my Django application on a VPS using gunicorn and Nginx. I created a config file for the Django app under /etc/nginx/sites-available/myapp and the app is running well on port 80. The below image is the config file regarding the Djagno app: Now, I want to run the Angular application on the same server. How can I do that taking in consideration that I already did a research on it and tried creating a config file for angular under /etc/nginx/sites-available/angular-app but failed? The below image is the config file regarding the Angular app: -
django.db.utils.OperationalError: foreign key mismatch - "businesses_activebusiness" referencing "businesses_business"
I have a Business class, I want to make an active business class that depends on the first class class Business(models.Model): name = models.CharField(max_length=50, primary_key=True,unique=True,default='new') label = models.CharField(max_length=50, blank=True, null=True) ripeningTimeInSeconds = models.IntegerField() requiredLevel = models.IntegerField() price = models.IntegerField() def __str__(self): return str(self.label) class ActiveBusiness(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None) id = models.AutoField(primary_key=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default=None) def __str__(self): return str(self.business.label) @property def ripeningDate(self): ripeningTimeInSeconds = self.business.ripeningTimeInSeconds now = datetime.datetime.now() result = now + datetime.timedelta(seconds = ripeningTimeInSeconds) return result Why can't I refer to the Business class? Where is the problem here? -
How to declare variable using loop in Python?
I just wanted to know how I can shorten my code using loop in python, can someone help me? Thanks! I'm using Python-flask. app.route('/data', methods=["GET", "POST"]) def data(): con = sqlite3.connect('tmonitor.db') con.row_factory = sqlite3.Row cur = con.cursor() cur.execute("SELECT * FROM monitors ORDER BY id DESC limit 1") rows = cur.fetchall() value = [row[1] for row in rows] //to split the array value1 = '-'.join(str(e) for e in value) value2 = value1.split('-') //Insert inside the loop to shorten the code Cell1_raw = value2[0] Cell2_raw = value2[1] Cell3_raw = value2[2] Cell4_raw = value2[3] Cell5_raw = value2[4] Cell6_raw = value2[5] Cell7_raw = value2[6] Cell8_raw = value2[7] Cell9_raw = value2[8] Cell10_raw = value2[9] // To convert in integer (Also need to shorten the code) Temperature1 = int(Cell1_raw) Temperature2 = int(Cell2_raw) Temperature3 = int(Cell3_raw) Temperature4 = int(Cell4_raw) Temperature5 = int(Cell5_raw) Temperature6 = int(Cell6_raw) Temperature7 = int(Cell7_raw) Temperature8 = int(Cell8_raw) Temperature9 = int(Cell9_raw) Temperature10 = int(Cell10_raw) // to shorten also data = [time() * 1000, Temperature1, Temperature2, Temperature3, Temperature4, Temperature5, Temperature6, Temperature7, Temperature8, Temperature9, Temperature10] response = make_response(json.dumps(data)) response.content_type = 'application/json' return response I added some comments for you to see what needs to be shorten, I'm still studying python, thank you so much! -
How can I get the previous instance of an object in Django templates, dynamically?
So I have a **model** which accumulates most of the other models to display a report. class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True) receivables=models.ForeignKey(Receivables, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True) As you can see, most of the fields are optional. filters.py class IpdFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name') package__patient_type__patient_type=django_filters.CharFilter(lookup_expr='icontains', label='Type of Patient') realization__amount_received__gt=django_filters.NumberFilter(field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received') realization__amount_received__lt=django_filters.NumberFilter(field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte') class Meta: model=IpdReport fields={ 'realization__cash':['exact'] } What I want is, when the context passes an instance to the template, the template should be able to access the previous instance containing the same patient in order for me to use it to display a particular text in one of the table-data based on the condition I put. I tried something like: views.py def ipd_report_view(request): report=IpdReport.objects.all().order_by('id') myFilter=IpdFilters(request.POST, queryset=report) report=myFilter.qs lst=[] temp_lst=[] for indie in report: prev=IpdReport.objects.filter(patient=indie.patient).order_by('id') print('prev ka value: ', prev) for chu in prev: if chu not in lst: lst.append(chu) ln=len(lst) for i in range(0, ln): if i not in temp_lst: temp_lst.append(i) pitch=prev[:ln-1] total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2, 'myFilter':myFilter, 'previous':lst, 'len':temp_lst, … -
Sign Up view test not passing [Django REST]
I'm trying to test the sign up view in Django using REST Framework but I'm getting an assertio error AssertionError: 201 != 400 when defining self.assertEqual(status.HTTP_201_CREATED, response.status_code). I'm not really sure where this error comes from so I'm asking for some help. Here is what I have: accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUser(AbstractUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(_('email address'), unique=True) def __str__(self): return self.email accounts/serializers.py from django.contrib.auth import get_user_model from django.core.validators import EmailValidator from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer import re def company_email_validation(email): pattern = r'(@gmail|@hotmail|@googlemail|@yahoo|@gmx|@ymail|@outlook|@bluewin|@protonmail|@online|@web|@online|@aol|@live)' return bool(re.search(pattern, email)) class UserSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) def validate(self, data): email_validator = EmailValidator() email_validator(data['email']) if (company_email_validation(data['email'])): raise serializers.ValidationError('You must use a company email') if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] data['email'] = validated_data['email'] return self.Meta.model.objects.create_user(**data) class Meta: model = get_user_model() fields = ( 'id', 'username', 'email', 'password1', 'password2', ) read_only_fields = ('id',) accounts/views.py from django.contrib.auth import get_user_model from rest_framework import generics from rest_framework_simplejwt.views import TokenObtainPairView from .serializers import UserSerializer, … -
How to create the foreign key relationship between Account and Post models on the model level, not on a database level?
I want to create the foreign key relationship between Account and Post models on the model level, not on a database level. I have created a custom account user, https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#custom-users-and-proxy-models The models are: Account : first_name, last_name, email, password, username Post : user, text, created_at, updated_at class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY) def has_module_perms(self, app_label): return True class Post(models.Model): user = models.CharField(max_length=30) text = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user -
Django rest framework POST nested serializer using action
I am new to django. I am having trouble with nested serializers. The nested serialization doesn't work as expected. when I am trying to create and post a new student, it does not create and post every thing and I got the following typeError: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() argument after ** must be a mapping, not str and I see the rest as following: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": {} } But the name of the student should be created too. it should be like this: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": { "first_name": "John" } } Can someone help me? In my serializers.py class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance in my views.py class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school_serializer = self.get_serializer(data=request.data) if school_serializer.is_valid(): school_serializer.save() else: return Response(status=status.HTTP_204_NO_CONTENT) -
Why we use JWT if we can use Redux for routes
Sorry for this question, I'm working in a project with React/Django/PostgreSQL, I realised a basic routes managing using Redux. I didn't understand what is the utility of Web Tokens, I want to use them in my project but for now I can see that I can do plenty premission things using Redux states. I really need to know some use cases for using Web Tokens for the whole projects. Thank you -
(421, b'Cannot connect to SMTP server, connect error 10061')
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command, python -m smtpd -n -c DebuggingServer localhost:1025 in order to test it. It intercepts with no problem, but I don't see anything in my inbox. Here is the settings.py file: EMAIL_HOST = '178.67.220.242' # My current ip address EMAIL_PORT = '587' # Port of the email host EMAIL_HOST_USER = 'b....a1@gmail.com' # Here is my actual email EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login EMAIL_USE_TLS = True EMAIL_USE_SSL = False Here is the views.py file: from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm def contact(request): form = ContactForm if request.method == 'POST': message_name = request.POST.get('name') message_email = request.POST.get('email') message = request.POST.get('message') send_mail(message_name, message, message_email, ['b....a1@gmail.com']) return render(request, 'contact.html', {'form': form}) Here is the error: Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\1\PycharmProjects\StasProject\sales_project\contact\views.py", line 15, in contact send_mail(message_name, message, message_email, ['badabuska1@gmail.com']) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\smtp.py", line … -
Django Rest Framework - How can I serialize a complex many-to-many object model with a custom table join?
I'm new to Django and Django REST Framework. I have a fairly complex relationship model, the intent is to have a shopping cart with many orders: class Product(models.Model): name = models.CharField(max_length=200) class Order(models.Model): title = models.CharField(max_length=200) items = models.ManyToManyField(Product, through='TableJoin') class TableJoin(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() I'm having trouble both using the ORM to pull a complete Order model (with relations), and to then serialize that. -
Heroku 500 internal error (due to postgres field errors?)
Im running an app on heroku that has a postgres db. I encountered a strange situation that whenever I pass in more than 50 characters inside the first field (title) of a ModelForm I get an Server Error (500) message and the app crashes. If the length of the input is 50 or less characters then the app works fine. I double checked that in models.py the CharField's max_lenght is more than 50 class Ad(models.Model): title = models.CharField(max_length=240) I also checked that the max character length is 240 in postgres /dt+ table desription Column | Type | Collation | Nullable | Default | Storage | Stats target | Description -----------------------+------------------------+-----------+----------+------------------------------------+----------+--------------+------------- id | integer | | not null | nextval('ads_ad_id_seq'::regclass) | plain | | category | text | | not null | | extended | | title | character varying(240) | | not null | | extended | | I haven't inputed any constraints on character lengths in the forms.py also. And what else is strange that in my local development env (also running on postgres) the app does not crash if I enter more that 50 characters in the title field. Both versions are tracked by git vc. Unfortunately the … -
django Error: Tried everything suggested by every website existing on google but still getting "The given username must be set"
I am working on user registration for an E-commerce Website I am not using any forms.py and there is no Indentation issue. I am passing simple JSON on postman on POST method to check if it is working or not, but I am getting errors. Below is my code and my error. I will be grateful for your help. My model.py from django.db import models from django.contrib.auth.models import AbstractUser import datetime class User(AbstractUser): created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username My View.py class Register(APIView): def post(self, request): username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') email = request.POST.get('email') if password == confirm_password: if Client.objects.filter(username = username).exists(): return Response({"message": "this username already exist"}) elif Client.objects.filter(email = email).exists(): return Response({"message": "This emaila address is already taken"}) else: user= Client.objects.create_user(username = username, password =confirm_password, email=email) user.save() else: return Response({"message": "Try it again"}, 404) My urls.py from django.urls import path from user_authentication.views import Login, Logout, Register urlpatterns = [ path('login/', Login.as_view()), path('logout/', Logout.as_view()), path('register/', Register.as_view()), ] Error--- Exception Value: The given username must be set Internal Server Error: /register/ Traceback (most recent call last): File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response … -
List liked post in django
Suppose class Post(models.Model): content = models.CharField(...) image = models.ImageField(...) class PostLike(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) class PostSave(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) How do i list all the liked post in serializers with fields ["content","image","liked","saved"] ? Here liked will be true for all as the list is coming from liked posts. And saved will be true if request.user and post_id in PostSave. view def getLikedPost(request): obj = # Get all the liked post serializer = CustomSerializer(obj.,many=True) result = JsonResponse(serializer.data, safe=False) Help me in completing view and serializer Thanks in Advance! -
Internal Server Error (500) showing on sub-routes when running Django on server
I'm hosting my Django application on a VPS and I'm using Django Rest Framework and the Django Admin Site. Everything seemed working running fine (check the below image), but when I try to click on my API's I'm redirected to a Server Error (500) page. One thing to notice is that when I'm running the app locally on my machine everything is working fine. Below is my settings.py if it can help in anyway: Django settings for thepatron project. Generated by 'django-admin startproject' using Django 3.2.4. 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 import os import django_heroku import datetime from dotenv import load_dotenv # Initialize environment variables load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! try: SECRET_KEY = str(os.getenv('SECRET_KEY')) except KeyError as e: raise RuntimeError("Could not find a SECRET_KEY in environment") from e # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ # VPS '194.5.159.80', # … -
Schedule emails on a specific time using Django and celery
This is the use case I am looking for : User will register on my application It is a note making and remainder application While creating remainder users will enter the time my application wants to send user an email at that time I have to use celery for the same I read several posts and stack overflow answers but didn't get proper answer for the same. My application is written in Django. -
Django + ElasticSearch + Docker - Connection Timeout no matter what hostname I use
I'm having issues connecting with my Elasticsearch container since day 1. First I was using elasticsearch as the hostname, then I've tried the container name web_elasticsearch_1, and finally I'd set a Static IP address to the container and passed it in my configuration file. PYPI packages: django==3.2.9 elasticsearch==7.15.1 elasticsearch-dsl==7.4.0 docker-compose.yml version: "3.3" services: web: build: context: . dockerfile: local/Dockerfile image: project32439/python command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" env_file: - local/python.env depends_on: - elasticsearch elasticsearch: image: elasticsearch:7.10.1 environment: - xpack.security.enabled=false - discovery.type=single-node networks: default: ipv4_address: 172.18.0.10 settings.py # Elasticsearch ELASTICSEARCH_HOST = "172.18.0.10" ELASTICSEARCH_PORT = 9200 service.py from django.conf import settings from elasticsearch import Elasticsearch, RequestsHttpConnection es = Elasticsearch( hosts=[{"host": settings.ELASTICSEARCH_HOST, "port": settings.ELASTICSEARCH_PORT}], use_ssl=False, verify_certs=False, connection_class=RequestsHttpConnection, ) traceback HTTPConnectionPool(host='172.18.0.10', port=9200): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7f1973ebd6d0>, 'Connection to 172.18.0.10 timed out. (connect timeout=5)')) -
Django asgi Single thread executor already being used, would deadlock deployment error
my run command for django asgi application using gunicorn looks like this: gunicorn -b '0.0.0.0:8000' myproject.asgi:application -w 4 -k uvicorn.workers.UvicornWorker --access-logfile /logs/access.log --access-logformat "%(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s" >> /logs/error.log When I try to access any endpoint of the application, I get Single thread executor already being used, would deadlock error. I am using following package versions: Django=3.2.4 asgiref==3.4.0 uvicorn==0.15.0 gunicorn==20.1.0 -
Django star rating system AJAX and JavaScript
I am trying to implement a star rating system on a Django site. I have found the following, and like the style of the stars here: https://www.w3schools.com/howto/howto_css_star_rating.asp Currently have a limited understanding of JavaScript, AJAX and Django. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating? It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. For this, there must be an IP check. I am confused about the code and I need help. models.py: class Rating(models.Model): ip = models.CharField(max_length=15) post = models.ForeignKey(Post, related_name='ratings', on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) views.py: def RatingView(request): obj = Rating.objects.filter(score=0).order_by("?").first() context ={ 'object': obj } return render(request, 'blog/post_detail.html', context) # def get_client_ip(self, request): # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') # if x_forwarded_for: # ip = x_forwarded_for.split(',')[0] # else: # ip = request.META.get('REMOTE_ADDR') # return ip def RateView(request): if request.method == 'POST': element_id = int(request.POST.get('element_id')) val = request.POST.get('val') print(val) obj = Rating.objects.get(id=element_id) obj.score = val obj.save() return JsonResponse({'success':'true', 'score': val}, safe=False) … -
Pass video uploaded via django to cv2
I am uploading video via django and want to process it using cv2. This is how video uploaded via django is accessed. video_obj = request.FILES['file_name'] Next i want to pass it to opencv. I dont want to save video in disk first and then acess it via cv2 using following code cap = cv2.VideoCapture(vid_path) I tried passing this video_obj to VideoCapture this way video_obj = request.FILES['file_name'] cap = cv2.VideoCapture(video_obj) But i got following error Can't convert object of type 'TemporaryUploadedFile' to 'str' for 'filename' VideoCapture() missing required argument 'apiPreference' (pos 2) -
Django: Foreign Key to User -> Form is not validating because field is required
I'm currently creating a Registration-Page with two parts One part is about the Username and a Passwort. The second part is about choosing the own PC-Configuration After defining everything, the User can register to get to the Main-Page. Therefore I got a Model called "PC_Configuration" with a bunch of Foreign-Keys to the different Database-Models of the Processors/Graphicscards etc.: class PC_Configuration(models.Model): user = models.ForeignKey(User, related_name='user_id', on_delete=models.DO_NOTHING) processor = models.ForeignKey(Processors, related_name='processor_id', on_delete=models.DO_NOTHING) graphicscard = models.ForeignKey(Graphicscard, related_name='graphicscard_id', on_delete=models.DO_NOTHING) os = models.ForeignKey(OS, related_name='os_id', on_delete=models.DO_NOTHING) ram = models.ForeignKey(RAM, related_name='ram_id', on_delete=models.DO_NOTHING) harddrive = models.ForeignKey(Harddrive, related_name='harddrive_id', on_delete=models.DO_NOTHING) Also, there is one ForeignKey to the User to connect the Configuration to the respective User-ID. Inside views.py, I've been creating a DropdownForm for all the Dropdown-Fields which the User shall choose on his own: class DropdownForm(forms.ModelForm): class Meta: model = models.PC_Configuration exclude = [] def __init__(self, *args, **kwargs): super(DropdownForm, self).__init__(*args, **kwargs) self.fields['processors'].queryset = DropdownForm.objects.all() self.fields['processors'].label_from_instance = lambda obj: "%s" % obj.name self.fields['graphicscard'].queryset = DropdownForm.objects.all() self.fields['graphicscard'].label_from_instance = lambda obj: "%s" % obj.name self.fields['os'].queryset = DropdownForm.objects.all() self.fields['os'].label_from_instance = lambda obj: "%s" % obj.name self.fields['ram'].queryset = DropdownForm.objects.all() self.fields['ram'].label_from_instance = lambda obj: "%s" % obj.name self.fields['harddrive'].queryset = DropdownForm.objects.all() self.fields['harddrive'].label_from_instance = lambda obj: "%s" % obj.name But regarding the fact, that the User-ID shall … -
Blank page showing in django server after adding python in index.html file
please help i'm following a tutorial and not showing desierd output in the server page. Every thing was going smoothly until the index.html page content not shown This is my index.html file <!DOCTYPE html> <html lang="eng"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script> <title>document</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <div class="container"> <div class="row"> **{% for Product in product_objetcs %}** <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> **{{ product.tittle }}** </div> <div class="card-text"> **{{ product.price }}** </div> </div> </div> **{% endfor %}** </div> </div> </div> </body> </html> this is my views page from django.shortcuts import render from.models import Product # Create your views here. def index(request): product_objects = Product.objects.all() return render(request, models "my models page looks like this" from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() discount_price = models.FloatField() category = models.CharField(max_length=200) description = models.TextField() image = models.CharField(max_length=300) -
How to setup Openwisp-radius with Django
Hello kindly help with is error, i am trying to get started with openwisp-radius with django project. after setting up my django project with openwisp radius when i run py manage.py migrate i run into this error Applying openwisp_radius.0013_remove_null_uuid_field...Traceback (most recent call last): django.db.utils.OperationalError: (1280, "Incorrect index name 'nas_uuid_694a814a_uniq'") -
django (errno: 150 "Foreign key constraint is incorrectly formed")')
recently when in want to migrate my model I encountered this error in django: "(errno: 150 "Foreign key constraint is incorrectly formed")')" class PartCategory(models.Model): name=models.CharField("نام",max_length = 50) code=models.CharField("کد",max_length = 50,unique=True) description=models.CharField("توضیحات",max_length = 50) priority=models.IntegerField("اولویت", null=True) isPartOf = models.ForeignKey('self',on_delete=models.CASCADE,verbose_name="زیر مجموعه",null=True,blank=True) def __str__(self): return self.name class Meta: db_table = "partcategory"