Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
develope online questionnaire web app with Django
I have a Django website already and I want to upload several questionnaires to my clients can answer online. so that I can receive and interpret the answers in Django admin dashboard. Each questionnaire has several questions and the answer to each question can be multiple choice or descriptive. I created the table of Question in model.py and the questions will be write on the website through the Django admin dashboard. Now I have trouble with UserAnswer class in models.py and the UserAnswerForm in forms.py, and I also had trouble with the views and Html codes. when I submit a questionnaire no item save in Django admin dashboard. models.py: import os from django.db import models from django.contrib.auth.models import User def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): name, ext = get_filename_ext(filename) final_name = f"{instance.id}-{instance.title}{ext}" return f"image/{final_name}" # Create your models here. class AssessmentsManager(models.Manager): def get_by_id(self, assessment_id): qs = self.get_queryset().filter(id=assessment_id) if qs.count() == 1: return qs.first() else: return None class Assessments(models.Model): title = models.CharField(max_length=200, null=True, verbose_name='عنوان پرسشنامه') description = models.TextField(max_length=2500, null=True, blank=True, verbose_name='توضیحات') image = models.ImageField(upload_to=upload_image_path, null=True, blank=True, verbose_name='تصویر پرسشنامه') objects = AssessmentsManager() class Meta: verbose_name = 'ایجاد پرسشنامه' verbose_name_plural = 'ایجاد پرسشنامه ها' … -
Django ckeditor codesnippet plugin shows codes without color
I am using ckeditor in my django project, everything is working fine, but when add code snippet there is only simple text code without colors but in my admin panel it is normal. -
How do you change the title of a pdf using django?
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason urls.py urlpatterns = [ path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ), ] views.py def show_file(response,file_id): doc = Document.objects.get(id=file_id) pdf = open(f"media/{doc.file}", 'rb') return FileResponse(pdf, content_type='application/pdf') -
Django Rest Framework 'can't set attribute' in APIView
I have an endpoint, CompanyDefaultView class that inherits APIView and AURPostCompIdMixin classes. using this endpoint i get AttributeError: can't set attribute error. this is all code in one file import logging from abc import ABC from rest_framework import status, serializers from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView logger = logging.getLogger(__name__) HEADER_USER_STATUS = 'User-Status' USER_STATUS_NOT_EXIST = 'not-exist' USER_STATUS_EXIST = 'exist' USER_STATUS_EXIST_NOT_ACTIVE = 'not-active' USER_STATUS_EXIST_ACTIVE = 'active' class RspPropsMixin: _response = None @property def response(self): return self._response _stat_code = None _rsp_headers = {} @property def stat_code(self): return self._stat_code @property def rsp_headers(self): return self._rsp_headers def _set_rsp_props(self, response, header_key, header, stat_code): self._response = response if header is not None: self._rsp_headers[header_key] = header self._stat_code = stat_code def set_rsp(self, response=None, header_key=HEADER_USER_STATUS, header=None, stat_code=status.HTTP_200_OK): self._set_rsp_props(response, header_key, header, stat_code) def set_rsp_msg(self, msg, desc=None, header_key=HEADER_USER_STATUS, header=None, stat_code=status.HTTP_200_OK): response = {'msg': msg} if desc is not None: response['desc'] = desc self._set_rsp_props(response, header_key, header, stat_code) def add_header(self, header_key=HEADER_USER_STATUS, *, header): self._rsp_headers[header_key] = header class AURMixin(RspPropsMixin): """ AuthenticatedUserRequestMixin class """ permission_classes = (IsAuthenticated,) _comp_id = None _ruser = None @property def comp_id(self): return self._comp_id @property def ruser(self): return self._ruser def handle_valid_request(self, request, http_method_data, *args, **kwargs): raise NotImplementedError("You must implement handle_valid_request method!") def handle_request(self, request, http_method_data, *args, **kwargs): … -
How to execute a method within a class without calling it, with self parameter
I am trying to make a randomized urls and save them in a database but this code keep return this error TypeError: randomizer() missing 1 required positional argument: 'self' I Tried to call The randomizer as randomizer() instead of randomizer but this does not work because it will generate random characters for once. It is the same when with qr_generator function it requires the self argument. class Table(models.Model): def randomizer(self): qr = str(self.restaurant.id).join((random.choice(string.ascii_letters) for x in range(5))) return qr def qr_generator(self): url = DOMAIN +"/table/" + self.qr qr_img = qrcode.make(url) qr_img.save(f"qrs/{self.restaurant.id}/{self.qr}.png") return f"qrs/{self.restaurant.id}/{self.qr}" number = models.IntegerField() restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) qr = models.CharField(max_length=50, default=randomizer, unique=True) qr_img = models.CharField(default=qr_generator, max_length=100) -
How to fetch specific location inside map part?
Example maps image Suppose, I've draw-line for store delivery area. Now, any user to inside draw-line delivery area then got store instance else not found object. So, How can I set django filter query for fetching the store base on user current location? from django.contrib.gis.db import models class Store(models.Model): store_name = models.CharField(default="", max_length=255, null=True, blank=True) delivery_area = models.MultiPointField(srid=4326, null=True, blank=True) Base on Above, model to I've set delivery area for store. Now, user side getting current location like, PointField(28.632194789684196, 77.2200644600461) and this location getting from user mobile. According to this location coordinate how can fetch the store.? Store.objects.filter(delivery_area=PointField(28.632194789684196, 77.2200644600461)) Like, fetch the store on above queryset. -
Reverse Relationship Django Rest Framework
i have this serializer of a Photo, that translates uploaded photos to URL class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_img') def get_img(self, entity_photo): if not entity_photo.image: raise NotFound request = self.context.get('request') return request.build_absolute_uri(entity_photo.image.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) And this serializer is based on a model that's connected to Entity Model reverse relationship. class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False, related_name='entity_photo') image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) The class Entity class Entity(models.Model): Has no fields connecting to EntityPhotos, but i'd like to add the photos to Entity Serializer class EntityCreateSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = '__all__' And i would like to show the EntityPhotos that have Entity_id=pk from url. So that whenever i make a get request to entity/1 i want to see also the photos that have entity_id == 1. Do you have any idea how to do that? -
Error in Pipenv when trying to install django
OK I was learning Django and they told me to use VS CODE so I installed it and when I opened the terminal and did some beginner stuff and then the teacher told me to use pipenv to install Django he used "pipenv install Django" but when I did I received this error Here is link to image please tell me what to do. -
How to use basic deleteview
I start use DeleteView of django.views.generic. However I am still confused about DeleteView Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView So,,,,is this correct?? It doesn't delete the item. in urls.py path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(), name="pre-action-delete"), in views.py class PreActionDeleteView(LoginRequiredMixin, DeleteView): model = PreAction success_url = reverse_lazy("pre-action-list") def delete(self, request, *args, **kwargs): success_url = self.get_success_url() messages_text = "deleted" messages.success(self.request, messages_text) return HttpResponseRedirect(success_url) -
What does a function in a django model do?
i wrote this function in django model that would help send and get messages but tbh i do not understand what the code exactly does because the tutorial teacher didn't explain anything about the code and for days now i have been trying to figure out what the code does with no solutions yet. I do not just want to copy and paste code from a tutorial, i want to also understand what each code does so that's why i would appreciate anyhelp. The code def get_messages(user): messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') users = [] for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count() }) return users complete models.py class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') body = models.TextField(max_length=1000, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def send_message(from_user, to_user, body): sender_message = Message( user=from_user, sender=from_user, recipient=to_user, body=body, is_read=True) sender_message.save() recipient_message = Message( user=to_user, sender=from_user, body=body, recipient=from_user,) recipient_message.save() return sender_message def get_messages(user): messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') users = [] for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count() }) return users views.py if needed def Inbox(request): messages = Message.get_messages(user=request.user) active_direct = None directs = None … -
service postgres not running in docker
I want to change my project Django with postgres to docker and then I make Dockerfile and docker-compose.yml my Dockerfile FROM python:3.10.0-slim-buster ENV APP_HOME=/app RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles ENV PYTHONBUFFERED=1 RUN apt-get update \ && apt-get install -y build-essential \ && apt-get install -y libpq-dev \ && apt-get install -y gettext \ && apt-get -y install netcat gcc postgresql \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* WORKDIR $APP_HOME RUN pip install --upgrade pip COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY ./docker/local/django/entrypoint /entrypoint RUN sed -i 's/\r$//g' /entrypoint RUN chmod +x /entrypoint ENTRYPOINT [ "/entrypoint"] my docker-compoae.yml version: "3" services: api: container_name: estate-api-container build: context: . dockerfile: ./docker/local/django/Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/app - static_volume:/app/staticfiles - media_volume:/app/mediafiles ports: - "8000:8000" env_file: - .env depends_on: - db db: container_name: estate-db-postgres12 image: postgres:12.0-alpine ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} volumes: static_volume: media_volume: postgres_data: entrypoint #!/bin/sh if [ "$DATABASE" = "estate1" ] then echo "Waiting for postgres..." while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "PostgreSQL started" fi exec "$@" when I run the command docker-compose build successfully build, my problem … -
what should we do to change page through link in django in urls, views?
Geography from this button i need to go on gallery.html. urlpatterns = [ path('',include('my_app.urls')), path('gallery',include('my_app.urls')), path('admin/', admin.site.urls), ] def gallery(request): return render(request, 'gallery.html') -
How to install uwsgi on windows?
I'm trying to install uwsgi for a django project inside a virtual environment; I'm using windows 10. I did pip install uwsgi & I gotCommand "python setup.py egg_info". So to resolve the error I followed this SO answer As per the answer I installed cygwin and gcc compiler for windows following this. Also changed the os.uname() to platform.uname() And now when I run `python setup.py install``. I get this error C:\Users\Suhail\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\_distutils\dist.py:275: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running install C:\Users\Suhail\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( using profile: buildconf/default.ini detected include path: ['/usr/include', '/usr/local/include'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 4 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_IPCSEM_ATEXIT -DUWSGI_EVENT_TIMER_USE_NONE -DUWSGI_EVENT_FILEMONITOR_USE_NONE -DUWSGI_VERSION="\"2.0.19.1\"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="19" -DUWSGI_VERSION_REVISION="1" -DUWSGI_VERSION_CUSTOM="\"\"" -DUWSGI_YAML -DUWSGI_PLUGIN_DIR="\".\"" -DUWSGI_DECLARE_EMBEDDED_PLUGINS="UDEP(python);UDEP(gevent);UDEP(ping);UDEP(cache);UDEP(nagios);UDEP(rrdtool);UDEP(carbon);UDEP(rpc);UDEP(corerouter);UDEP(fastrouter);UDEP(http);UDEP(signal);UDEP(syslog);UDEP(rsyslog);UDEP(logsocket);UDEP(router_uwsgi);UDEP(router_redirect);UDEP(router_basicauth);UDEP(zergpool);UDEP(redislog);UDEP(mongodblog);UDEP(router_rewrite);UDEP(router_http);UDEP(logfile);UDEP(router_cache);UDEP(rawrouter);UDEP(router_static);UDEP(sslrouter);UDEP(spooler);UDEP(cheaper_busyness);UDEP(symcall);UDEP(transformation_tofile);UDEP(transformation_gzip);UDEP(transformation_chunked);UDEP(transformation_offload);UDEP(router_memcached);UDEP(router_redis);UDEP(router_hash);UDEP(router_expires);UDEP(router_metrics);UDEP(transformation_template);UDEP(stats_pusher_socket);" -DUWSGI_LOAD_EMBEDDED_PLUGINS="ULEP(python);ULEP(gevent);ULEP(ping);ULEP(cache);ULEP(nagios);ULEP(rrdtool);ULEP(carbon);ULEP(rpc);ULEP(corerouter);ULEP(fastrouter);ULEP(http);ULEP(signal);ULEP(syslog);ULEP(rsyslog);ULEP(logsocket);ULEP(router_uwsgi);ULEP(router_redirect);ULEP(router_basicauth);ULEP(zergpool);ULEP(redislog);ULEP(mongodblog);ULEP(router_rewrite);ULEP(router_http);ULEP(logfile);ULEP(router_cache);ULEP(rawrouter);ULEP(router_static);ULEP(sslrouter);ULEP(spooler);ULEP(cheaper_busyness);ULEP(symcall);ULEP(transformation_tofile);ULEP(transformation_gzip);ULEP(transformation_chunked);ULEP(transformation_offload);ULEP(router_memcached);ULEP(router_redis);ULEP(router_hash);ULEP(router_expires);ULEP(router_metrics);ULEP(transformation_template);ULEP(stats_pusher_socket);" *** uWSGI compiling server core *** [thread 1][gcc] core/utils.o [thread 2][gcc] core/protocol.o [thread 3][gcc] core/socket.o [thread 0][gcc] core/logging.o In file included from In file included from core/logging.c:2core/socket.c:1 : : ./uwsgi.h:172:10:: fatal error: sys/socket.h: No such file or directory #include sys/socket.h: No such file or directory #include <sys/socket.h>sys/socket.h: No such file or directory #include ^~~~~~~~~~~~~~^~~~~~~~~~~~~~ cc^~~~~~~~~~~~~~o mm ppiillaattiioonn cttoeemrrpmmiiilnnaaatttieeoddn.. In file included from t rcore/utils.c:1mi: n … -
Data from back end not showing in front end using django
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code... I don't have any errors showing in my terminal or web browser. my views.py from django.shortcuts import render, get_list_or_404 from adopt.models import Adopt Create your views here. def adopt(request): return render(request, 'adopts/adopt.html') def adopt_detail(request, id): single_pet = get_list_or_404(Adopt, pk=id) data = { 'single_pet': single_pet, } return render(request, 'adopts/adopt_detail.html', data) def search(request): adopt = Adopt.objects.order_by('-created_date') if 'keyword' in request.GET: keyword = request.GET['keyword'] if keyword: adopt = adopt.filter(description__icontains=keyword) data = { 'adopt': adopt, } return render(request, 'adopts/search.html', data) my models.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField Create your models here. class Adopt(models.Model): pet_gender = ( ('F','Female'), ('M', 'Male'), ) state_choice = ( ('AL', 'Alabama'), ('AK', 'Alaska'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District Of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', … -
Generating new unique uuid4 in Django for each object of Factory class
I have a Model Sector which has a id field (pk) which is UUID4 type. I am trying to populate that table(Sector Model) using faker and factory_boy. But, DETAIL: Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists. This is the error I am getting. Is it possible that the error is due to the fact that everytime I am creating SectorFactory objects (which is in a different django app) and the seed gets reset to some previous number causing the uuid to repeat? Please suggest some ways as to how I shall get unique uuid for each Factory object? SectorFactory class import uuid from factory.django import DjangoModelFactory from factory.faker import Faker from factory import Sequence class SectorFactory(DjangoModelFactory): id = uuid.uuid4() name = Sequence(lambda n: f'Sector-{n}') class Meta: model = 'user.Sector' django_get_or_create = ['name'] Class Sector class Sector(models.Model): id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Meta: db_table = 'sector' constraints = [ models.UniqueConstraint('name', name = 'unique_sector_name') ] The script which creates the custom command to create SectorFactory objects. from types import NoneType from django.core.management.base import BaseCommand from user.factories import SectorFactory class Command(BaseCommand): help = 'Generate fake data and seed the models with them.' def add_arguments(self, parser) -> None: parser.add_argument( '--amount', type=int, … -
How to solve local variable error with forloop in django?
Info: I want to get data from context. The context data is coming from for loop function. Problem: I am getting this local variable 'context' referenced before assignment def CurrentMatch(request, match_id): match = Match.objects.get(id=match_id) match_additional = MatchAdditional.objects.get(match=match) innings = match_additional.current_innings recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1] for score in recent: context = { "ball_number": score.ball_number, "over_number": score.over_number, } return HttpResponse(json.dumps(context)) -
Can't run python manage.py runserver
Hello~ I have installed django-bootstrap-ui-2.0.0 and django-admin startproject, and tried both python and python3 manage.py runserver. However, it says that no such file or directory. Am I missing some functions that have to pip install? Much thanks! C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\ Users\user\PycharmProjects\Pyshop\manage.py': [Errno 2] No such file or directory PS C:\Users\user\PycharmProjects\Pyshop> -
Change django modal field passing in a attribute
The modal is "account" and I wanna change its integer field "balance" The below code is working: account.balance += amount But the following code is not working: balance = account.balance balance += amount I don't know why it is not working just by holding it in a variable. -
Unable to Pass UUID string to API endpoint using POSTMAN Correctly
The API endpoint is something like that, at django backend /accounts/id/uuid:pk/some_action/ in the models it is defined as id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) The apiview accepts requests and pk which is uuid as pk. @api_view(['PUT']) def some_action(request, pk): when i'm making a request with uuid it is giving me following error Not Found: /accounts/user/{id}/some-action/ [12/Feb/2022 18:41:28] "PUT /accounts/id/%7Bid%7D/some-action/ HTTP/1.1" 404 4930 in Postman i configure the url like this /accounts/id/{id}/some-action/ So what might be the problem in passing the uuid ? -
Reverse relations Image Serialization DRF
I have a Photo serializer that shows me an URL of the photo, and i want to include this reverse relationship in EntityAPIView, so that i can see on a particular Entity the images related to the entity. If i do it like so (just put the related name='entityphotos' into fields, it works, but shows me the IDs of the EntityPhotos instead of URLS.) Do you have any idea how to show the urls? class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = ('id', 'entity_name', 'slug', 'created_at', 'updated_at', \ 'entity_category', 'entity_service', 'entity_animal', \ 'entity_member', 'entity_email', 'entity_address', 'entity_city', \ 'entity_zip_code', 'entity_description', 'entity_phone', \ 'entity_nip', 'gallery', 'points_from_reviews', 'reviews_quantity', \ 'logo', 'payment_method_cards', 'payment_method_cash', \ 'payment_method_blik', 'payment_method_wire', 'payment_method_installments', \ 'creator', 'lat', 'lng', 'img_map', 'entityphoto', ) class SpecialistDetailAPIView(generics.RetrieveAPIView): queryset = Entity.objects.all() serializer_class = SpecialistSerializer lookup_field = 'pk' class Entity(models.Model): ...... class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False, related_name='entityphoto') image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_image') def get_image(self, entity): if not entity.image: return request = self.context.get('request') return request.build_absolute_uri(entity.entity.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) -
How do I add buttons using javascript in a bunch of divs generated by Django through loop?
I am working on a Django project, where I have made a bunch of HTML divs. I want to add a single button on each div. In the image above, I have created a div of class card-footer with Django for loop. I want to add a blue coloured like button on each of the divs using javascript but you can see in the image that it is being added into only one div. Here I am sharing my HTML template. <div id="posts" class="card"> <ul class="card-body"> {% for posts in page_view %} <li class="card"> <div class="card-header bg-success"> <h5 class="card-title"><a class="text-light" style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5> <h6 class="card-subtitle text-light">{{ posts.timestamp }}</h6> </div> <div class="card-body"> <h3 class="card-text">{{ posts.post }}</h3> </div> {% include 'network/like.html' %} </li> {% empty %} <h6>No post availabel 😔</h6> {% endfor %} </ul> </div> Here is my network/like.html: <div class="card-footer"> <form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;"> {% csrf_token %} <button id = "like" class="btn btn-link" type="submit">Like</button> </form> <small id="num_of_likes">{{ posts.likepost.all.count }}</small> {% block script %} <!-- <script> let posts_id = "{{ posts.id }}"; </script> --> <script src="{% static 'network/controller.js' %}"></script> {% endblock %} <button class="btn btn-link" style="text-decoration: none;">Comment</button> <a href="{% url … -
django-simple-history, TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html
I am using django-history-admin I have model class class MannedSetting(BaseModel): history = HistoricalRecords() class Meta: db_table = 't_manned_setting' confirm_msg = m.CharField(max_length=400) then in admin.py from simple_history.admin import SimpleHistoryAdmin class MannedSettingAdmin(SimpleHistoryAdmin): list_display = ["id","confirm_msg"] admin.site.register(MannedSetting,MannedSettingAdmin) There appears the history button in the edit page of MannedSetting instance However when clicking the button, this error comes. TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html Request Method: GET Request URL: http://localhost:8010/admin/shared_models/mannedsetting/1/history/ Django Version: 3.2.7 Exception Type: TemplateDoesNotExist Exception Value: simple_history/object_history.html Exception Location: /Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/lib/python3.9/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/bin/python Python Version: 3.9.10 Python Path: ['/Users/whitebear/MyCode/httproot/s_cdk/myadmin', '/Users/whitebear/MyCode/httproot/s_cdk/myadmin/my-shared-models', '/Users/whitebear/MyCode/httproot/s_cdk/myadmin/$PYTHONPATH', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/lib/python3.9/site-packages'] Server time: Sat, 12 Feb 2022 22:24:06 +0900 -
DRF is not updating the database
Here's the model: from django.db import models from datetime import datetime, timedelta # Create your models here. def set_expiration(): return datetime.today().date() + timedelta(days=30) class Customer(models.Model): email = models.EmailField(max_length=254, unique=True) created_on = models.DateField(auto_now_add=True) expires_on = models.DateField(editable=False, default=set_expiration()) def __str__(self): return self.email And this is the view: @api_view(['POST']) def update_customer(request): try: customer = Customer.objects.get(email=request.data['email']) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CustomerSerializer(instance=customer, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) And the serilizer: from rest_framework import serializers from .models import Customer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' At this moment I have a record in database with expires_on set to 2022-03-14 and I want to update that to 2024-12-12 so I call the endpoint with the following data: { "email": "myemail@mydomain.com", "expires_on": "2024-12-12" } The view returns this: { "id": 1, "email": "myemail@mydomain.com", "created_on": "2022-02-12", "expires_on": "2022-03-14" } This is the existing data. expires_on is not updated with the new value. I get no error and no exception. It just doesn't work. -
Unabled to deploy django + apache on aws Ubuntu server
I am trying to deploy a Django Application using Apache on an Ubuntu Server, I am having a weird error (500 internal error server error) when using port :80. I made some test using port :8000 running the command: python3 manage.py runserver 0.0.0.0:8000 And the application is working without any problem there, but when I try to access the application using port 80 it does work. My apache config file looks like this: <VirtualHost *:80> Alias /static /home/ubuntu/gh_system/static <Directory /home/ubuntu/gh_system/static> Require all granted </Directory> <Directory /home/ubuntu/gh_system/HRSYSTEM> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess HRSYSTEM python-home=/home/ubuntu/gh_system/env python-path=/home/ubuntu/gh_system> WSGIProcessGroup HRSYSTEM WSGIScriptAlias / /home/ubuntu/gh_system/HRSYSTEM/wsgi.py -
How to create timer in django
I want ,when user click a button a timer start and show it top menu. if user close website or navigate other page it's work. show hh:mm:ss or only minute ,start from user clicked on button.