Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test if a method is called in django rest framework
I am currently struggling with testing one of my APIs localhost:<port No.>/blah/. My model is class class1(models.Model): field_a = models.integerfield(...) field_b = models.integerfield(...) I have also a serializer: class Class1Serializer(serializers.ModelSerializer): class Meta: model = Share fields = '__all__' this is my view: from .utils import prop lass Class1View(viewsets.GenericViewSet, mixins.CreateModelMixin, ): queryset = Share.objects.all() serializer_class = ShareSerializer def perform_create(self, serializer, *args, **kwargs): _field_a = serializer.validated_data['field_a'] _field_b = serializer.validated_data['field_b'] if _field_a == 1: prop(test.objects.get(field_b = _field_b)) my urls.py is : router = routers.DefaultRouter() router.register(r'blah', Class1View) Also, I have utils.py def prop(Share): pass how can one write a test to check if the prop is called? -
Use Sendgrid templates or Django templates?
I have Django application that sends emails via Sendgrid. I know that Sendgrid has own templates for transactional emails. Also Django has its own and is able to generate html for emails on application side. Is it a normal to generate html content for emails on application side? Or should I always use Sendgrid templates and use substitutions? For which cases? If only Sendgrid templates - how to manage them and keep up to date? Is it ok to sync templates stored in Django app to Sendgrid via API on start up? -
How to check if a database entry is older than x minutes old
I'm writing an API in Django to store support tickets in a database. This consists of an Error ID, email address, phone number, image file of the problem, and the date/time the entry was submitted. Due to the nature of the use case here, I need to poll the API every 10 minutes or so with a request to check on the status of all tickets. What I want to do is automatically delete every ticket that is unresolved for over 10 minutes (not immediately delete on 10 minutes, but when the API is polled and finds that the entry is over 10 minutes old). I thought that including the date/time column would help me but I can't think of any way of doing the check that isn't super messy. The data type is models.DateTimeField and the database I'm using is MariaDB. -
How to Download BinaryField in django admin?
I am working on a legacy system, where an institution's logo field is declared as a BinaryField, I was able to upload the file using the file input widget, how can I edit the registry to be able to download the file? As with FileField -
Slides are not switching in Bootstrap carousel inside Django template
The problem is probably active class. I don't know why but it's not switching between classes inside {% for %} loop. The problem occurs both when trying to change the slides manually or automatically {% if homepage.display_carousel %} <div class="bd-example"> <div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for slide in homepage.carousel.all %} <li data-target="#carouselExampleCaptions" data-slide-to="{{forloop.counter0}}" class="{% if forloop.first %} active {% endif %}"></li> {% endfor %} </ol> <div class="carousel-inner"> {% for slide in homepage.carousel.all %} {% if slide.display %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img src="{{slide.img.url}}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>{% trans slide.title %}</h2> {% if slide.button %}<a href="{{slide.button_url}}"class="btn">{% trans slide.button %}</a>{% endif %} {% if slide.subtitle %}<p class="carousel_text_p">{% trans slide.subtitle %}</p> {% endif %} </div> </div> {% endif %} {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> {% endif %} -
Deploying Django to Google cloud platform
I'm working on a project which is a django backend application , the application at some point relies on the file system to read and write videos and also load tensorflow models. Is it possible to use google app engine to run my django app or do I need to rent a VM ? Thanks -
Hi, I created Dockerfile and docker-compose but gives me this error django-apache2 exited with code 0 when i write docker-compose up
I created Dockerfile and docker-compose but gives me this error django-apache2 exited with code 0 when i write docker-compose up Dockerfile FROM ubuntu:18.04 RUN apt-get -y update && apt-get -y upgrade RUN apt-get -y install python3.8 RUN apt-get -y install python3-pip RUN apt -y install apache2 RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN pip3 install --upgrade pip COPY ./requirements.txt ./requirements.txt RUN apt-get -y install python3-dev RUN apt-get -y install python-dev default-libmysqlclient-dev RUN pip3 install -r ./requirements.txt COPY ./apache.conf /etc/apache2/sites-available/000-default.conf RUN mkdir /var/www/api/ COPY ./project/. /var/www/api/ WORKDIR /project/ Docker-compose version: "3" services: django-apache2: container_name: "django-apache2" build: . ports: - "8005:80" -
Django register and login endpoints error : AttributeError: 'AnonymousUser' object has no attribute '_meta'
It's my first time using DRF and I'm trying to make an endpoint for registration and login. When I try to login with a new created user, it would give me this error. AttributeError: 'AnonymousUser' object has no attribute '_meta' I'm not sure what the problem is. Although I did notice that when I create a new user and check out through admin, it would say this in the password field. invalid password format or unknown hashing algorithm But, when I add a new user through admin it would say this. *algorithm: pbkdf2_sha256 iterations: 150000 salt: qJZGic****** hash: cVr+WP* And login would work when the user is added through admin. Also, when I print out this code user = authenticate( request = self.context.get('request'), username = email, password = password, ) print(user) it would print out "none". I'm not sure if this is normal or if I'm just doing everything wrong... model.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_active=True, is_staff=False, is_admin=False): user_obj = self.model(email=self.normalize_email(email)) user_obj.set_password(password) user_obj.active = is_active user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_user(self, email, password): user = self._create_user( email, password=password, is_staff=True, ) return user def create_superuser(self, email, password): user = self._create_user( email, password=password, is_staff=True, is_admin=True, … -
How seletc distinct search_fields using django_search_views
I'm new to django and I'm having a search problem when I do the query you can repeat the tuple, but you have to return different tuples [...] from search_views.views import SearchListView from search_views.filters import BaseFilter [...] class RequestFilter(BaseFilter): search_fields = { 'search_text': ['comments', 'privilegiedComments', 'commentsDemands', 'landRecord__captancy__name', 'type__name', 'type__comments',], 'search_age_min': {'operator': '__gte', 'fields': ['date', 'deferment__concessionDate']}, 'search_age_max': {'operator': '__lte', 'fields': ['date', 'deferment__concessionDate']}, } class RequestListView(SearchListView): model = Request template_name = 'alimentation/request_list.html' form_class = RequestSearchForm filter_class = RequestFilter -
Django's Template Does Not Exist
enter image description hereI got an error which is a template that does not exist while I was created a template folder that contains a file. I had done necessary changes in setting.py file.enter image description here please guide me further to solve the error. -
Django changes data to tuple on save
I'm working on one project where when a customer registers on my website, I check if the user's email is already registered with the website or not. If the user is already registered then I simply update the old data with the new data which is entered by the user. But in the case of an update, Django changes the data to the tuple. Below is my code Models.py class Customer(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) email = models.CharField(max_length = 50) Views.py If email is there user_data = get_object_or_404(Customer, email = email) user_data.first_name = 'Test' user_data.save() But it changes the data in the database to the tuple. Like below DB first_name -> ('Test',) last_name -> ('Demo') When the customer registers for the first time, data is saved correctly. But when a user registers again there's a problem Kindly help with this I'm using Python 3.5 and Django 2.2 -
Displaying data in react from public API calls in django class based views
Ive been googling for a good few hours, ive learnt the basics of django rest-framework and react. Now im trying to make API calls in the backend using django class based views and then serve that up in a react frontend. I already have the project set up displaying a blank fron page in react. -
Best way to rotate Django.QuerySet
I want to rotate my QuerySet like collections.deque.rotate(). Now i do it like this: def do_rotate(queryset, n) my_list = list(queryset) return my_list [n:] + my_list [:n] How i can do it better? -
Django on nginx ubuntu server static files in admin not fount
I have setup my django project on a ubuntu server with nginx webserver. In my django settings.py file i set: STATIC_URL = '/static/' STATIC_ROOT = '/static/images/' STATICFILES_DIRS = [ '/var/www/core/frontend/static', '/.venv/lib/python3.6/site-packages/django/contrib/admin/static', ] whell, in my nginx.conf file i write: server { listen 80 default_server; listen [::]:80 default_server; } # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /static/ { alias /var/www/core/frontend/static/; } location / { proxy_pass http://127.0.0.1:8000; } but when i open the admin part of my project i get a lot of 404 error about css and js not found. Where i have to implement my code for correctly manage static admin file? So many thanks in advance -
Cannot decode russian symbols in pdf (xhtml2pdf)
Following this, I've created html to pdf converter and it works fine with english language, but I have some russian symbols that I cannot decode. Instead of normal russian words I get: тут должен быть текÑ■Ñ template: <html lang="ru"> <head> <meta charset="UTF-8"> <title>MC-report</title> </head> <body> <div style="align:center"> тут должен быть текст {{ today }}</div> </body> </html> I have same code (plus some code just to get needed data) as in this manual, instead of playing with html.encode and template: pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) #for decoding data, not template text None of cp1251/2/866 and UTF-8 won't work -
django Rest Framework filter by date range
I have view class given class eventList(ListAPIView): queryset = Event.objects.all().filter(is_active=1, is_approved=1) serializer_class = eventSerialiser filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] search_fields = ['event_name', 'event_address', 'start_date', 'start_time', 'end_time', 'age_max', 'age_min','event_organizer__name', 'event_type__name', 'event_city__name', 'event_tag__name'] filterset_fields = ['event_name', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_organizer', 'event_type', 'event_city', 'event_tag'] ordering_fields = '__all__' ordering = ['-id'] All filters working fine but how i can get data against date rang start_date and end_date -
Is there a way to change TCP settings for Django project?
I have been working on a project built with Django. When I run profiler due to slowness of a page in project, this was a line of the result: 10 0.503 0.050 0.503 0.050 {method 'recv_into' of '_socket.socket' objects} Which says almost 99% of passed time was for the method recv_into(). After some research, I learned the reason is Nagel's algorithm which targets to send packets only when the buffer is full or there are no more packets to transmit. I know I have to disable this algorithm and use TCP_NODELAY but I don't know how, also it should only affect this Django project. Any help would be much appreciated. -
Remove redundancy in requirements.txt in Django projects
I wonder if there is a tool by which we can figure out what packages are not in used in our requirements.txt because I have tons of dependencies written in the requirements.txt but I am sure a lot of them are not in use but at the same time I am not sure as well. Looking for some help via tools or any conventional method if thats possible. Thanks! -
Compare context variable django
How can I compare context variable in Django? I want to compare the name that I have saved in my model with request.user {% if user %} {% for x in user %} {% ifequal x request.user %} <h1>working</h1> {% else %} <h1>false</h1> {% endifequal %} {% endfor %} {% endif %} I want the following comparison: {{x}} == {{request.user}} Context dict {"user": Prod.objects.filter().values_list('name', flat=True)} User is here for example admin and request.user is also admin -
How to use SQLAlchemy Core with Django REST framework?
Django REST framework provides a lots of features such as serialization and database migrations by default. The main drawback is performing complex database queries which SQLAlchemy Core is excellent with. How can SQLAlchemy Core be reliably used with Django REST framework? OR If SQLAlchemy Core is a requirement should Flask and Flask-SQLAlchemy be used instead? This is for a new project so there is no committment to any specific solution yet. A recent talk at DjangoCon provided one approach although it looks to be difficult to maintain. -
renderer returned unicode, and did not specify a charset value
I am using Django 2.x and DRF. From my APIView, I want to return pdf or eps binary data file. class DownloadFile(APIView): serializer_class = DownloadFileSerializer renderer_classes = (BinaryFileRenderer,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) name = serializer.validated_data.get('name') data = serializer.validated_data.get('imgdata') mimetype = None data, mimetype = convert_file_to_pdf_or_eps(data) if data and mimetype: response = Response(data=data, content_type=mimetype) ascii_name = get_ascii_name(name, "QRCode") response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(filename.split()) return response else: return Response(status=status.HTTP_400_BAD_REQUEST, data='Either data or mime type was missing') and the BinaryFileRenderer from rest_framework.renderers import BaseRenderer class BinaryFileRenderer(BaseRenderer): media_type = 'application/octet-stream' format = None charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data This works fine for pdf data, but with EPS data, it gives error renderer returned unicode, and did not specify a charset value -
How to change the admin History link in django?
I want to change the behavior of the History button in the change view of admin. Instead of going to the default page, I want the button to take the user to another url within the application. Is this possible? -
Could django reload urls.py when running?
I encounter a weird problem with my django app. There is a known issue that sometimes one dependency would failed to be imported in views.py, but it could result in a 500 Internal Server Error which was triggered by not only a request to the unrelated views, but also a request to the static files. The error message indicates that the error occured when the framework was resolving the url, and the resolver was trying to import urls.py which would import the views.py. The stack trace of the 500 error is as follows. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 172, in _get_response resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 362, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ...... I had briefly read the django/urls/resolvers.py and found that the import_module() function, the source of this problem, would be called by a … -
Is that possible to store array in mysql database using django model?
i have a array of values and want to store in mysql database using django model.py. what are the possible ways that i can store array values -
Django URLs giving error The current path, carmodels/Tata/ZEST/XE Petrol, didn't match any of these
My urls.py urlpatterns = [ url(r'^$', home_view, name='home'), url(r'^home/', home_view, name='home'), url(r'^search/', search, name='search'), url(r'^select/', search, name='select'), url('ajax/home_view/',home_view, name='ajax_load_models'), url(r'^carmodels/(?P<product_make>\w+)/(?P<model_name>\w+)/(?P<variant>\w+)/$', search, name='product_detail'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My href link in html <a href="/carmodels/{{ item.product_make }}/{{ item.model_name }}/{{ item.variant }}" class="card-title">{{ item.product_make }} {{ item.model_name }} {{ item.variant }} </a> I am new to django,could you please tell me what am I doing wrong? Or how to write multiple slashes in url