Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django as ORM - Perform update query asynchronously without blocking
I'm using Djang as my ORM. As part of my code I want to initiate an update request some_object = SomeObject.objects.get(...) calculated_value = func(some_object.value1, some_object.value2) some_object.value1 = calulated_value # This line should happen asynchrnoously and I don't if it fails some_object.save() # Can be replaced with some_object.update(value=calculated_value) # continue doing other stuff The line some_object.save() has some latency, but actually, I don't really mind if it fails, and I don't need its result. I want it to be handled by Django without the rest of the code waiting for it -
Issue with requests in django rest framework
I created an API using django restframework. It works well on the django development server. When the application is migrated to a web server (apache mod wsgi, nginx - gunicorn) it works fine only if the pagination is set to 100 records per page, if the pagination is set to more than 100 records, requests between 100 and 200 records They remain stalled or blocked. I deployed the application in Apache with wsgi and gunicorn with nginx. But the problem persists. It works perfect on the django development server with any page size and works well on the server if I set the page size to 100 records. View class SoftwareList(generics.ListCreateAPIView): queryset = SoftwareModel.objects.all().order_by('-id') serializer_class = SoftwareSerializer http_method_names = ['get'] filter_backends = (DjangoFilterBackend,) filter_fields = ('product_type',) Settings REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } Expected: The request with a pagination different than 100. Actual: Request Stalled/Blocking -
I want to create a comment form of user (Create Edit and Delete comment button) with DetailView and FormMixin
I want to create a comment form of user (Create, Edit and Delete Comment) with DetailView and FormMixin. My user can created comment. But when i create button to edit or delete comment. I don't know what should i do now. class Comment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='comments', null=True) user_commented = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) reply = models.ForeignKey('Comment', on_delete=models.CASCADE, null=True, related_name="replies") comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return '{} {}'.format(self.book.title, self.user_commented) This is my ModelForm class CommentForm(ModelForm): comment = forms.CharField(label="", widget=forms.Textarea(attrs={'title': 'Comment', 'class': 'form-control', 'placeholder': 'Text Input Here !!!', 'style': 'margin-left: 40px', 'rows': 4, 'cols': 100})) class Meta: model = Comment fields = ('comment',) exclude = ('user_commented', 'book') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.book = kwargs.pop('book') super(CommentForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('comment', css_class='form-group col-12 m-auto',), css_class='form-group' ), FormActions( Submit('save', 'Submit', css_class='btn-success'), ), ) I don't know how to create update or delete with form in view logic. class BookDetailView(FormMixin, generic.DetailView): model = Book template_name = 'catalog/book_detail.html' query_pk_and_slug = True form_class = CommentForm def get_form_kwargs(self, *args, **kwargs): kwargs = super(BookDetailView, self).get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user.username kwargs['book'] = Book.objects.get(slug=self.kwargs.get(self.slug_url_kwarg)) return kwargs def get_success_url(self): return reverse('catalog:book-detail', … -
adding formset fields dynamically in django with javascript
I created a js function which increments ID's of formset fields. The idea is to add and remove fields dynamically. However when I delete a field dynamically and click submit the form doesn't submit.The error the form displays is that the field I deleted is required. Where do I need to make some changes to be able to remove fields dynamically and don't get an error that the field i deleted is required for submittion? This is how my django template looks like: <ul class="clone--list"> {% for skill_form in skill_formset %} {% for hidden in skill_form.hidden_fields %} {{ hidden }} {% endfor %} <li> {{ skill_formset.management_form }} {{ skill_form.errors }} {{ skill_form.skill_name }} <a class="clone--add" id="add_skill">>Add Skill</a> <a class="clone--remove">Remove</a> </li> {% endfor %} </ul> javascript: $(".clone--list").on("click", ".clone--add", function () { var parent = $(this).parent("li"); var copy = parent.clone(); parent.after(copy); copy.find("input[type='text'], textarea, select").val(""); copy.find("*:first-child").focus(); updateskill(); }); $(".clone--list").on("click", "li:not(:only-child) .clone--remove", function () { var parent = $(this).parent("li"); parent.remove(); updateskill(); }); function updateskill() { var listskill = $("ul.clone--list li"); listskill.each(function (i) { var skill_TOTAL_FORMS = $(this).find('#id_form-TOTAL_FORMS'); skill_TOTAL_FORMS.val(listskill.length); var skill_name = $(this).find("input[id*='-skill_name']"); skill_name.attr("name", "form" + i + "-skill_name"); skill_name.attr("id", "id_form-" + i + "-skill_name"); }); } view: def profile_edit(request): skill_instance = ProfileSkill.objects.filter(profile__user_id=request.user.id) if request.method … -
YouTube request works fine on dev server, but is declined when sent from VM prod server
The following code (from views.py) is used to download YouTube mp3 from video with pytube library, and is working fine on development server: import os from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from pytube import YouTube # Create your views here. def index(request): url = 'https://www.youtube.com/watch?v=v2JsxXxf1MM' audio = get_audio(url) download(audio) return HttpResponse('Downloaded!!!') def get_audio(url): yt =YouTube(url) all_streams = yt.streams.all() audio_mp4_stream_itag= [stream.itag \ for stream in all_streams \ if stream.mime_type == 'audio/mp4'][0] audio = yt.streams.get_by_itag(audio_mp4_stream_itag) return audio def download(audio): dst = os.path.join(settings.BASE_DIR, 'tester', 'audio') audio.download(dst, 'downloaded_audio') However, when I run the project on my Digital Ocean droplet (Ubuntu VM), YouTube blocks the request. The error is: Traceback (most recent call last): File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/requests_test/requests_test/tester/views.py", line 14, in index audio = get_audio(url) File "/root/requests_test/requests_test/tester/views.py", line 22, in get_audio yt =YouTube(url, on_progress_callback=log) File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 88, in init self.prefetch_init() File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 96, in prefetch_init self.prefetch() File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 160, in prefetch self.watch_html = request.get(url=self.watch_url) File "/root/testenv/lib/python3.5/site-packages/pytube/request.py", line 21, in get response = urlopen(url) File "/usr/lib/python3.5/urllib/request.py", line 163, in … -
Django validator not preventing invalid IPv4 address from being added to database
I am experimenting with Django's validate_ipv46_address validator in my model: class Policy(models.Model): ... omitted for brevity ... allowed_network_ips = ArrayField(models.CharField(max_length=225, null=True, validators=[validate_ipv4_address])) ... I have a view with a POST method that creates a Policy object which looks like: class PolicyView(generics.GenericAPIView): ... def post(self, request, namespace_id): ... allowed_network_ips = request.data.get('allowed_network_ips') ... try: np = Policy.objects.create( ... allowed_network_ips=allowed_network_ips, ... ) serialized_np = PolicySerializer(np, many=False) except Exception as ex: ... return Response({"message": message}, status=status.HTTP_400_BAD_REQUEST) return Response(serialized_np.data, status=status.HTTP_200_OK) I am testing this with this curl script that has an invalid ipv4 address. The curl script looks like this: curl -v -X POST \ "http://example.com/namespace/49/policy" \ ... -d '{ "..., "allowed_network_ips": ["not.an.ipv4.addres"], ... }' I was hoping I would get some sort of error because I do not think not.an.ipv4.addres is a valid ipv4 address (I could be wrong there), but the POST works and a Policy with allowed_network_ips of not.an.ipv4.addres gets created. What am I doing wrong here? -
Annotation field is str instead of datetime.datetime
Example I'm trying to annotate objects using data from a related model's DateTimeField. class Author(models.Model): name = models.CharField(max_length=256) class Book(models.Model): name = models.CharField(max_length=256) is_published = models.BooleanField() publication_date = models.DateTimeField() author = models.ForeignKey(Author, on_delete=models.PROTECT) queryset = Author.objects.annotate( has_unpublished=Exists( Book.objects.filter( author=OuterRef('pk'), is_published=False)) ).annotate( last_published_date=Max( 'book__publication_date', filter=Q(book__is_published=True) ) ) I alternate between the default local sqlite3 database and MySQL (with mysqlclient). SQLite works and MySQL crashes. Here's the reason: compilers for both databases results = compiler.execute_sql(**kwargs) return a list of lists of tuples of int and string, like so: SQLite <class 'list'>: [[(1, 'Alice', 1, '2017-01-01 01:00:00'), (2, 'Bob', 0, '2019-01-05 13:00:00'), (3, 'Carol', 1, None), (4, 'Dan', 0, None)]] MySQL <class 'list'>: [((1, 'Alice', 1, '2017-01-01 01:00:00.000000'), (2, 'Bob', 0, '2019-01-05 13:00:00.000000'), (3, 'Carol', 1, None), (4, 'Dan', 0, None))] Now, when the SQLite backend sees a supposed datetime field, it generates a converter at runtime using this method: django.db.backends.sqlite3.operations.DatabaseOperations def convert_datetimefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.datetime): value = parse_datetime(value) if settings.USE_TZ and not timezone.is_aware(value): value = timezone.make_aware(value, self.connection.timezone) return value which works ok. The MySQL backend, however, does this: django.db.backends.mysql.operations.DatabaseOperations def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) … -
Informix db conection driver for django?
can some1 help me with any example to connect django 5.8 with external informix db, i am try some driver but I don't get positive results -
Call a Django Rest Framework view within another Django Restframework view
I've searched stack overflow and the internet for a solution to call a django restframework ListAPIView from anotehr django restframework APIView. I've tried: class ViewA(APIView): def get(request): response = ViewB.as_view({'get':'list'})(request) print response.render() # do other things with the response However, I get the error: response = SubsidiariesStatisticsView.as_view({'get': 'list'})(request) TypeError: as_view() takes exactly 1 argument (2 given) How do I pass in a request from viewA to viewB and get a response? Also, class ViewB has a get_serializer_context method. How do I call that from ViewA? -
Django form creates default User rather than acustom User. How do I create a Custom User?
Trying to extend Django's basic user model to a custom user model. I have a form for users to register, but when the form is sent it creates a default user, not a custom user. I want it to create a custom user. The only way I seem to be able to create a custom user currently is through admin. Here is my Django custom user model, which exists and can add users via admin. class MyUserManager(BaseUserManager): def create_user(first_name, last_name, zipcode, email, username, password): if not first_name: raise ValueError("Users must have a first name.") if not last_name: raise ValueError("Users must have a last name.") if not zipcode: raise ValueError("Users must have a zipcode.") if not email: raise ValueError("Users must have an email.") if not username: raise ValueError("Users must have a username.") if not password: raise ValueError("Users mush have a password.") user=self.model( first_name = first_name, last_name = last_name, zipcode = zipcode, email=email, is_logged_in=is_logged_in, is_bot=is_bot ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25, validators … -
Django urls slug must contain word
here is my URL: /jobs-in-new-york here is my urls.py url(r'^account/', include('.account.urls')), url(r'^account/', include('allauth.urls')), url(r'^payment/', include('.payments.urls', namespace='payments')), url(r'^student/', include('.student.urls')), url(r'^employer/', include('.employer.urls')), url(r'^(?P<slug>[-\w\/]+)', JobSearchView.as_view(), name='job_search') How can I change this regex ^(?P<slug>[-\w\/]+) so that if slug contains word jobs, it gets matched! -
How to get data from google classroom api?
I need to get classroom info and course posts from google-classroom. Thus I have used oauth to authorize user first. And then access data using the googles quickstart.py example def authorized(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES) flow.redirect_uri = 'http://localhost:8000/google-class/oauth2callback/' flow.code_verifier = rs authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') request.session['state'] = state some = state print("/n" + "The state is =" + state + "/n") return redirect(authorization_url) def oauth2callback(request): state = request.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES, state=state) flow.redirect_uri = 'http://localhost:8000/google-class/oauth2callback/' flow.code_verifier = rs authorization_response = request.get_full_path() # print(request.get_full_path()) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials # request.session['credentials'] = credentials_to_dict(credentials) cred = credentials_to_dict(credentials) if 'credentials' in request.session: # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( cred["token"], refresh_token = cred["refresh_token"], token_uri = cred["token_uri"], client_id = cred["client_id"], client_secret = cred["client_secret"], scopes = cred["scopes"]) service = googleapiclient.discovery.build(API_SERVICE_NAME,API_VERSION, credentials=credentials) # Call the Classroom API results = service.courses().list(pageSize=1).execute() print('somethign ') print("blaad,lasd," + results) courses = results.get('courses', []) if not courses: print('No courses found.') else: print('Courses:') for course in courses: print(course['name']) return render(request,'api/google-class.html') But when the oauth2callback() is called it goes straight to the return statement instead of printing. And the terminal gives - "GET /google-class/oauth2callback/?state=KG8awXXNDQehgDEKcRbltVBxrv4Lxv&code=4/nQHoFfykiDmkS_CPg_zGvCJxJyob52r7TLcUsDTrEJRck0nLZki7Ukf9aiug6kqR0NMs6KrKQiCMKCIod-e1Iao&scope=https://www.googleapis.com/auth/classroom.courses.readonly HTTP/1.1" 200 5273 so how can I get the classroom names here? -
Why is coverage.py looking for a file titled 'blub'?
I'm working on a django project and recently installed coverage.py to generate coverage reports for our unit and integration tests. When I generate the report, it gives the following error message: " blub NoSource: No source for code 'home/me/Documents/myProject/blub'. Aborting report output, consider using -i. " The report then prints out and looks mostly normal. However, if I subsequently try to generate the report as html, the same error is printed and the index.html file is not generated. Does anyone know why coverage is looking for 'blub' or how I can disable it? I have tried specifying source, as described in django documents as follows: coverage run --source='.' manage.py test coverage report coverage html -
Django does not find static files for serving
I am trying to serve some static files. This is my project structure: Django Project Structure I am trying to serve all static files in the "(...)/templates/architectui/assets". For that I updated this line in the settings.py for the django project: STATIC_URL = 'templates/architectui/assets/' And this is how my urls.py in the "dashboard" app looks like: from django.urls import path from dashboard import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", views.index, name="index"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Unfortunately if I try to open one of the files within the "assets" dir like for example "http://127.0.0.1:8000/dashboard/images/avatars/1.jpg" the following error occurs: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/images/avatars/1.jpg Using the URLconf defined in frontend.urls, Django tried these URL patterns, in this order: admin/ dashboard/ [name='index'] dashboard/ ^templates/architectui/assets/(?P<path>.*)$ The current path, dashboard/images/avatars/1.jpg, didn't match any of these. Has anyone an idea on how to fix this issue? -
Wheel for mysqlclient
I tried to dowload mysqlclient and it give me this error Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\acer\appdata\local\programs\python\python37- 32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Acer\\Ap pData\\Local\\Temp\\pip-install-4p7ik_w4\\mysqlclient\\setup.py'"'"'; __file__=' "'"'C:\\Users\\Acer\\AppData\\Local\\Temp\\pip-install- 4p7ik_w4\\mysqlclient\\se tup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open) (__file__);code=f.read().re place('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"' exec'"'"'))' bdist_wheel -d 'C:\Users\Acer\AppData\Local\Temp\pip-wheel- l3n80_sf ' --python-tag cp37 cwd: C:\Users\Acer\AppData\Local\Temp\pip-install-4p7ik_w4\mysqlclient\ Complete output (30 lines): I installed wheel for mysqclient and it give me C:\Users\Acer>pip3 install C:\Users\Acer\Desktop\mysite\mysqlclient-1.4.2- cp35-c p35m-win32.whl ERROR: mysqlclient-1.4.2-cp35-cp35m-win32.whl is not a supported wheel on this platform. I'm using windows 7 32bit python 3.7.4 and wondering if there is any wheel for windows 7 32 bit or if I can install mysqlclient without wheel I alerady installed c++ builds tools and django and when I tried to upgrade wheel it tell me that all requirement exist and there is no update for wheels or env -
Xamarin.Forms with Django REST API
I am working on a Xamarin.Forms application and want to have both a website and an app for my application. If I have built a website with Django Web Framework and use a REST API to POST/GET information to and from the server, is that good practice? Are there many downsides associated with Python web framework sending JSON data via a REST API. Thank you for your help! -
How to automate django deployment?
OK, I am desperate enough to finally post a github question. SUMMARY: Django deploy -> digital ocean droplet -> nginx and gunicord + git pull It works, but manually writing all the commands is way to tedious + error prone. I have been trying to find a suitable tool ever since, and kinda need some advice. SOO FAR: I have tried Fabric, BUUUT complexity and simplicity baffles me. Some tutorial are way to trivial, some are way too complex and 95 % of them seems to be outdated(this seems relevant in this case , because syntax has changed drastically) In addition, the most basic example in docs don't work no matter how many times I have tried to correct it(ssh connection vie password). P.S. I am completely new to devops, so a lot of things is confusing for me Beside that, I have tried to dive into some other tools like bash scripting and ansible and dropped them shortly after, mainly due to them not being as alluring as Fabric seems to be. My question is! Should I continue tring to solve Fabric, or is there some other commonly used way to make deployment a simple and enjoyable matter while … -
Writing django validators. Do i need a own file for validators?
In the Django Manuel is an example for Writing validators. https://docs.djangoproject.com/en/2.2/ref/validators/ qoute For example, here’s a validator that only allows even numbers: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) You can add this to a model field via the field’s validators argument: > from django.db import models > > class MyModel(models.Model): > even_field = models.IntegerField(validators=[validate_even]) qoute end But where should i put this code? from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) should i create a own File like validator.py or should i put this in the model? -
How to save a fileField's path without writing the file itself to reflect an external change
I have a model that includes a FileField, the path to which I want to update without writing the file itself via the storage system. Usually the file would be saved from a form upload, but when the file location is updated externally, I don't want to re-write the file in order to update the DB entry. I've tried to use the field's.save() method, but that requires the file's content to be supplied. I'd want to only change the related DB entry so that the storage system can find the file again. -
'NoneType' object has no attribute 'seventh_five' despite the existence of the object
I am creating a website where a user can create a project. Each project has 10 macro-questions. Each macro-question has sub-questions. I am trying to retrieve the answer to a macro-question. projects_id contains all the projects in my database. for project_id in projects_id: seventh_question_project = Seventhquestion.objects.all().filter(project=project_id).first() answer_seventh_five = seventh_question_project.seventh_five if answer_seventh_five == "No": unaudited_projects.append(answer_seventh_five) else: audited_projects.append(answer_seventh_five) If I use the console, I am able to retrieve answer_seventh_five: however, if load the page, I get: 'NoneType' object has no attribute 'seventh_five' Which I cannot explain since answer_seventh_five exists (as I tested it by retrieving it via console) -
Make api calls inside Serializer create vs ModelViewSet create
I have this API end point, see below: from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter from wish_list.views import WishListViewSet router = DefaultRouter() router.register('wish-list', WishListViewSet, base_name='wish-list') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ] My goal is to receive data from a POST request and use this data to make an API call and save these data(title and isbn_13) into my WishList object. This is my views.py import json import requests from django.core import serializers from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import WishList from .serializers import WishListSerializer class WishListViewSet(viewsets.ModelViewSet): serializer_class = WishListSerializer queryset = WishList.objects.all() http_method_names = ['get', 'post', 'delete', 'head'] def create(self, request, *args, **kwargs): ol_id = request.data.get('ol_id') try: wish_list_obj = WishList.objects.get(ol_id=ol_id) except WishList.DoesNotExist: return super(WishListViewSet, self).create( request, *args, **kwargs ) return Response(serializers.serialize('python', [wish_list_obj, ]), status.HTTP_200_OK) def perform_create(self, serializer): try: response = self._open_library_book_response( serializer.validated_data.get('ol_id')) except requests.exceptions.RequestException: return Response( { 'Error Message': "Could not get a valid response " "from Open library's Book API" }, status=status.HTTP_503_SERVICE_UNAVAILABLE ) parsed_response = self._parse_response(response) serializer.save( title=parsed_response.get('title'), isbn_13=parsed_response.get('isbn_13'), ) @staticmethod def _open_library_book_response(ol_id: str) -> requests.models.Response: """ Make request to open library to get the details of a specific book. """ open_library_url = … -
Why does my url return data sometimes and return error 404 not found others?
I have a django website, I have multiple INSTALLED_APPS listed in the settings.py. One being the app that I am having trouble with. This app loads properly sometimes, but randomly it returns with a 404 error. I also have an ajax call from the app which also will go to the server and get the json data sometimes but even a second later when i try again it returns a 404 error. If i run it again it will usually return the json data, but sometimes again the 404 error. There is no difference in the call to the server that returns the data or the 404 error. I can see in the debug of the 404 error response that it says "Using the URLconf defined in website.urls, Django tried these URL patterns, in this order:" and the app path is not listed in the patterns but the other installed apps are. Of course the times it works the path must be listed. It seems to fail approximately 25% of the calls. Is there something that is cached in django that reverts the URLconf to an earlier version that doesn't include the new installed app randomly? Any suggestions are welcome, … -
media files saved manually not showing ?Saving images in image fields manually and showing them in deployment?
I have a Django app where users can upload images and can have a processed version of the images if they want. and the processing function returns the path, so my approach was model2.processed_image = processingfunction( model1.uploaded_image.path) and as the processing function returns path here's how it looks in my admin view not like the normally uploaded images In my machine it worked correctly and I always get a 404 error for the processed ones while the normally uploaded is shown correctly when I try change the url of the processed from myurl.com/media/home/ubuntu/Eyelizer/media/path/to/the/image to myurl.com/media/path/to/the/image so how can i fix this ? is there a better approach to saving the images manually to the database ? I have the same function but returns a Pil.image.image object and I've tried many methods to save it in a model but i didn't know how so I've made the function return a file path. -
Django HTML-Template media links are not being served
I have a django app with which I try to serve a prebuilt html template from my python app. I can access the template, but the total layout etc. is corrupted because all src="" links are pointing to a django 404 page. My app: --> http://127.0.0.1:8000/dashboard/ (WORKS) Example media link: --> http://127.0.0.1:8000/dashboard/assets/images/avatars/1.jpg (NOT WORKING) This is my views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'templates/name/index.html') How can it be accomplished that django serves the complete folder with all files in it and not only the index.html page? -
Scrapy imports really slow
I am trying to use Scrapy but the setup time is really slow. start_time = time.time() from scrapy.spiders import SitemapSpider from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots from scrapy.http import Request from scrapy.linkextractors import LinkExtractor print('Completed imports. Total time: ' + str(time.time() - start_time)) # Completed imports. Total time: 5.819392919540405 Why is this so slow? Has Scrapy cached data somewhere that it's loading each time it starts up?