Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to change time format to naturally in a queryset
This is the model: class Comment(models.Model): """ 评论表 """ nid = models.AutoField(primary_key=True) news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE) user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE) content = models.CharField(verbose_name='评论内容', max_length=255) create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) parent_comment = models.ForeignKey('self', null=True, on_delete=models.CASCADE) def __str__(self): return self.content This is the view: def get_comment_tree(request): news_id = request.GET.get("news_id") ret = list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id",'create_time',username=F('user__username'))) return JsonResponse(ret, safe=False) My question is ,how to convert the create_time to human time like "5 minute ago" in django? -
Dockerize Django project with MySQL container
I have a very simple Django project (v.2.2) with Python (v.3.6.9), Docker (v.20.10.3), and docker-compose (v. 1.28.4) running on Ubuntu 18.04. I'm trying to dockerize Django project with MySQL container. I did all the migrations and have the .sql file of my database. The project works fine without Docker, however, when I run docker-compose up I got the following error: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") Here's my full configuration: https://github.com/aziele/docker-django-mysql Briefly, this is my Dockerfile: FROM python:3.6.9 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt WORKDIR /app And these my requirements.txt: Django==2.2 mysqlclient==2.0.3 django-mysql The docker-compose.yml file: version: '3' services: db: image: mysql:5.7.33 restart: unless-stopped environment: MYSQL_DATABASE: 'projectdb1' MYSQL_USER: 'user' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' volumes: - ./db/projectdb1.sql:/docker-entrypoint-initdb.d/projectdb1.sql ports: - '3307:3306' django: build: context: . dockerfile: ./Dockerfile-dev volumes: - ./src:/app command: python manage.py runserver 0.0.0.0:8000 ports: - 8080:8000 restart: always depends_on: - db Also I have change the database configurations in settings.py for this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectdb1', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '3307', } } -
How to test external POST call that receives query parameters as arrays instead of single values?
Has anybody successfully managed to write tests for a Paddle webhook in a Django application? Paddle sends messages as POST requests to a webhook. According to Paddle's webhook testing an exemplary request looks like this: [alert_id] => 1865992389 [alert_name] => payment_succeeded [...] => ... The webhook at my Django application receives this as the request.POST=<QueryDict> parameter: {'alert_id': ['1865992389'], 'alert_name': ['payment_succeeded'], '...': ['...']} That is, all values are received as arrays, not values. Contrary, my webhook test looks like the message format I would expect, i.e. uses values instead of arrays: response = client.post('/pricing/paddlewebhook/', {'alert_name': 'payment_succeeded', 'alert_id': '1865992389', '...': '...', }, content_type='application/x-www-form-urlencoded') assert response.status_code == 200 # Match paddle's expectation This is received by the webhook as request.POST=<QueryDict> parameter: {'alert_name': 'payment_succeeded', 'alert_id': '1865992389', '...': '...'} The webhook itself is a simple POST method of a class-based view: # Django wants us to apply the csrf_exempt decorator all methods via dispatch() instead of just to post(). @method_decorator(csrf_exempt, name='dispatch') class PaddleWebhook(View): def post(self, request, *args, **kwargs): logger.info("request.POST=%s", request.POST) # ... Is it really suitable testing behaviour to change the test (and the view's post()) to include array values or am I missing something obvious about external calls to POST webhooks? -
The empty path didn't match any of these:
i am using python 3.8 and getting error when i launch server: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in djangoProject.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my polls/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] my djangoProject/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url("polls/", include('polls.urls')), url("admin/", admin.site.urls), ] -
Why don't my CSS static files work in Django when I pass an optional parameter to the view?
I am making an application in Django, where I have a main (index) page displaying a number of objects styled with CSS. The CSS is in a static file. When I do not pass any parameters to the index view in views.py, all the CSS renders great. However, whenever I pass in an extra parameter to the view url, no CSS is applied (but the information gets displayed correctly). Please can someone help me with this? settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "auctions/static") STATICFILES_DIRS = [os.path.join(BASE_DIR, "auctions/static")] urls.py (app): urlpatterns = [ path("categories", views.categories, name="categories"), path("", views.index, name="index"), **path("category/<str:cat_name>", views.index, name="index"),** path("create_listing", views.create_listing, name="create"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("<int:id>", views.view_listing, name="view"), path("watchlist", views.watchlist, name="watchlist") ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT Template: {% load static %} <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> views.py: def index(request, cat_name=None): if cat_name is not None: listings = Listing.objects.filter(category=cat_name) listings = listings.filter(bid_active=True) else: listings = Listing.objects.filter(bid_active=True) return render(request, "auctions/index.html", { "listings": listings }) Basically, the view works if I don't enter the extra parameter (but I have to in order to avoid redundancy in my code). -
Django REST - How do I correctly configure URLs lookup_field?
I've made a few django projects and am now experimenting with the rest framework. I'm trying to configure my urls such that url /testuser/ will take you to the profile page of user with username 'testuser'. Pretty simple task that I can manage in regular django using slug_field but I guess I'm not quite understanding how to correctly configure REST urls. Any help appreciated. Code below. FYI, as you will see below, I am using a CustomUser model, linked to a Profile model by OneToOneField. The username is stored in the CustomUser model. However, the profile page will be populated using ProfileSerializer. I believe the issue might be the way I am accessing the 'username' from the related model, CustomUser - but I could be wrong (likely, lol). Anyone have any idea? My current code throws the error: Expected view ProfileView to be called with a URL keyword argument named "username". Fix your URL conf, or set the .lookup_field attribute on the view correctly. users.models class CustomUser(AbstractBaseUser): username = models.CharField( verbose_name='username', max_length=40, unique=True, ) ... profiles.models class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile' ) ... profiles.serializers class ProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(read_only=True, source="user.username") class Meta: fields = ('username', 'display_name', 'profile_pic', … -
Async View in Django
Working on a django app that depends on a payment API, the app has to redirect based on response from user's phone input which takes a while, is there a way to use async to wait for the user's input before running the rest of the code. I would like for the code to run only once it gets the response as shown in the function below. Any help would be appreciated. class CallBack(TemplateView): template_name = 'callback.html' def get(self, request): response = json.loads(request.body.decode('utf-8')) result_code = response["Body"]["stkCallback"]["ResultCode"] if result_code == 0: merchant_request_id = response["Body"]["stkCallback"]["MerchantRequestID"] checkout_request_id = response["Body"]["stkCallback"]["CheckoutRequestID"] result_code = response["Body"]["stkCallback"]["ResultCode"] amount = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] mpesa_receipt_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] transaction_date = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] phone_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] str_transaction_date = str(transaction_date) transaction_datetime = datetime.strptime( str_transaction_date, "%Y%m%d%H%M%S") aware_transaction_datetime = pytz.utc.localize( transaction_datetime) our_model = Mpesa.objects.create( CheckoutRequestID=checkout_request_id, MerchantRequestID=merchant_request_id, PhoneNumber=phone_number, MpesaReceiptNumber=mpesa_receipt_number, Amount=amount, ResultCode=result_code, TransactionDate=aware_transaction_datetime, ) our_model.save() return redirect('realtor:create') else: return redirect('payments:lipa_na_mpesa') -
Django Static Files Compression and Google Cloud Run
Django app is hosted on Google Cloud Run. That requires to store static files on Cloud Storage. They're collected automatically during the build with collectstatic command. It suits for me, but I'd like to optimize page load, so first I need to minify css/js resources, like whitenoise library does. How to implement compressing + minifying before uploading to GCS and handle .min. resources without significant changes (as using 'whitenoise')? I'm using django-storages package -
how to read 401 unautherized response in react
My django api responds with the username if the user is authenticated and a not authenticated details msg if not authenticated but i am unable to read the status code or console log or catch the 401 status code and response.status gives undifined msg console img how can i use http status to render depending on the code recived . export default class GetUser extends Component { constructor(props) { super(props); this.state={ data : [],} } componentDidMount(){ fetch("http://127.0.0.1:8000/app/ebooks/", { credentials: 'include', method: 'GET', mode: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': CSRF_TOKEN }, }) .then(response => response.json()) .then(response => { this.setState({data:[response]}) console.log(response.status) --->UNDIFINED }) .catch(err => console.log(err)); } render() { var x = this.state.data return ( <pre>{JSON.stringify(x, null, 2) }</pre> ) } } -
How to change Datetime field with queryset in Django
this is the class class Post(models.Model): author = models.ForeignKey(User) . . last_seen = models.DateTimeField(auto_add = True) I want to change last_seen time with another time in the future last_seen = Post.objects.get(author = user).last_seen if request.user.is_authenticated: last_seen = timezone.now() when I run print(last_seen) I find it does not change and still an old datetime value what's the wrong? -
Should I use docker or virtual env for my production level django project (to be hosted)
I am new to backend development and having some serious doubts which I am unable to clear. I am going to work on some production level djangoRestFramework project and I learned it by creating a virtual environment. Now I have come across this Docker thing. Now I can say that this provided OS-level abstraction to our project. But which I should use, docker or virtualenv? and why? The same project I want to deploy at someplace and what will be the benefits if I am using docker tr virtualenv? Thanks -
Django / better way to make follow model and get follower and following list
my code views class FollowView(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): follow_from = request.user follow_to_username = request.POST.get('follow_to') follow_to = get_object_or_404(User, username=follow_to_username) try: follow_obj = Follow.objects.get(follow_from=follow_from, follow_to=follow_to) follow_obj.delete() except Follow.DoesNotExist: follow_obj = Follow.objects.create(follow_from=follow_from, follow_to=follow_to) return redirect(request.META.get('HTTP_REFERER')) model class Follow(models.Model): follow_from = models.ForeignKey( User, related_name='following', on_delete=models.CASCADE) follow_to = models.ForeignKey( User, related_name='follower', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.follow_from} follows {self.follow_to}" template of user profile <div class="card-body"> <p> {{ object.user }} </p> <p> {{ object.state_message }}</p> <p> following </p> {% for follow in object.user.following.all %} <p> {{ follow.follow_to }}</p> {% endfor%} <br> <p> followers </p> {% for follow in object.user.follower.all %} <p> {{ follow.follow_from }}</p> {% endfor%} </div> when i try to get one user's followers and following users {% for follow in object.user.following(or follower).all %} like this i have to use ".follow_to" or ".follow_from" once more This way is a bit confusing to use. What i want is get "one user's follower" and "one user's following" using just keyword 'followers', and 'following'. Should i try different way of making follow model? please give me advice or idea. -
RelatedObjectDoesNotExist at /teacher/class_students_list
Views.py #For Student Registration def StudentSignUp(request): user_type = 'Student' registered= False if request.method == "POST": logger_Form = loggerform(data = request.POST) Student_Form = StudentForm(data = request.POST) if logger_Form.is_valid() and Student_Form.is_valid(): user = logger_Form.save() user.is_student = True user.save() profile = Student_Form.save(commit=False) profile.user = user profile.save() registered = True else: print(logger_Form.errors,Student_Form.errors) else: logger_Form = loggerform() Student_Form = StudentForm() return render(request,'student_signup.html',{'logger_Form':loggerform,'Student_Form':StudentForm,'registered':registered,'user_type':user_type}) # FOR teacher Registration def TeacherSignUp(request): user_type = 'Teacher' registered = False if request.method == "POST": logger_Form = loggerform(data = request.POST) Teacher_Form = TeacherForm(data = request.POST) if logger_Form.is_valid() and Teacher_Form.is_valid(): user = logger_Form.save() user.is_teacher = True user.save() profile = Teacher_Form.save(commit=False) profile.user = user profile.save() registered = True else: print(logger_Form.errors,Teacher_Form.errors) else: logger_Form = loggerform() Teacher_Form = TeacherForm() return render(request,'teach_signup.html',{'logger_Form':loggerform,'Teacher_Form':TeacherForm,'registered':registered,'user_type':user_type}) #List of all the students that teacher has added in their class def class_students_list(request): query = request.GET.get("q", None) students = StudentsInClass.objects.filter(teacher = request.user.Teacher) students_list = [x.student for x in students] qs = Student.objects.all() if query is not None: qs = qs.filter( Q(name__icontains=query) ) qs_one = [] for x in qs: if x in students_list: qs_one.append(x) else: pass context = { "class_students_list": qs_one, } template = "class_students_list.html" return render(request, template, context) class ClassStudentsListView(LoginRequiredMixin,DetailView): model = models.Teacher template_name = "class_students_list.html" context_object_name = "teacher" Models.py class logger(AbstractUser): is_student … -
Unable to send mail using django PasswordResetView?
I've used django's User model for authentication, now I am doing password reset for my project, User is not getting any email but in terminal I am getting this message, and I am doing all of these in my local computer In my terminal You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000. Please go to the following page and choose a new password: http://127.0.0.1:8000/accounts/reset/Mg/aisdmr-bd229ea69f64a159ed5c744816b02ca3/ Your username, in case you’ve forgotten: xxxxx Thanks for using our site! The 127.0.0.1:8000 team In my urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', views.SignUp.as_view(), name='signup'), path('user/<int:pk>/', views.UserList.as_view(template_name='accounts/about_user.html'), name='about_user'), path('reset_password/',auth_views.PasswordResetView.as_view(), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] In settings.py # SMTP configuration EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USER_TLS = True EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password' I've also enabled this in my EMAIL_HOST_USER -
Extended user model with encrypted or hashed email as usermane
in this previus link : Django User model with encrypted and hashed email as username Appear the user find a way to that but the answers is not clear, I am trying to be compliant with GDRP too, but I cannot find the way to achieve it , I really appreciate any people that provide to me any information in order to know how you solve it. My case: I am using the cryptography.fernet to encrypt and decrypt the email field and using my own filetype to encrypt and decrypt the information from and to DB and the same time I create my own backend authentication in order to handle the authentication via email. The problem is when you are using your own authentication backend in order to find the email into the User DB I need to convert the email received like an encrypted field, of course when I use again the encrypt function this encryption is complete difference that already are into the DB. bellow part of code: function.py def encrypt(txt ): try: # convert integer etc to string first txtadvance=(str(txt)).translate(str.maketrans('', '', ' \n\t\r')) #txt = str(txt) txt = txtadvance # get the key from settings cipher_suite = … -
django a want show the user is login added any
I have a model class orders5(models.Model): uesr = models.ForeignKey(User,on_delete=models.CASCADE, null=True) names = models.CharField(max_length=50) i want show the user ligin add any -
TemplateDoesNotExist at / blog/home.html, blog/post_list.html
I am trying to deploy my project on heroku but getting error:TemplateDoesNotExist at / blog/home.html, blog/post_list.html.But every thing is working fine on my local server.In 'blog' app i have 'Template' directory and inside that i have 'blog' directory which contains 'home.html'. Any suggestion,please. -
Problem in integrating Paho Python MQTT Client with Django 3.1
from this SO question, I implemented a subscriber client in my Django project as following: in mqtt.py, I create a client and connect to a local broker and subscribe to a topic. #myapp/mqtt.py: import paho.mqtt.client as paho import django import json django.setup() from .models import Temperature, Turbidity, Refined_fuels, Crude_oil from datetime import datetime # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("CONNACK received with code %d." % (rc)) client.subscribe("sensor/temp", qos=0) def on_subscribe(client, userdata, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+", "+'QOS: ' +str(msg.qos)+",\n"+str(msg.payload, 'utf-8')) message_dict = json.loads(msg.payload) now = datetime.now() captured_timestamp = datetime.utcfromtimestamp(int(message_dict['Timestamp'])).strftime('%Y-%m-%d %H:%M:%S') print('timestamp: ', captured_timestamp ) if message_dict['Temperature'] and message_dict['D850'] and message_dict['D280']: temp = Temperature(captured_timestamp=captured_timestamp, data=message_dict['Temperature'], received_timestamp=now) temp.save() refined_fuels = Refined_fuels(captured_timestamp=captured_timestamp, data=float(message_dict['D850']), received_timestamp=now) refined_fuels.save() crude_oil = Crude_oil(captured_timestamp=captured_timestamp, data=float(message_dict['D280']), received_timestamp=now) crude_oil.save() # defining client client = paho.Client(client_id="testSubscriber", clean_session=True, userdata=None, protocol=paho.MQTTv311) # adding callbacks to client client.on_connect = on_connect client.on_subscribe = on_subscribe client.on_message = on_message client.connect(host="localhost", port=1883, keepalive=60, bind_address="" ) in __init__.py I call the loop_start() of client: # myapp/__init__.py from . import mqtt mqtt.client.loop_start() now, When I run Django server(python manage.py runserver), … -
Django poll models choice, how change my models?
I am new in django and i need some helps. I just can't figure out the situation, since I have little experience in django, perhaps this question is too simple but not for me. I wrote a survey with the ability to choose one option, but I do not know how to add the option of a text response, an answer not only with a choice of one option, an answer with a choice of several options models.py class Poll(models.Model): title = models.CharField(max_length=200) question = models.TextField() option_one = models.CharField(max_length=50) option_two = models.CharField(max_length=50) option_three = models.CharField(max_length=50) option_input = models.CharField(max_length=50, null=True, blank=True) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) active_from = models.DateTimeField(auto_now_add=True, null=True) active_for = models.IntegerField(default=0) views.py def create(request): if request.method == 'POST': form = CreatePollForm(request.POST) if form.is_valid(): form.save() return redirect ('home') else: form = CreatePollForm() context = {'form':form} return render(request, 'poll/create.html', context) def update_vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) form = CreatePollForm(instance=poll) if request.method == 'POST': form = CreatePollForm(request.POST, instance=poll) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'poll/create.html', context) def delete_vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.method == 'POST': poll.delete() return redirect('home') context = {'poll': poll} return render(request, 'poll/delete_votting.html', context) def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) … -
Django FormSet Two Table
I have two tables, staff and salary. A salary table will be created for all staff every month. and will be listed one under the other. like django admin editable : django admin but one to many will not choose, will be side by side example: here "No selection will create its own by date. and I can edit right next to the staff" Personel name---Bodro editable text class Personel(models.Model): ad = models.CharField(blank=True,null=True, max_length=50) soyad = models.CharField(blank=True,null=True, max_length=50) netmaas = models.DecimalField(blank=True,null=True,max_digits=10, decimal_places=3) gorev = models.CharField(blank=True,null=True, max_length=50) tc = models.CharField(blank=True,null=True, max_length=11) telefon = models.CharField(blank=True,null=True, max_length=12) aktif = models.BooleanField(verbose_name='Aktif', default=True) aciklama = models.CharField(blank=True,null=True, max_length=100) class Bodro(models.Model): netmaas = models.DecimalField(blank=True,null=True,max_digits=10, decimal_places=3) cgsmaas = models.IntegerField(blank=True,default=30) fm = models.DecimalField(blank=True,max_digits=10, decimal_places=3) rtc = models.DecimalField(blank=True,max_digits=10, decimal_places=3) htc = models.DecimalField(blank=True,max_digits=10, decimal_places=3) dbc = models.DecimalField(blank=True,max_digits=10, decimal_places=3) bes = models.DecimalField(blank=True,max_digits=10, decimal_places=3) ekkesinti = models.DecimalField(blank=True,max_digits=10, decimal_places=3) eködeme = models.DecimalField(blank=True,max_digits=10, decimal_places=3) agi= models.DecimalField(blank=True,max_digits=10, decimal_places=3) hakedis= models.DecimalField(blank=True,max_digits=10, decimal_places=3) personel = models.ForeignKey('Personel', on_delete=models.CASCADE) -
comparing a model field with choices to a string
Struggling a bit with something that should work and can't figure out why it doesn't. I'm using Django 3.1.5, Python 3.9.1 Simplified version: addresses/models.py: SHIPPING_CHOICES = ( ('standard', '$4.50 > 2-5 business days'), ('tracked ', '$5.50 > 2-5 business days'), ('rural', '$8.50 > 3-6 business days'), ) class Address(models.Model): shipping_option = models.CharField(max_length=120, default='standard', choices=SHIPPING_CHOICES) orders/models.py class Order(models.Model): shipping_address = models.ForeignKey(Address, related_name="shipping_address", null=True, blank=True, on_delete=DO_NOTHING) def update_total(self): if self.shipping_address is not None: if self.shipping_address.shipping_option == "tracked": shipping_total = 5.50 Problem is that the comparismant if self.shipping_address.shipping_option == "tracked": never gives true when I choose tracked as the shipping option in this example. From reading other questions I know that "is" would be wrong here to use and it can only be "==" for the two strings. I've checked the type of "self.shipping_address.shipping_option" output and did print to double check the value that comes trough is the same as in the if clause. Thoughts on what could be going here? -
Is there a way to control video from web cam in Django?
I have to deploy a machine learning model which will process the video coming from the user's camera and we have to process on the model's predictions. I want to give user the ability to control for how long the model will input/ take the video feed from the camera like some kind of button which can provide that service. For now, I am able to do prediction on the video feed but it is continuous like for every frame and I am returning that frame to the front end with StreamingHttpResponse but the problem in StreamingHttpResponse is I don't have any idea on how to include any controls(stop, continue prediction) in the application. I am open to suggestions if there is any other way to achieve this other than StreamingHttpResponse or if it is possible with StreamingHttpResponse please guide me in the proper direction view functions that allow the streaming capability def gen(camera): while True: frame = cam.get_frame() # print(frame) m_image, lab =predict_video(frame, "result") print(lab) # m_image = cv2.cvtColor(m_image, cv2.COLOR_RGB2BGR) ret, m_image = cv2.imencode('.jpg', m_image) m_image = m_image.tobytes() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + m_image + b'\r\n\r\n') def livefeed(request): try: return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") except Exception as e: # This is bad! … -
How to assign value into string base ForeignKey?
I have to get value from foreign key based Modal but i have the foreign key is like dynamically changed from modal to modal. this is my code def get_object(self, queryset=None): data = self.model.objects.filter(pk=queryset) fk = self.fk_name + '_id' inline_data = self.inline_model.objects.filter(#fk_name=queryset) #fk_name please help me solving this. -
Relations between abstract models in Django
Is there any way to create base abstract models and implement some kind of fake relations between them instead of re-defining the same relations in each inherited real models? I've made this models.py for testing purposes: from django.contrib.contenttypes.models import ContentType from django.db import models class BaseSource(models.Model): source_field = models.CharField(max_length=10, null=True) source_field1 = models.IntegerField(default=0) pointers = GenericRelation('BasePointer') class Meta: abstract = True def print_pointers(self): for pointer in self.pointers.all(): print(pointer.pointer_field) class BasePointer(models.Model): pointer_field = models.CharField(max_length=10, null=True) class Meta: abstract = True source_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) source_id = models.PositiveIntegerField() source = GenericForeignKey(source_type, source_id) class Source(BaseSource): pass class Source2(BaseSource): pass class Pointer(BasePointer): source = models.ForeignKey(Source, related_name='pointers', on_delete=models.CASCADE) class Pointer2(BasePointer): source = models.ForeignKey(Source2, related_name='pointers', on_delete=models.CASCADE) The reason is to provide a way to switch current models (Source+Pointer and Source2+Pointer2) depending on user's choice, models will be mostly the same with minor differences, so I don't want to make them completely different classes. Most fields and logic are described in base abstract models, and real models are using different tables in database, views will be determining current models set and provide specific context variables, if needed. The problem is relations between those models: example method - print_pointers, which uses non-declared field self.pointers. I've tried declaring GenericRelation('BasePointer') … -
stripe update subscription python
I have three stripe plans (free, normal, premium) defined. When a user wants to upgrade (e.g. from normal to premium user), then the user should get a new subscription with the premium plan. This is my code so far: subscription = stripe.Subscription.modify( id=stripe_subscription_id, items=[ { 'plan': stripe_plan_id, } ], ) In the docu there is no need for another required argument. But I get this error: modify() missing 1 required positional argument: 'sid' Does somebody know what this parameter means and where do I place it in the code?