Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter REST API using django
i have a program to filter REST API using django , but whenever i try to filter it is showing all the response data again , no idea why . so can anyone help me ... posting the rest api response { "output": "success", "data": [ { "IPadd": "17629082", "Mobiles": { "output": "success", "data": [ { "Name": "samsung js", "price": "100", "count": "1" }, { "Name": "Samsung j13", "price": "100", "count": "3" } ] } } ] } and the method i used to get it . response = requests.get('http://abcd/users/?Name="samsung js"') details = json.loads(response.text) print(details) but it returns everything , once again .... Can anyone help me sort it out . -
Django REST Framework filter by Foreign key
First of all, please consider that I'm very new in Django so I'm not really sure about what I'm looking for. I have a model called Product: class Product(models.Model): name = models.CharField('Name', max_length=100) ... One Product can have several variants so I created another model called ProductVariant which has a ForeignKey to Product. class ProductVariant(models.Model): name = models.CharField('Name', max_length=100) product = models.ForeignKey(Product, verbose_name='Produkt', related_name='productvariants', on_delete=models.CASCADE) ... I want to return only the Products that have Variants but I don't know how to access that information from the Product Filter or Product Serializer, since the ForeignKey is on the ProductVariant model. Any ideas? I know this is basic Django but I'm completely new, any help would be really appreciated. This is my Product Filter: class ProductFilter(filters.FilterSet): class Meta: model = Product fields = ['id', 'name'] The Product Serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name') The Product ViewSet: class ProductViewSet(ModelViewSet): queryset = Product.objects.all() filterset_class = ProductFilter serializer_class = ProductSerializer permission_classes = [IsAuthenticated] -
Using ModelFormMixin (base class of PostDetailView) without the 'fields' attribute is prohibited
Form button does not work. After adding ModelFormMixin, the error "Using ModelFormMixin (base class of PostDetailView) without the 'fields' attribute is prohibited" appears. This is my #views.py code class PostDetailView(ModelFormMixin, DetailView): model = Post template_name = 'articles/article_details.html' context_object_name = 'post' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) stuff = get_object_or_404(Post, slug=self.kwargs['slug']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked self.object.views = F('views') + 1 post = get_object_or_404(Post, slug=self.kwargs['slug']) if self.request.method == 'POST': form = CommentForm(data=self.request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = self.request.user comment.save() return context else: form = CommentForm() context["form"] = form self.object.save() self.object.refresh_from_db() return context This is my #forms.py code class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) widgets = { # 'author': forms.Select(attrs={'class': 'form-control'}), # 'author': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } This is my #models.py code class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", verbose_name='Публикация', on_delete=models.CASCADE) author = models.CharField(max_length=255, verbose_name='Автор') # author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(verbose_name='Комментарий') is_active = models.BooleanField(default=True, verbose_name='Опубликовано', db_index=True) comment_date = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return '%s - %s' % (self.post.title, self.author) class Meta: ordering = ['comment_date'] This is my #article_details.html code <div class="form-group"> <form method="POST"> {% csrf_token %} … -
Django Rest Framework - Making efficient APIs
How can we make APIs efficient in terms of responding time and processing time? What are they ways, would you please clarify? Can we use caching for the APIs? -
Decorator that includes celery task with attributes
I'm working on a Django project with several apps, each of them have their set of tasks and it works pretty fine. But, in general, the set of tasks of each app use the same attributes for rate limiting, retry, etc. I was trying to create a decorator that would have all those common attributes and set the target function as a task. So, I have this in my example/tasks.py: from celery import current_app @current_app.task( queue='example_queue', max_retries=3, rate_limit='10/s') def example_task_1(): ... @current_app.task( queue='example_queue', max_retries=3, rate_limit='10/s') def example_task_2(): ... I'm trying something like: from celery import current_app, Task class ExampleTask(Task): def __init__(self, task, *args, **kwargs): super().__init__(self, *args, **kwargs) self.task = task def run(self): self.task.delay( queue='example_queue', max_retries=3, rate_limit='10/s') def example_decorator_task(func): @wraps(func) def wrapped(self, *args, **kwargs): return ExampleTask(func) @example_decorator_task def example_task_1(): ... @example_decorator_task def example_task_2(): ... This code does not work and I'm sure it is not that hard to do this, but I'm not getting it. Any ideas? -
pass data from db to template without a view
I am trying to display a placeholderfield in my template but it's not showing anything. I think it's because I am passing data from db to my template using a plugin class ElmentsList(CMSPlugin): Elements = Element.objects.all() Composition_1 = Composition_1.objects.all() then in my template {% if instance.Composition_1 %} {% for Composition in instance.Composition_1 %} {% if forloop.counter == 1 %} {% render_model_add Composition %} {% endif %} <h5 class="card-title"> {% render_model Composition "title" %}</h5> {% render_placeholder Composition.credit language 'en' %} {% placeholder Composition.image language 'en' %} <p></p> {% endfor %} {% else %} <p>There are no Compositions in the database.</p> {% endif %} -
django model formset factory how to write {{ form.field }}
So for forms, if you have quantity = IntegerField() in forms.py, then in the html file you can write {{ form.quantity }} to get the input for the quantity. How can do you the samething for modelformset_factory? I've created a formset to ask the user for the item name and quantity. The item name is given by the loop. I need to move the modelformset factory inside the loop for each iteration, but I don't know how #views.py form_extras = Items.objects.filter(show=True).count() formset = modelformset_factory(Cart, form=CustomerOrderForm,extra=form_extras) form = formset(queryset=Items.objects.none()) if request.method == 'POST': form = formset(request.POST) #work on this if form.is_valid(): print("is valid") form = formset(request.POST) instances = form.save(commit=False) for instance in instances: #item previously in cart if (Cart.objects.filter(username=request.user, item_name=form.cleaned_data.get('item_name')).exists()): cart_instance = Cart.objects.get(username=request.user, item_name=form.cleaned_data.get('item_name')) cart_instance.quantity = cart_instance.quantity + form.cleaned_data.get('quantity') cart_instance.save() else: #item never in cart, create new instance item_instance = Items.objects.get(item_name=form.cleaned_data.get('item_name')) Cart.objects.create(username=request.user, item_name=form.cleaned_data.get('item_name'), weight=item_instance.weight, quantity=form.cleaned_data.get('quantity'), description=item_instance.description, image=item_instance.image, price=item_instance.price, storage_type=item_instance.storage_type, item_category=item_instance.item_category, limit=item_instance.limit,) timestamp = datetime.date.today() messages.success(request,"Sucessfully added your items to your cart! " + str(timestamp)) return redirect('/') else: print("form not valid for cart") form = formset() Home.html: #home.html <form method="POST"> {% csrf_token %} {{ form.management_form }} {{form.as_p}} <div class="row"> {% for item in produce %} <div class="card" style="width: 18rem;"> <img src="/media/{{ item.image … -
Can we use django builtin function of password reset for all users?(not for admin)
I am new to Django and I have started developing a website, where I provide the functionality of user login, logout and password reset. But I am not able to use Django default password reset as I am only getting email verification link to the superuser only. I need the password resetting for all users rather than superuser. Kindly help me .. -
How to break if statement's condition in jinja
I am trying to divide media files based on their file type. I have one big if statement's condition do this task. But when I am trying to break if statement's condition into multiple lines like below it causing an error. My Code: <div> {% for post in posts %} <h3>{{ post.title }}</h3> {% if ( (".jpg" in post.media_file.url) or (".png" in post.media_file.url) ) %} <img width="500" height="400" src={{ post.media_file.url }}></img> {% else %} <video width="500" height="400" controls controlsList="nodownload" src={{ post.media_file.url }}> </video> {% endif %} {% endfor %} </div> Error: Django Version: 3.0.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 16: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? It is working fine if I convert if statement condition like below, {% if ".jpg" in post.media_file.url or ".png" in post.media_file.url %} So, is there any way or how to break if condition properly in jinja2? -
How to programatically create a database view in Django?
I have following query that I ran to create a database view inside my SQLite database: CREATE VIEW customerview AS SELECT a.id , name , email , vat , street , number , postal , city , country , geo_lat , geo_lon , customer_id , is_primary FROM customerbin_address a , customerbin_customer b WHERE b.id = a.customer_id AND a.is_primary = 1 In models.py I added the model: class Customerview(models.Model): name = models.CharField(max_length=100, db_column='name') email = models.EmailField(unique=True, db_column='email') vat = VATNumberField(countries=['NL', 'BE', 'FR', 'DE', 'UK'], blank=True, null=True, db_column='vat') street = models.CharField(max_length=100, db_column='street') number = models.IntegerField(null=True, db_column='number') postal = models.IntegerField(null=True, db_column='postal') city = models.CharField(max_length=100, db_column='city') country = CountryField(db_column='country') is_primary = models.BooleanField(null=False, db_column='is_primary') geo_lat = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lat') geo_lon = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lon') class Meta: managed = False db_table = 'customerview' and in admin.py I altered the list: @admin.register(models.Customerview) class CustomerviewAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon') readonly_fields = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon',) How do I programatically add the database view with the query above in my application? -
Static files in Django with AWS S3
I just moved the static files of my Django project into AWS S3. It works so far. But my .css files contain relative paths, for example to fonts, for example: @import "variables"; @font-face { font-family: '#{$font-family}'; src: url('#{$font-path}/#{$font-family}.eot?4zay6m'); format('svg'); font-weight: normal; font-style: normal; } My browser console shows that the path to these file is set correctly, for example https://mybucket.s3.amazonaws.com/static/plugins/fonts/myfont.ttf?4zay6m but I get a permission denied, because unlike the other (from django set paths), these paths do not contain the "Amazon stuff" after the question mark like https://mybucket.s3.amazonaws.com/static/js/jquery.tablednd.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXX Is there a simple workaroud? Thanks in advance. -
Why django dependent dropdownn is not working
I cant tell where there is an error in my code. It just doesnt work as expected. My views.py def load_cities(request): year_id = request.GET.get('year') terms = Term.objects.filter(school=request.user.school).filter(year_id=year_id).order_by('name') return render(request, 'city_dropdown_list_options', {'terms': terms}) My models. class Year(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.CharField(max_length=200,unique=True) class Term(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.CASCADE) name = models.CharField(max_length=200,unique=True) class Exam(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.SET_NULL, null=True) term = models.ForeignKey(Term,on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=20) form = models.ManyToManyField(FormModel) My forms.py class NewExamForm(forms.ModelForm): class Meta: model = Exam fields = ("year","term","name","school","form") widgets = { 'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}), "year":forms.Select(attrs={"class":'form-control'}), "name":forms.TextInput(attrs={"class":'form-control'}), "form":forms.Select(attrs={"class":'form-control'}), } def __init__(self, school, *args, **kwargs): super(NewExamForm, self).__init__(*args, **kwargs) self.fields['year'] = forms.ModelChoiceField( queryset=Year.objects.filter(school=school)) self.fields['term'].queryset = Term.objects.none() self.fields['form'] = forms.ModelMultipleChoiceField( queryset=FormModel.objects.filter(school=school), widget=forms.CheckboxSelectMultiple, required=True) if 'year' in self.data: try: year = int(self.data.get('year')) self.fields['term'].queryset = Term.objects.filter(school=school).filter(year_id=year).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['term'].queryset = self.instance.year.term_set.order_by('name') The template <div class="form-group"> <form method="post" id="examForm" data-cities-url="{% url 'ajax_load_cities' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <table> {{ form|crispy }} </table> <button type="submit">Save</button> </form> </div> I have tried but it works only after I select a year and refresh manually with the year selcted, that's when the terms appear. I tried following the code … -
What does this error mean? And how to solve it?
*** Good afternoon, sansei. Faced a problem and can't solve it. I am trying to add models to the database and I am getting an error. Please explain what I am doing wrong. Maybe someone came across such an error and will tell you how to solve it *** `` dadi2015@ubuntu:~$ sudo python3 /home/allianceserver/myauth/manage.py migrate [sudo] password for dadi2015: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/init.py", line 130, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 185, in init super().init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/allianceserver/myauth/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/migrate.py", line 75, in … -
from django.http import HttpResponse, JsonResponse ModuleNotFoundError: No module named 'django'
I am running a project in python 3.7 to obtain data from a server through a GET, for this I import the following: django.http import HttpResponse, JsonResponse When executing the project I get the following error as output: from django.http import HttpResponse, JsonResponse ModuleNotFoundError: No module named 'django' -
Django return field for each model object
I have two models Game and People. I'm trying to iterate through the People model & return a single CharField for each value that people has & save their score with their name to the Game when creating the game. (Don't want name to be a field, just save with the score). The error I'm currently getting with this is the following: no such column: home_game.score class People(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.name Game Model: class Game(models.Model): title = models.CharField(verbose_name="Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) for each in People.objects.all(): score = models.CharField(verbose_name=each.title, max_length=4) -
problem with displaying CSS and the image in django
I'm just not able to get the CSS properties to display on the browser and also the image. I don't know what I'm doing wrong,i'd appreciate someone helping me out with this. thank you. -
Filtering with wildcards in Django Rest Framework
I'm looking for a way to be able to filter my dataset in DRF using a wildcard. For example; I want to return any hostname in the below model that starts with 'gb'. I also have some requirements to search in the middle and the end of the hostname depending on usecase. I'd expect to be able to hi the following endpoint: /devices/?host_name=gb* and it return everything that has a host_name starting with gb. Model: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host_name = models.CharField(max_length=64) mgmt_ip_address = models.GenericIPAddressField() domain_name = models.CharField(max_length=64) class Meta: ordering = ['host_name'] def __str__(self): return self.host_name Serializer: class DeviceSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Device fields = '__all__' View: class DeviceViewSet(viewsets.ModelViewSet): permission_classes = (DjangoModelPermissions,) queryset = Device.objects.all() serializer_class = DeviceSerializer filter_backends = [DjangoFilterBackend, filters.rest_framework.DjangoFilterBackend, drf_filters.SearchFilter] filter_fields = ['id', 'host_name', 'mgmt_ip_address', ] I have tried creating custom filters but not sure that is the right approach since I haven't been able to get it working. -
Using Django, should I implement two different url mapping logics in my REST API and web application, and how?
I have a Book model an instance of which several instances of a Chapter model can be linked through Foreign Key: class Book(models.Model): pass class Chapter(models.Model): book = models.ForeignKey(to=Book, ...) class Meta: order_with_respect_to = "book" I decided to use Django both for the RESTful API, using Django Rest Framework, and for the web application, using Django Template. I want them separate as the way should be open for another potential application to consume the API. For several reasons including administration purposes, the API calls for a url mapping logic of this kind: mylibrary.org/api/books/ mylibrary.org/api/books/<book_id>/ mylibrary.org/api/chapters/ mylibrary.org/api/chapters/<chapter_id>/ For my web application, however, I would like the user to access the books and their contents through this url mapping logic: mylibrary.org/books/ mylibrary.org/books/<book_id>-esthetic-slug/ mylibrary.org/books/<book_id>-esthetic-slug/chapter_<chapter_order>/ The idea is the router to fetch the book from the <book_id>, whatever the slug might be, and the chapter according to its order and not its ID. Now I need some advice if this is desirable at all or if I am bound to encounter obstacles. For example, how and where should the web app's <book_id>/<chapter_order> be "translated" into the API's <chapter_id>? Or if I want the web app's list of books to offer automatically generated slugged links … -
Using value from URL in Form Wizard for Django
I'm trying to use this Form Wizard to design a multipage form in Django. I need to catch a value from the URL, which is a client's ID, and pass it to one of the Forms instance, as the form will be built dynamically with specific values for that client. I have tried redefining the method get_form_kwargs based on this thread, but this isn't working for me. I have the following code in my views.py: class NewScanWizard(CookieWizardView): def done(self, form_list, **kwargs): #some code def get_form_kwargs(self, step): kwargs = super(NewScanWizard, self).get_form_kwargs(step) if step == '1': #I just need client_id for step 1 kwargs['client_id'] = self.kwargs['client_id'] return kwargs Then, this is the code in forms.py: from django import forms from clients.models import KnownHosts from bson import ObjectId class SetNameForm(forms.Form): #Form for step 0 name = forms.CharField() class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id def __init__(self, *args, **kwargs): super(SetScopeForm, self).__init__(*args, **kwargs) client_id = kwargs['client_id'] clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id)) if clientHosts: for h in clientHosts.hosts: #some code to build the form When running this code, step 0 works perfectly. However, when submitting part 0 and getting part 1, I get the following error: _init_() got an unexpected keyword … -
How to receive the emails from the user, using office365 mail credentials, In `Django`?
As office 365 requires to use only the HOST_USER mail as the sender, tha mail which was used to buy the office365 credentials. So how can we receive the mail from the user. -
how to jquery ajax json response for loop / django
django model class UserAlbum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='albums') album_photos = models.ManyToManyField(Photo, through='AlbumPhoto') album_name = models.CharField(max_length=50, blank=False) is_private = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_created'] def __str__(self): return f"{self.user}'s album [{self.album_name}]" def get_absolute_url(self): return reverse('album:album', args=[self.user, str(self.id)]) django view @login_required def get_album_list(request): if request.method == 'GET': user = request.user albums = user.albums.all() return JsonResponse(serializers.serialize('json', albums), safe = False) script $("#album_list_modal_button").click(function () { $.ajax({ type: "GET", url: "{% url 'album:get_album_list' %}", dataType: "json", success: function (response) { if (response) { //test $("#modal_body_album_list").html(response) //loop test 1 $.each(response, function(i, item) { $("#modal_body_album_list").append(item.fields.album_name); }); //loop test 2 for (var i = 0; i < response.length; i++) { $('#modal_body_album_list').append('<li>'+response[i].fields.album_name+'</li>'); } } else { $("#modal_body_album_list").html('None'); } }, error: function (request, status, error) { window.location.replace("../user/login") }, }); }) what i need to do is print each albums name using iteration only test part works and printed like this. [{"model": "album.useralbum", "pk": 6, "fields": {"user": 6, "album_name": "test album name1", "is_private": true, "date_created": "2021-03-26T19:20:23.571"}}, {"model": "album.useralbum", "pk": 4, "fields": {"user": 6, "album_name": "test album name2", "is_private": false, "date_created": "2021-03-18T20:30:09.575"}}] i've searched and find two way of loop. But these are not working. please help!! -
Python DJANGO input fields
I want to make simple "calculator" on django app. I want to make 2 fields. Visitor put 2 numbers into fields and multiplication this numbers. I want to make input1 = 2, input2 = 3 and output will be 6. only this inputs make customer on website. Thanks for help and hve a great day -
How to handle excel file sent in POST request in Django?
I sent an excel file in a post request to my back-end and I tried handling the file using the following: def __handle_file(file): destination = open('./data.xslx', 'wb') for chunk in file.chunks(): destination.write(chunk) destination.close() However, the output from that is not an excel file. It is a collection of XML files. My end goal is to obtain a data frame from the file data that was sent so that I can extract the data. What is a clean way of handling this type of file? -
Why do I get "HTTP Error 404: Not Found" when installing pyaudio with pipwin in Python Django project in Windows 10?
I'm trying to install pyaudio with pipwin in a Python Django project in Windows 10. I first run CMD as admin in Windows 10. Then I run the command: pipwin install pyaudio and I get the following error: raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found the full output from the command: Package `pyaudio` found in cache Downloading package . . . https://download.lfd.uci.edu/pythonlibs/z4tqcw5k/PyAudio-0.2.11-cp38-cp38-win_amd64.whl PyAudio-0.2.11-cp38-cp38-win_amd64.whl Traceback (most recent call last): File "C:\Users\Knowe\AppData\Local\Programs\Python\Python38\Scripts\pipwin-script.py", line 11, in <module> load_entry_point('pipwin==0.5.1', 'console_scripts', 'pipwin')() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\command.py", line 103, in main cache.install(package) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 300, in install wheel_file = self.download(requirement) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 294, in download return self._download(requirement, dest) File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pipwin\pipwin.py", line 290, in _download obj.start() File "c:\users\knowe\appdata\local\programs\python\python38\lib\site-packages\pySmartDL\pySmartDL.py", line 267, in start urlObj = urllib.request.urlopen(req, timeout=self.timeout, context=self.context) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 531, in open response = meth(req, response) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 640, in http_response response = self.parent.error( File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 502, in _call_chain result = func(*args) File "c:\users\knowe\appdata\local\programs\python\python38\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Why can I not install pyaudio? Thanks! -
Error while installing mysqlclient in django project on cPanel
I've been trying to solve this problem for a couple of days. I am trying to put my Django project in a venv on cPanel and install mysqlclient. So after setting up my Python (version = 3.7.8) on Cpanel, I installed Django version 3.1.7 and mysqlclient from the terminal using pip install django and pip install mysqlclient. However when I try to install mysqlclient, this error pops out. Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/canggihmallmy/virtualenv/django_test/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))'bdist_wheel -d /tmp/pip-wheel-scx4wswm cwd: /tmp/pip-install-ct08p_k4/mysqlclient_5cd61bc8b4de40efb5731cfe082b4d65/ Complete output (43 lines): mysql_config --version ['10.0.38'] mysql_config --libs ['-L/usr/lib64', '-lmysqlclient', '-lpthread', '-lz', '-lm', '-ldl', '-lssl', '-lcrypto'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mysqlclient', 'pthread', 'm', 'dl'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> …