Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter data from Mongo DB in Django
I use Djongo as the connector for mongoDb with Django. But I dont know how to get all the data with filter. I get int error while trying to do that. class HomeView(LoginRequiredMixin, ListView): template_name = 'home.html' getter = PostModel.objects.filter(author='1') model = getter login_url = reverse_lazy('login') This is my code for getting the data. But it says. 'QuerySet' object has no attribute '_default_manager' What am I doing wrong here. Please help me. -
How to search query sets that have a specific value in a list in Django Rest framework
What I want to do Getting all query set which has a specific value in a list which is ManyToManyField. In short, if I type http://localhost:8000/api/pickup/?choosingUser=5, I would like to get all PickUp_Places that matches like choosingUser = 5. choosingUser comes from ManyToManyField so a PickUp_Places model has like choosingUser = [2,3,5,7]. Problem I cannot search query sets by a specific value in list. When I type http://localhost:8000/api/pickup/?choosingUser=5, I get all query sets that include ones don't have choosingUser = 5. I am using django_filters in order to filter query sets. I read the documentation but I couldn't find how to get query sets by a value in a list. If it is alright with you, would you please tell me how to do that? Thank you very much. ===== ========= ========== ========= My code is like this. models.py class PickUp_Places(models.Model): name = models.CharField(max_length=200, unique=True) choosing_user = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="pick_up") def __str__(self): return self.name class Meta: db_table = "pickup_places" serializers.py class PickUp_PlacesSerializer(serializers.ModelSerializer): class Meta: model = PickUp_Places fields = "__all__" views.py class PickUp_PlacesViewSet(viewsets.ModelViewSet): queryset = PickUp_Places.objects.all() permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] serializer_class = PickUp_PlacesSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = "__all__" -
Best way of checking whether a certain Model instance is in fact an instance of a certain Model
I am trying to write a class that takes an instance of a Model from my app as an argument in its __init__. While reading up on the subject, I stumbled upon this quesiton: django: best practice way to get model from an instance of that model which argues that simply using type(instance) would be the best way to go. As tempting as it may be to use this right away, wouldn't using isinstance(instance, model) be a better solution? Say, for example (from my own code): from app_name.models import Model1, Model2, ... ModelN MODELS = (Model1, Model2 ... ModelN) and then inside the class itself (in my case, Graph), do something like this: class Graph(): model_instance = None model = None def __init__(self, model_instance): if isinstance(model_instance, MODELS): for a_model in MODELS: if isinstance(model_instance, a_model): self.model = a_model self.model_instance = model_instance ... As a beginner, I thought this was the best way I could come up with but also assume there are smoother/better ways of doing this. Possibly an even more "readable" way maybe? Pros? Cons? Appreciate ALL feedback on this! Thanks! -
form errors do not show on the template
Non of my validation errors show, the template page just refreshes if there is something wrong. i placed the validation error code in my forms.py, i don't know if i am supposed to place it in my views, because nothing works. i also thought django had a default for errors, seems i was wrong. html <form method="post"> {%csrf_token%} <form method="post">{%csrf_token%} {{form.username}} {{form.first_name}} {{form.last_name}} {{form.email}} {{form.phonenumber}} {{form.state}} {{form.next_of_kin}} {{form.dob}} {{form.address}} {{form.password1}} {{form.password2}} <li class="btnn"><button type="submit" class="conf">Add</button></li> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{error}} </p> {% endfor %} {% endfor %} {% endif %} forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class PatientForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name') last_name = forms.CharField(max_length=100, help_text='Last Name') address = forms.CharField(max_length=100, help_text='address') next_of_kin = forms.CharField(max_length=100, help_text='Next of kin') dob = forms.CharField(max_length=100, help_text='Date of birth') state = forms.CharField(max_length=100, help_text='State') phonenumber = forms.CharField( max_length=100, help_text='Enter Phone number') email = forms.EmailField(max_length=150, help_text='Email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'placeholder': ('Username')}) self.fields['email'].widget.attrs.update( {'placeholder': ('Email')}) self.fields['address'].widget.attrs.update( {'placeholder': ('Address')}) self.fields['phonenumber'].widget.attrs.update( {'placeholder': ('Phone number')}) self.fields['first_name'].widget.attrs.update( {'placeholder': ('First name')}) self.fields['last_name'].widget.attrs.update( {'placeholder': ('Last name')}) self.fields['password1'].widget.attrs.update({'placeholder': ('Password')}) self.fields['password2'].widget.attrs.update({'placeholder': ('Repeat password')}) self.fields['dob'].widget.attrs.update({'placeholder': ('Date of birth')}) self.fields['state'].widget.attrs.update({'placeholder': ('State')}) self.fields['next_of_kin'].widget.attrs.update({'placeholder': ('Next … -
Django form submit button doing nothing
I'm trying to upload a csv file to insert into the model I created since the data in the csv is quite a lot I cannot manually input it all. I've watched a tutorial and I kinda copy pasted every detail the tutorial gave, the problem is when I'm click the upload button, nothing happens. Models.py class Dev(models.Model): projName = models.CharField(max_length=255) clientName = models.CharField(max_length=255) projDesc = models.CharField(max_length=255) projTask = models.CharField(max_length=255) userName = models.CharField(max_length=255) userEmail = models.CharField(max_length=255) projTag = models.CharField(max_length=255) billable = models.BooleanField() dateStart = models.DateField(auto_now=False, auto_now_add=False) timeStart = models.DateTimeField(auto_now=False, auto_now_add=False) dateEnd = models.DateField(auto_now=False, auto_now_add=False) timeEnd = models.DateTimeField(auto_now=False, auto_now_add=False) timeDuration = models.DateTimeField(auto_now=False, auto_now_add=False) duration = models.DecimalField(max_digits=4, decimal_places=2) billRate = models.DecimalField(max_digits=10, decimal_places=2) billAmount = models.DecimalField(max_digits=10, decimal_places=2) and here is the views.py from django.shortcuts import render from django.http import HttpResponse import csv, io from django.contrib import messages from django.contrib.auth.decorators import permission_required from .models import Dev # Create your views here. def homepage(request): return render(request, 'Home.html') @permission_required('admin.can_add_log_entry') def csv_upload(request): template = "upload.html" prompt = { 'order': 'Order of the CSV chuchu' } if request.method == "GET": return render(request, template, prompt) csv = request.FILES['file'] if not csv.name.endswith('.csv'): message.error(request, 'Not a csv file, please choose another file.') data_set = csv.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for col … -
How To Configure Apache To Point To Media Files
My website isn't finding my media files in production and I think it's because I need to configure my webserver to point to my media root file, I think with the following code: Alias /media /home/atms/atms/media <Directory /home/atms/atms/media> Require all granted </Directory> However I have no idea where to place this code? Apparently it goes in a file 'htaccess', but I can't find this file. I am using A2 hosting. Thank you. -
How to add Django model ImageField to ReportLab
I would like to add a media file to PDF generated by Reportlab. STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") output STATIC_ROOT --> project/static/ MEDIA_ROOT = os.path.join(BASE_DIR, "media") output STATIC_ROOT --> project/media/ when i draw static images are ok: logo = STATIC_ROOT + "img/dilains-logotipo-bg-white-290x100.jpg" self.canvas.drawImage(logo, self.x, self.y, w, h, preserveAspectRatio=True) but with media: output self.rejection.img_general_model_1 --> images/treatments/rejections/mouth.jpg picture = MEDIA_ROOT + str(self.rejection.img_general_model_1) self.canvas.drawImage(picture, self.x + text_x * 0, self.y, w, h, preserveAspectRatio=True, mask='auto') Throws error: Cannot open resource "/project/media/images/treatments/rejections/mouth.jpg" <class 'OSError'> Anybody know how to fix it ? And in production with AWS S3 configuration ? Thanks in advance. -
form submitted data from template is not saved in database in Django?
I was doing a small project on django where i create simple blog mini project. Everything worked for me but i am in issue now that i can create post form Django administration and i wanted to do it with in front-end with templates in create-post.html but i am no issue just my form is not working or it is not submitting any data or some error ? I'm using summernote rich text editor instead of textfield in Model. Expert please look my code and suggest me it is good or bad or where i am wrong ? my models.py class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) author_profile_pic = models.ImageField(upload_to='images',null=True) author_description = models.TextField(null=True) author_facebook_url = models.CharField(max_length=50,null=True) author_twitter_url = models.CharField(max_length=50,null=True) author_instagram_url = models.CharField(max_length=50,null=True) author_github_url = models.CharField(max_length=50,null=True) def __str__(self): return f'{self.user}' class Category(models.Model): # show string title in Admin panel title = models.CharField(max_length=30,null=True) def __str__(self): return self.title class Blogpost(models.Model): title = models.CharField(max_length=100,null=True) thumbnail = models.ImageField(upload_to='images') post_body = models.TextField() slug = models.SlugField(null=True,blank=True) posted_date = models.DateField(default=date.today) author = models.ForeignKey(Author, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) publish = models.BooleanField() and my form from django import forms from .models import Blogpost from django_summernote.widgets import SummernoteWidget class CreatePostForm(forms.ModelForm): class Meta: model = Blogpost fields = "__all__" widgets = { 'post_body': … -
How to count data from Another Model in Django?
I have 2 models and i want to count Foreignkey data, I am trying to count the number of records in related models, but I am unable to count the records, Please let me know how i can Count the data. I want to count this data after filter, I am filtering between 2 dates, it's giving me the current data of using model in filter,but i want to count related model data also using filter. Here is my models.py file... class Product(models.Model): name=models.CharField(max_length=225) customer=models.ForeignKey(Brand, related_name='product_customer',on_delete=models.CASCADE) user= models.ForeignKey(Supplement, related_name='product_user', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) here is my views.py file... def index(request): data = Project.objects.all() if request.method == 'POST': v1= request.GET.get('created-at') if v1: v2 = v1.split(' - ') s1 = v2[0] s2 = v2[1] result = Product.objects.filter(created_at__range=[s1,s2]) return render(request, 'index.html' {'result':result}) here is my index.html file.. <p>{{result.count}} product</p> <p>{{result.product_customer.count}} Customer</p> <p>{{result.product_user.count}} User</p> I want to display this data after filter, for product it's working perfect, but i want to display data for customer and user when user filter... -
django, TypeError: doctor_code_create() missing 1 required positional argument: 'h_code'
doctor.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(h_code): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' h_code_test = h_code d_code = last_doctor_code.d_code doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + h_code_test + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'h_code' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I have to specify it? -
Filter Django query set by appended attribute
I'd like to filter/exclude instances in a query set where change=0 but I'm getting a FieldError with the below code. movements = part.history.all() previouslevel = 0 for movement in movements: movement.change = movement.stockOnHand - previouslevel previouslevel = movement.stockOnHand print(movements.exclude(change=0)) Is there a way to filter a query set with an appended attribute? -
django) Got a `TypeError` when calling `Doctor.objects.create()`, I want to solve it
hospital.py class HospitalList(models.Model): hospitalname = models.CharField(max_length=200) def hospital_code_create(): last_hospital_code = HospitalList.objects.all().order_by('code').last() if not last_hospital_code: return 'h' + '000001' code = last_hospital_code.code hospital_int = int(code[3:9]) new_hospital_int = hospital_int + 1 new_code= 'h' + str(new_hospital_int).zfill(6) return new_code code = models.CharField(primary_key=True, max_length = 200, default = hospital_code_create, editable=False) doctor.py class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) I want to display d_code as d002001, not d001. Here, 002 is the foreign key from which the primary key of hospital.py is imported. I've slightly modified doctor.py to implement this. doctor.py(Revise) class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(**h_code**): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code **h_code_test = h_code[-3]** doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + **h_code_test** + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) After modifying as above, Got a TypeError when calling DoctorList.objects.create(). Error occurred. What … -
Django Unable to open static file loading
enter image description here enter image description here enter image description here I was proceed "python manage.py collectstatic" enter image description here -
MKV file downloads and doesn't display
I have made a Django model where I store files and if there is a mkv file it doesn't display in the URL like how the others do. The URLs do show the video but if it is mkv it downloads in the link so what could I do to stop it. So I think in need to change the file type in python so like how can I do that or if there is a better way could you tell me how to. Thanks -
Como puedo asignar un valor iniciar a un foreignkey en vistas basadas en clase django
estoy tratando de seleccionar el valor inicial del Paciente ForeignKey: class Consulta(models.Model): Paciente = models.ForeignKey(paciente, on_delete=models.CASCADE) Area_de_consulta = models.ForeignKey(Area, on_delete=models.CASCADE) Notas_de_la_consulta = models.TextField("Ingrese las notas de la consulta", max_length=500) def __str__(self): return '%s %s %s' % (self.Paciente, self.Area_de_consulta, self.Notas_de_la_consulta) el objetivo es que al aparecer el form en la vista debe ir con el paciente que recibirá la consulta seleccionado. Como podría realizar esta acción ? he buscado y aun no termino de entenderlo, podrían orientarme por favor. -
How to make multiple choice field from Django many to many related model
I want to show products from product model using check boxes in my store form where user can select multiple products. Product Model: class Product(models.Model): product_name = models.CharField(max_length=30) product_price = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product_name Store Model: class Store(models.Model): AREAS = [ (0, 'Dhaka'), (1, 'Khulna'), (2, 'Chittagong'), (3, 'Barisal'), (4, 'Rajshahi'), ] SELLER_TYPE = [ (0, 'Manufacturer'), (1, 'Authorised Dealer'), (2, 'Distrubutor'), (3, 'Dealer'), ] store_owner = models.ForeignKey(User, on_delete=models.CASCADE,related_name='store_owner') store_name = models.CharField(max_length=256) store_address = models.CharField(max_length=300) seller_type = models.IntegerField(choices=SELLER_TYPE, default=0) area = models.IntegerField(choices=AREAS, default=0) products = models.ManyToManyField(Product, related_name='store_products') timestemp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.store_name Store Form: class StoreForm(forms.ModelForm): area = forms.ChoiceField(choices=Store.AREAS, label='Area', required=True) products = forms.MultipleChoiceField(queryset=Product.objects.all(), label='Manager', required=True) seller_type = forms.ChoiceField(widget=forms.RadioSelect, choices=Store.SELLER_TYPE) class Meta: model = Store fields = ('seller_type', 'store_name', 'store_address', 'products', 'area') I want to select multiple product item while I'm going to create a record for a store. Currently I can select multiple product items from the product list. But I want to represent them as check-boxes so that users can select multiple items from the check-boxes. -
On Django form, I want to know how to respond to form field data in JSON
I was successful using this method but, I want the repose code to be simpler. Is there such a way? The code is as follows: views.py class PersonnelInfoDetailView(DetailView): def get(self, request, pk): employee = Employee.objects.get(pk=pk) response = {'employeeType' : employee.employeeType_id, 'driverIndex': employee.driverIndex, 'routeId': employee.routeId_id, 'department': employee.department, 'employeeNumber': employee.employeeNumber, 'employeeName': employee.employeeName, 'employeeBirth' : employee.employeeBirth, 'employeeAddress' : employee.employeeAddress, 'employeeTel' : employee.employeeTel, 'employeeEmergencyTel' : employee.employeeEmergencyTel, 'employeeSalary' : employee.employeeSalary, 'employeeFixedRest1' : employee.employeeFixedRest1, 'employeeFixedRest2' : employee.employeeFixedRest2 , 'tableHoBong' : employee.tableHoBong_id, 'jobTitleType' : employee.jobTitleType, 'employeeStatus' : employee.employeeStatus } return HttpResponse(json.dumps(response), content_type='application/json') forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ('employeeType','driverIndex', 'routeId', 'department', 'employeeNumber', 'employeeName', 'employeeBirth', 'employeeAddress', 'employeeTel', 'employeeEmergencyTel', 'employeeSalary', 'employeeFixedRest1', 'employeeFixedRest2','tableHoBong','jobTitleType', 'employeeStatus') def __init__(self, *args, **kwargs): super(EmployeeForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control form-control-sm w-100' -
How To Serve media Files In Production
I have a Django project which sends automated e-mails with attached pdfs to users. At the moment I just have a normal /media/ folder with the pdf in it which the code points to. This works in development but throws a server error in production. My question is how do I server media files in production? I have read a lot about it but can't find exactly what I'm after. I use collectstatic in my production environment which works for static files, I'd expect something similar for media files. Thank you. -
Django HTMLForms AttributeError AttributeError: module 'polls.views' has no attribute 'index'
I'm using Django to create a simple HTML input page, right now I am just using the tutorial for Django Forms but I get the error AttributeError: module 'polls.views' has no attribute 'index' Here are all the relevant files: This is where the Error is happening: $ mysite/polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] This is views.py: $ polls/views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) and this is forms.py $ /polls/forms.py from Django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) I am so confused as to why this is happening because when I used it with the Writing your first … -
AttributeError: 'Query' object has no attribute 'explain_query'
I updated Django2.0.2 to 2.2.16. Then, I'm having a lot of errors of AttributeError: 'Query' object has no attribute 'explain_query' at many places. What's wrong? Any idea? -
django.db.utils.IntegrityError: UNIQUE constraint failed: cedente.cnpj (django)
After I delete a Cedente if I try to create another one with the CNPJ of the previous one, I have this error: django.db.utils.IntegrityError: UNIQUE constraint failed: cedente.cnpj this is the model: class Cedente(BaseModel): class Meta: db_table = 'cedente' verbose_name = "cedente" verbose_name_plural = "cedentes" razao_social = models.CharField(max_length=100, unique=True, verbose_name="Razão Social") nome = models.CharField(max_length=100, verbose_name="Nome Padrão") cnpj = models.CharField(max_length=14, validators=[validate_CNPJ], unique=True, verbose_name="CNPJ") nome_contato = models.CharField(max_length=100, verbose_name="Nome") ddd_telefone_contato = models.CharField(max_length=2, verbose_name="DDD", validators=[validate_int, validate_length_ddd]) numero_telefone_contato = models.CharField(max_length=9, verbose_name="Telefone", validators=[validate_int, validate_length_telefone]) email_contato = models.CharField(max_length=50, verbose_name="E-mail", validators=[validate_email]) calculo = models.ForeignKey(Calculo, verbose_name="Cálculo", related_name='cedentes', on_delete=models.CASCADE, null=True) commissao = models.ForeignKey(Commissao, verbose_name="Comissão", related_name='cedentes', on_delete=models.CASCADE, null=True) def __str__(self): return ("%s (ID: %d)" % (self.nome, self.id)) -
Quick help on how to format a logic statement
this might seem silly, but i need help, I have a model, in which if "is_vendor" is True, I want it to display something, while if "is_vendor" is False, I dont want the item to display. I already figured how to switch the is_vendor from True to False or vice versa, What i want now is to know how to complete {% if user_profile.is vendor... statement (Plus Im not sure if want i typed there is close to correct. Thank you Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') is_vendor = models.BooleanField(default=True) My template: **{% if user_profile.is_vendor** <div style="margin-left: 40px"> <a class="btn btn-sm btn-outline-primary mb-4 mr-3 "href="{% url 'vendor_register' %}"> Register </a> </div> -
Loading spinner after PayPal payment
So I'm building a Django e-commerce which allows payments via PayPal. Once the user introduces all his PayPal information and presses pay, the PayPal window disappears and take a few seconds to call the function I put inside onApprove. As I show here: // Finalize the transaction onApprove: function (data, actions) { return actions.order.capture().then(function (details) { submitFormData(); }); } As I said it takes a few seconds (3 or 4) to execute the call submitFormData() after the customer accepted the transaction. Is there any way I can put a loading spinner in the middle of the screen? I imagine I can but honestly I don't know where to start. Thank you very much -
i have accidently delete my sceret key form settings.py in django
while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project. while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project. -
Django Class Based Views Download Video YouTube return 404 not found in File
I'm developing a website for training in Django (Class Based View) that downloads a video that the user informs the URL on the front end. However, when returning the exact URL, Django appears as 404 - Not Found. How can I pass the parameter to download the file? In urls.py I already inserted + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) to download the static files Below are the files: views.py class PaginaPrincipal(TemplateView): template_name = 'home/index.html' def get(self, request, *args, **kwargs): if not os.path.exists('media/'): os.makedirs('media', exist_ok=True) for file in glob.glob('media/*.mp4'): if file: os.remove(file) return render(self.request, self.template_name) def post(self, request): link = str(self.request.POST.get('link-youtube')) if link: func.videoDownload(link) return redirect(reverse_lazy('pagina-resultado')) return render(request, 'error.html', {'error': 'erro ao baixar, tente novamente'}) class PaginaResultado(TemplateView): template_name = 'home/result.html' def get_context_data(self, **kwargs): context = super(PaginaResultado, self).get_context_data(**kwargs) arquivo = None for file in glob.glob('media/*.mp4'): arquivo = file context['videoDownload'] = arquivo return context func.py def videoDownload(url): yt = YouTube(url) yt.streams.order_by('resolution')[-1].download() movingFileToCorrectPath(flag='video') yt.streams.filter(only_audio=True)[-1].download() movingFileToCorrectPath(flag='audio') joinFile() title = yt.title urlVideo = 'https://www.youtube.com/watch?v=' + yt.video_id views = yt.views thumbnail = yt.thumbnail_url author = yt.author renameLastFile(title=title) # print(title, urlVideo, views, thumbnail, author) def movingFileToCorrectPath(flag): if not os.path.exists('/static/video'): os.makedirs('static/video', exist_ok=True) try: if flag == 'video': for file in glob.glob('*.webm'): os.renames(file, f'video-{file}') a = f'video-{file}' shutil.move(a, 'static/video/') elif …