Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django sql server studio backend doesn't support altering from/to AutoField
Please help me I tried to connect to the database The connection was successful and the rules were lifted, but I have this problem raise NotImplementedError("the backend doesn't support altering from/to %s." % t.name) NotImplementedError: the backend doesn't support altering from/to AutoField. Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying profiles.0001_initial... OK Applying goals.0001_initial...Traceback (most recent call last): File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\li Apply all migrations: account, admin, auth, contenttypes, goals, notifications, profiles, sessions, sites, socialaccont Running migrations: Applying goals.0001_initial... OK Applying goals.0002_approvedgoals... OK Applying goals.0003_auto_20210928_1206... OK Applying goals.0004_goal_cer... OK Applying goals.0005_auto_20211027_1918...Traceback (most recent call last): -
Django Parameters in URL from POST Request
I'm trying to create a search bar in Django, where users can enter a value to search for, click enter / search button, and then the url redirects to https:localhost:3000/usearch/abc, if they for example search for abc. This is URL paramter can always change based on the search, and it should send the parameter to the views.py file to be processed, though I can't get it to work. urls.py urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path('usearch/', views.usearch, name='usearch'), path('usearch/<str:query>', views.usearch_query, name='usearch_query' ] views.py def usearch(request): return render(request, 'myapp/usearch.html') def usearch_query(request, query): context = {'query': query} print(query) # Testing the search result return render(request, 'myapp/usearch_query.html'} usearch.html <form method="POST" action="{% url 'usearch_query' %} <input type="search" placeholder="Search here..."> <button type="submit"> Search </button> </form> usearch_query.html {{ query }} I essentially want the user to search something, have it navigate to usearch/<search_parameter> and process the search in the usearch_query function so I can do some computations with it. -
Filtering by length of substring of a name django queryset?
I am trying to find a efficient way of filtering based on a length range of a full name field in my model. E.g the full name is separated as "John-Doe" in the model. John is the first name and Doe is the last name My goal is to find all objects in the model whose first_name is greater than 2 but less than 5. One approach I thought was of adding two additional field in the model called first_name and last_name and running a management command to extract the first_name and last_name and save it in those fields. This is a legacy db. So, there are close to 1million records. number_of_character_filter |= Q(first_name__length__gte=start, first_name__length__lte=end) Is there any other efficient approach I can take to resolve this? -
Update data using Django and AJAX
I have an issue with making a choice field in the input field from Django data. the models.py is: class Manifold_monitoring(models.Model): MFD_type = models.ForeignKey(Manifo_types , on_delete=models.CASCADE) DATE_TEST = models.DateField() Pressure_MFD = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) Pressure_SP = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) ..... def __str__(self): return str(self.MFD_type.MFDsID.MFDsID +' '+ self.MFD_type.Type +' '+ self.MFD_type.Fluid_N) class Meta: ordering = ('-post_date',) unique_together=[['MFD_type','DATE_TEST']] and the updating views.py: class UpdManifold_Monto(View): form_class = Manifold_monitoring_F def get(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) task.delete() return JsonResponse({"message":"success"}) return JsonResponse({"message": "Wrong request to delete"}) def post(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) print('request.is_ajax()1', task.MFD_type_id) data = { "MFD_type_id": task.MFD_type_id, "DATE_TEST" :task.DATE_TEST, "Pressure_MFD":task.Pressure_MFD, "Pressure_SP":task.Pressure_SP } print('request.is_ajax()2', task.MFD_type ,data ) form = self.form_class(request.POST, initial=data) if form.is_valid(): MFD_type = form.cleaned_data['MFD_type'] DATE_TEST = form.cleaned_data['DATE_TEST'] Pressure_MFD = form.cleaned_data['Pressure_MFD'] Pressure_SP = form.cleaned_data['Pressure_SP'] print('request.is_ajax()3', MFD_type) if form.has_changed(): task.MFD_type_id = MFD_type task.DATE_TEST = DATE_TEST task.Pressure_MFD = Pressure_MFD task.Pressure_SP = Pressure_SP task.save() return JsonResponse({"message": "success"}) return JsonResponse({"message":"No change"}) return JsonResponse({"message":"Failed"}) return JsonResponse({"message": "Wrong request"}) The HTML code of the edit form: <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLable" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="formEdit" action=""> {% csrf_token %} <div class="modal-body"> <div class="form-group validate"> … -
how can I calculate a value from user input which are not saved to database and value from database using django
I am doing the site with calculating of calories in products, so I need to do this action. I have different objects of products and for each - different value in "calories per 100 gram" field. So idk how to do the calculation not saving it to database, I am sure it is easy, but I am newer, so.. This is my code: views.py: class CurrentProductView(FormView): template_name = "cur_product.html" form_class = ProductForm success_url = reverse_lazy("product") def form_valid(self, form): obj = form.save(commit=False) calc_value = (obj.cur_weight * obj.calories) / 100 return HttpResponse(calc_value) forms.py: class ProductForm(forms.ModelForm): cur_weight = forms.IntegerField() class Meta: model = Product fields = ["calories"] models.py: class Product(models.Model): name = models.CharField(max_length=100) calories = models.PositiveIntegerField() #calories per 100 gram description = models.TextField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) html: {% block content %} <form method="post"> {% csrf_token %} {{ form.cur_weight }} <input type="submit" value="Count"> </form> {% endblock %} -
Django-rest-framework: 3rd Level Custom endpoints
I'm new to the Django rest framework and I'm trying to achieve 3rd level custom endpoints. I just want someone advice to solve 3rd level custom endpoints. I have read the official document: https://www.django-rest-framework.org/api-guide/routers/ but I'm confused to solve this. Please needs some advice. To achieve these endpoints: /admin/advisor/(default admin) /user/<user-id>/advisor /user/<user-id>/advisor/<advisor-id>/ /user/<user-id>/advisor/booking/ models.py from django.db import models class Advisor(models.Model): advisor_name = models.CharField(max_length=200) advisor_photo_url = models.ImageField(null=True, blank=True) def __str__(self): return self.advisor_name class User(models.Model): advisor_fk = models.ForeignKey(Advisor, related_name='advisors', on_delete=models.CASCADE) name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.name class Booking(models.Model): user_fk = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) booking = models.DateTimeField() def __str__(self): return '{0}'.format(self.user_fk) serializers.py from rest_framework import serializers from usersite.models import Advisor, User, Booking from django.utils import timezone class DateTimeFieldWihTZ(serializers.DateTimeField): def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeFieldWihTZ, self).to_representation(value) class AdvisorSerializer(serializers.ModelSerializer): class Meta: model = Advisor fields = ['advisor_name', 'advisor_photo_url', 'id'] class BookingSerializer(serializers.ModelSerializer): booking = DateTimeFieldWihTZ(format='%I:%M%p') #%b %d %Y %I:%M%p class Meta: model = Booking fields = ['user_fk', 'booking'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['advisor_fk', 'name', 'email', 'password'] -
How to delete label of a form in Django
How can I delete label of form in Django. I have something like this. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['user_image'] widgets = { 'user_image': forms.FileInput(attrs={'class': 'image-upload', 'label': ''}), } image-upload class does not include label. I have a auto-generated label and is written 'user-image' -
I can't run a function from the service layer in Django
I am a novice programmer. I'm trying to integrate PayPal IPN into my project, implement recurring subscription payments. I wrote a function that works fine in the console, BUT I DO NOT KNOW HOW TO RUN THIS FUNCTION SO THAT IT WOULD WORK AUTOMATICALLY. The ideal option for me would be if, when the data I need appears in the PayPal table, the IPN function would automatically start and perform the actions I need. For example, when these conditions appear in the table: ipn = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] my function would start, bypass the data in the table and perform the actions that I needed. I have tried such methods: def Proverka_1(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.exists(): return Podpiska() def Proverka_2(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0,mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.count() > 0: return Podpiska() def Proverka_3(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if len(ipn_12) > 0: return Podpiska() From the console, the Podpiska() function is launched, and works as expected. But when I write this in a python document, nothing works. I do not know how to run it all. I don't even know how to … -
Is it best practice to define a join table for Django many to many relationships?
I have the following code: class Tutors(models.Model): first_name = models.CharField(max_length=20, default=None, blank=False) #you need to add default none and blank false to enforce the Not-Null constraint last_name = models.CharField(max_length=20, default=None, blank=False) email = models.EmailField(max_length=254,default=None, blank=False) birth_day = models.DateField(auto_now=False, auto_now_add=False, default=False, blank=False) def __str__(self): return(self.first_name + ' ' + self.last_name) class ArtSubjects(models.Model): subject_name = models.CharField(max_length=20, default=None, blank=False) tutors = models.ManyToManyField(Tutors) def __str__(self): return self.subject_name My question is, should I define many to many relationships like this? Or should I define a new class for the table? The reason I ask is that I can get objects from the join table by querying by ArtSubjects class like so - adobeAI.tutors.all() returns <QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]> But I can't think of a way for querying the join table by tutors to see what classes an individual tutor teaches. Any advice on this? -
`xhr.getAllHeaders()` is missing some headers in a browser extension context?
I am working on a browser extension. In a script running on the popup page, I am making an ajax request. On the first line of my handler for the xhr.onload event, I have console.log(xhr.getAllResponseHeaders()). However, some headers from the response are missing. I know that this could be a problem with my manifest.json file, so here it is, with some extra details removed: { "manifest_version": 2, "name": "...", "version": "1.0", "description": "...", "options_ui": { "page": "options.html" }, "icons": { "16": "icons/favicon-16x16.png", "32": "icons/favicon-32x32.png" }, "browser_action": { "default_popup": "popup.html", "default_icon": "./icons/favicon-32x32.png" }, "key": "...", "permissions": ["identity"], "content_security_policy": "script-src 'self' https://unpkg.com https://apis.google.com https://www.gstatic.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'", "content_scripts": ["..."] } These are the actual response headers, according to the network debugging tab: HTTP/1.1 200 OK Date: Wed, 27 Oct 2021 18:09:36 GMT Server: WSGIServer/0.2 CPython/3.9.6 Content-Type: text/html; charset=utf-8 Hx-Trigger: setupLogin X-Frame-Options: DENY Content-Length: 220 Vary: Cookie, Origin X-Content-Type-Options: nosniff Referrer-Policy: same-origin Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: chrome-extension://kcegdmcjklppcfbmfjgkkomecpaofoec However, this is the output of console.log(xhr.getAllResponseHeaders()) on the first line of the xhr.onloaded event handler: content-length: 220 content-type: text/html; charset=utf-8 CORS I should note that I have no obvious CORS errors. I am using Django with the django-cors-headers library, and I have all these headers, … -
Cannot authenticate in Django
I implemented my CustomUser model and as far as I have understood I need to override an authentication method. I've done it, but my login form always returns the message "incorrect login/password" The registration form works fine my new accounts appear in the database. By the way, I tried to add the print function in authenticating backend method and it didn't print anything setting.py AUTHENTICATION_BACKENDS = ['account.forms.CustomBackend'] AUTH_USER_MODEL = 'account.CustomUser' I use built-in Django LoginForm urls.py path('login/', LoginView.as_view(template_name='login.html', authentication_form=CustomLoginForm), name='login'), models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return … -
How to scroll a line chart with the help of a mouse in Django?
I have a line chart rendered with Chart.js 2.4.0. According to the business requirement, the user should be able to move data points shown in the line chart using the mouse. Particularly, clicking the data point, hold the mouse clicked and move the point somewhere. Like drag and drop. Any ideas how to start? -
TypeError problem when I create "context_processor" in django
what is wrong here? I created 2 classes in the context_processor file, this problem I was facing when I was trying to return none dictionary objects but now doesn't understand what is wrong here. settings.py TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'accounts.context_processor.CreateNotification', 'accounts.context_processor.NotificationFeatures' ], }, }, ] context_processor.py from accounts.models import Notification, User class CreateNotification: def __init__(self, from_user, to_user, notification_type, role_sender, role_receiver, read_notif=False, active=False): self.from_user = from_user self.to_user = to_user self.notification_type = notification_type self.role_sender = role_sender self.role_receiver = role_receiver self.active = active self.read_notif = read_notif def send(self): if self.notification_type == "register": self.active = True Notification.objects.create( from_user=self.from_user, to_user=self.to_user, notification_type=self.notification_type, role_sender=self.role_sender, role_receiver=self.role_receiver, read_notif=self.read_notif, active=self.active ) return {} def read(self, id=None): if id: if self.active == True: self.read_notif = True return Notification.objects.filter(id=id).update(read_notif=self.read_notif) return {} class NotificationFeatures: def NotificationObject(self, req): notifications = Notification.objects.all() user_request = User.objects.get(username=req.user.username) if req.user.is_authenticated: # who is sender three_roles = notifications.distinct() for roles in three_roles: print(user_request.roles) if user_request.roles == roles: notifications.filter(from_user__roles__id=roles) return {} the traceback is: init() missing 4 required positional arguments: 'to_user', 'notification_type', 'role_sender', and 'role_receiver' knowing that: when I use the same classes that are in "context_processor file" in other locations like index views, for example, it works. so, I think that the problem … -
How to use Django/Nodejs with DDEV
I work a lot with DDEV on my PHP projects and love the features DDEV offers. Since I also work with Django and NodeJS projects I would like to use them in combination with DDEV. Officially these are not yet supported in the current version (1.18) but maybe someone has already found a solution? -
como hacer para que automaticamente no busque los datos de primary key en una relacion en django para un proceso automatico
id_clie = models.ForeignKey( Cliente, on_delete=models.CASCADE,) -
Django Chat - Image upload before message on channels
I've a Chat application built on Django Channels It has the capability to send images, files (soon). I send my message data over channels And create my Message model object during that. Now I've to upload images as well. Uploading images via a REST API and creating/updating a ImageField is what I've done before. Now in this case, I create the message object when something is sent over the channel and uploading an image over a websocket isn't good as I've read. How do people send images and create the object upon image upload success? This is my model class Message(models.Model): message = models.TextField() image = models.CharField(max_length=64, null=True) reported = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="message_reported" ) time = models.DateTimeField(auto_now_add=True) -
Generating user-unique links and storing points on purchase in Django
I'm trying to create a user-unique link so that the user can give to others, if the other user visited the website a cookie would be set for them, if the user with the cookie purchasd an item for the first time, a point would be added to the first user(the person who invented the second user to the website) -
How to get distinct data in Django views queryset?
I have the following records in table I want to get all sender_id where receiver_id is 15 and all receiver_id where sender_id is 15. How can I define queryset. I have tried following class ContactListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): return Messages.objects.filter(Q(sender=15) | Q(receiver=15)) serializer_class = ContactsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) but this is giving me all the records but I want Distinct values onle for example (sender =15, receiver=11) (sender =11, receiver=15) -
DRF nested serializer has validation over fields instead of ID
I have a PermissionSerializer and GroupSerializer, when I request to get data it works fine, but when I want to add a new group, it expects to receive all fields of PermissionSerializer while for the model it only needs ID. class PermissionSerializer(serializers.HyperlinkedModelSerializer): """Permission serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:permission-detail") content_type = ContentTypeSerializer(many=False, read_only=True) class Meta: model = Permission read_only_fields = ( "url", "id", "name", "content_type", "codename", ) fields = ( "url", "id", "name", "content_type", "codename", ) class GroupSerializer(serializers.HyperlinkedModelSerializer): """Group serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:group-detail") permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ( "url", "name", "permissions", ) When I enable the read_only=True, it completely ignores the permissions field validation while I really need it to be validated as well. Sample request which I expected to work fine: { "name": "editors", "permissions": [ {"id": 8} ] } or { "name": "editors", "permissions": [8] } But I really have no clue how to fix it. If I change the PermissionSerializer, then my output will be changed which it shouldn't, and if I want to keep it as what it is now, then I have to feed it by all permissions fields: { "name": "editors", "permissions": [{ "name": "something", "url": "something", "content_type": "something", "codename": … -
setattr doesn't save the values of my class in Python script
I´ve working on a project that must save in a database the values provided by a json. The setattr function is not working when i try to save the values of each json concept in the database. I think that i have provided the function attributes correctly. This is my models.py: class Balance_sheet(models.Model): company_name = models.CharField(max_length=140) year = models.CharField(max_length=140) quarter = models.CharField(max_length=140) CashAndCashEquivalentsAtCarryingValue = models.IntegerField(null=True, blank=True) ... #Extra fields class Meta: ordering = ['year'] verbose_name = "Balance Sheet" verbose_name_plural = "Balance Sheets" def get_attribute_by_name(self, field): if hasattr(self,field): return getattr(self,field) else: return '' def set_attribute_by_name(self, field, value): if hasattr(self, field): return setattr(self, field, value) else: return '' def __str__(self): return "%s %s" % (self.company_name, self.year) This is my script.py: from types import SimpleNamespace from typing import AsyncGenerator from django.core.management.base import BaseCommand, CommandError from database.models import Balance_sheet class Command(BaseCommand): def handle(self, *args, **options): data = open('database/static/data/data-q1.json') jsonObjectQ1 = json.load(data) json_prettyQ1 = json.dumps(jsonObjectQ1, sort_keys=True, indent=4) data.close() x = json.loads(json_prettyQ1, object_hook=lambda d: SimpleNamespace(**d)) print(x.startDate, x.companyName, x.companyCIK) print(x.year) # Creating Objects balance_sheet = Balance_sheet.objects.create(company_name=x.companyName, year=x.year, quarter=x.quarter) for data in x.data.bs: concept = data.concept value = data.value fields = Balance_sheet._meta.get_fields() for field in fields: if concept == field.name: model_name = field.name setattr(balance_sheet, model_name, value) balance_sheet.save I … -
expand model in backend
I have the following serializer class OrdenTrabajoserializer(BaseSerializer): class Meta: model = Orden_trabajo fields = '__all__' expandable_fields = { 'vehiculo': (Vehiculoserializer, { 'many': False }), 'asesor': (Tecnicoserializer, { 'many': False }), 'servicio_orden_registro': (Orden_registroserializer2, { 'many': True }) } when I make a request from the frontend and I want an expanded field I execute the endpoint and it correctly brings me the expanded object unexpanded {{url...}}/ response: { orden: 1, . . . vehiculo: 32 } expanded {{url...}}/?expand=vehiculo/ response: { orden: 1, . . . vehiculo: { id: 32, color: 'blue', ...data } } the problem is that I want to do the same but directly in the backend this is the viewset, according to the information I have searched it tells me that I should put 'permit_list_expands' but I don't know what to do to be able to use that and expand it ... class facturarOrdenV2viewSet(generics.ListAPIView): queryset = Orden_trabajo.objects.all() serializer_class = OrdenTrabajoserializer permit_list_expands = ['vehiculo', 'asesor', 'servicio_orden_registro'] def post(self, request, *args, **kwargs): orden = self.kwargs.get('orden', None) ordenTrabajo = self.queryset.get(pk = orden) dict_obj = model_to_dict(ordenTrabajo) print(dict_obj) return Response({'OK'}) -
Django webpage giving 404 error when I write the code to give video forward option
I am using django to make a website that shows some movies for me to watch when I am not at home. The code was working well, with the website showing the movie, letting me play it and everything that I wanted, except that i can't go forward and back in the movie. I spent a lot of time trying to solve that problem and I found some videos that explained how to make that work. But, when I write the code, django works normally, but if I try to access the website it shows me a 404 error, just saying "404 Not Found", without the usual 404 error page that django have. The code that is making all of this is application = Ranges(Cling(MediaCling(get_wsgi_application()))) in the wsgi.py file. Everything works fine until I add the MediaCling part. I have installed the libraries and writed the code equal to the videos that I watch. What I am doing wrong? import os from django.core.wsgi import get_wsgi_application from dj_static import Cling, MediaCling from static_ranges import Ranges os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Movies_site.settings') application = Ranges(Cling(MediaCling(get_wsgi_application()))) -
Using Django Allauth credentials instead of Google's flow
I'm trying to start a video stream on Youtube using Django but it seems my credentials are not working properly. To create the stream I use just the resource__owner_secret as a credential when starting the stream. Here is the view.py from django.shortcuts import render #import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors from allauth.socialaccount.models import SocialAccount, SocialApp scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"] api_service_name = "youtube" api_version = "v3" #client_secrets_file = "app/client_secret.json" def index(request): if request.method == 'PUT': google_app = SocialApp.objects.get(provider='google') user_account = SocialAccount.objects.get(user=request.user) client_key = google_app.client_id user_token = user_account.socialtoken_set.first() resource_owner_key = user_token.token resource_owner_secret = user_token.token_secret #flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes) # credentials = flow.run_console() credentials = resource_owner_secret print(credentials) youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials) request = youtube.liveStreams().insert( part="snippet,cdn,contentDetails,status", body={ "cdn": { "frameRate": "60fps", "ingestionType": "rtmp", "resolution": "1080p" }, "contentDetails": { "isReusable": True }, "snippet": { "title": "Your new video stream's name", "description": "A description of your video stream. This field is optional." } }, onBehalfOfContentOwnerChannel="<MY_CHANNEL_ID>" ) request.execute() return render(request, 'index.html') Any idea why starting the live stream isn't working? -
How Do I Pervent Django Default Ordering
I have two models, Exercise and Workout. When I add my list of exercise to the workout table, they are added in alphabetical order. I do not want that. I use ajax to send a list of exercise_id, in the order I want, then in my views.py, I get the exercise by id, and add it to my workout. I want to keep the order I add the exercises. How do I do that? below are my code snippets. BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ('Myofascial', 'Myofascial') ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'BattleRope'), ('Bodyweight', 'Bodyweight'),('Bands', 'Bands'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', 'Medicine Ball'), ('Plate', 'Plate'), … -
Don’t forget to enter notes” - If they have not enter note by today and enter note the prior day
I have two tables Member table and Daily_Notes table. class Member(models.Model): name = models.Charfield() Daily_notes table class DailyNotes(models.Model): member= models.Foreignkey('Member') note=models.Charfield() date=models.Datetimefield(default="") Daily note table contains daily entries I need to filter datas, If user have not enter note by today and entered the prior day.