Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use wkHTMLtoPDF running in docker-compose in Django application
I have a problem with undestanding on how to use wkHTMltoPDF, that I run in docker-compose and Django. Also I can't understand how to setup it in Django and use it in the right way. I will be very glad for any help. My docker-compose.yml: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 wkhtmltopdf: image: openlabs/docker-wkhtmltopdf-aas:latest volumes: - .:/data So, I can't even imagine where I should do it in Django. The example of usage that I need: on main page I fill some forms and then click button "Generate". It should send async requests on generating pdf file of this page with filled forms. Can anybody help me to realise it? -
Django Latest Timestamped Items from Many
I have a Model where there can be multiple instances of the same entry. They have their respective timestamps as I scrape the same data sources daily. I want to only receive the latest entries for each item. I wanted to approach this as grouping by the identifier of the items, which will result in groups of the same items but different timestamps, then get the latest from each group and combine this. My question is, how can this be done in Django? From what I have read I can use the "annotate()" function to GroupBy and then use "latest()" on each group. Is there any better way of accomplishing the same result or is this a proper approach? Thank you! -
Django uploaded file doesn't process
I'm building a Django web-app where the user needs to upload a file. This file should go through a machine-learning alogritme after that the results will be presented on a different page. right now it works if I have text fields present for every feature but when I want to upload a csv file(the csv file is called test.csv) put it in a pandas dataframe the resultpage doesn't show and it looks like the csv file isn't processed. what it should do is if file is uploaded keep the uploaded file in memory process it and return the output on the results page. HTML {% extends "base.html" %} {% block content %} <div class="content"> <div class="row"> <div class="col-lg-4"> <div class="card card-tasks"> <h1> </h1> <form action="{% url 'result' %}"> {% csrf_token %} <p>temp_normal:</p> <input class="form-control" type="text" name="temp_normal"> <br> <p>hour:</p> <input class="form-control" type="text" name="hour"> <br> <p>hour_x:</p> <input class="form-control" type="text" name="hour_x"> <br> <p>hour_y:</p> <input class="form-control" type="text" name="hour_y"> <br> <input class="form-control" type="submit" value='Submit'> </form> </div> </div> <div class="col-lg-4"> <div class="card card-tasks"> <form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div … -
When I clicked on 'viewall' submit button on html it goes to 'RestInfo url' and show NoReverseMatch at error Django
Template Code <a href="{% url 'ViewAll' cust.custId %}" <button class="btn cart viewall">View All</button></a> <a href="{% url 'RestInfo' rest.restId cust.custId %}" style="color: #000000;">RestInfo</button></a> url.py path('ViewAll/<str:mycid>',views.ViewAll,name='ViewAll') path('myRest/<int:myid>/<str:cid>',views.RestInfo,name='RestInfo'), views.py def ViewAll(request,mycid): print("Welcome",mycid) rests= Restaurant.objects.all() return render(request,'viewall.html',{'rests':rests}) def RestInfo(request,myid=None,cid=None): rests= Restaurant.objects.filter(restId=myid) return render(request,"restInfo.html",{'rest':rests[0]}) When I Clicked on button in which viewll url is given then it goes to restinfo and shows me noreversematch error -
Permissions Issues Linux
I'm trying to follow the Django official tutorial. When I'm trying to create a new project: django-admin startproject mysite I have this error : CommandError: [Errno 13] Permission denied: '/home/olivier/Documents/python/Django/official_tutorial/mysite' I thought that I didn't have the rights in this folder. Which is weird cause it's my personal folder. So I checked with ls -l /home : total 4 drwxrwxr-x 27 olivier olivier 4096 oct. 22 15:16 olivier Apparently I do have the rights. Side note I cannot create a venv in it with virtualenv venv virtualenv: error: argument dest: the destination . is not write-able at /home/olivier/Documents/python/Django/official_tutorial SystemExit: 2 What seems to be the problem here ? I'm running Pop!_OS 20.04 LTS -
Filtering Objects Using Other Objects - Queryset, Django
In my Django application, the user provides a unique product name which matches field of another object and then displays second object on the list (that the user sees). So the object's display condition looks something like this obj1.name == obj2.name It is extremely simple for one object but how to use it for get queryset (where the field of objects 1 is equal to the field of object 2)? An example of the effect I want to get: Obj1.objects.all() = ('AS2', 'AS9', 'AD5', 'AG1') Obj2.objects.all() = ('DD1', 'AS2', 'AS9', 'AP33', 'AD5', 'AG1', 'KQ1', 'LG4') query1 = Obj1.objects.all() query2 = obj2.objects.filter(name=???) #and query2 return all objects product which name=name well ('AS2', 'AS9', 'AD5', 'AG1') but from Obj2 -
django isn't sending data to html?
I am a newbie so please ignore the question quality :). my django views.py -- def search(request): if request.method == 'POST': try: query = request.POST["query"] try: query2 = User.objects.get(username=query) except: query2 = None if query2 == None: results = info.objects.filter(name=query) else: results = info.objects.filter(user=query2, name=query) if results == "": results=None return render(request, "search.html", {"results": results}) # https://docs.djangoproject.com/en/dev/topics/db/queries/# #spanning-multi-valued-relationships except: messages.info(request, "User not found") return redirect(home) else: pass my html page -- <div class="container"> {% for result in results %} <a href="profile_seen?profile_seen={{result.user}}-1"> <div style="border: 0.7px solid gray;" class="row card"> <div style="display: flex;align-items: center; justify-content: center;"> <img style="width: 107px; margin: 10px 2%;" class="img-fluid" src="https://facyfun-bucket.s3.ap-south-1.amazonaws.com/{{result.profile_pic}}" alt="error"> <ul style="padding: 11px 12%;" class="list-group list-group-flush"> <li style="font-size: 32px;" class="list-group-item p-0">{{result.user}}</li> <li style="font-size: 19px;" class="list-group-item p-0">{{result.name}}</li> <li style="font-size: 17px;" class="list-group-item p-0">age {{result.age}}y</li> </ul> </div> </div> </a> {% endfor %} Error -- I am sending data(results) but it still shows nothing(not even null value). -
Django save nested data to Elasticsearch
I want to save nested data to elastic, I created model, document and serialize. Incoming Data(from twitter and parsed): {'created_at': '2020-10-26 20:00:14', 'tweetID': xxx, 'userID': xxx, 'userName': 'xxx', 'userScreenName': 'xxx', 'full_text': 'xxx', 'hashtag': ['xxx'], 'urls': ['xxx'], 'ioc': [ {'type': 'xxx', 'value': 'yyy', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}, {'type': 'kkk', 'value': 'mmm', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}]} My Model class: from django.db import models from django.utils.translation import ugettext_lazy as _ class TwitterPost(models.Model): created_at = models.DateTimeField( _('created_at'), blank=True, null=True, ) tweetID = models.CharField( _('tweetID'), blank=True, null=True, default=None, max_length=100, ) userID = models.CharField( _('userID'), null=True, blank=True, default=None, max_length=100, ) userName = models.CharField( _('userName'), null=True, blank=True, default=None, max_length=200, ) userScreenName = models.CharField( _('userScreenName'), null=True, blank=True, default=None, max_length=200, ) full_text=models.CharField( _('full_text'), null=True, blank=True, default=None, max_length=500, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) def __str__(self): return self.tweetID class TwitterPostIOCs(models.Model): ioc = models.ForeignKey(TwitterPost, related_name='tweetIOC', on_delete=models.CASCADE) type = models.CharField( _('type'), null=True, blank=True, default=None, max_length=100, ) value = models.CharField( _('value'), null=True, blank=True, default=None, max_length=100, ) first_discovery = models.DateTimeField( _('first_discovery'), blank=True, null=True, ) last_observed = models.DateTimeField( _('last_observed'), blank=True, … -
Django: More pythonic way of saving form data to existing model
I'm currently saving my new ModelForm values by iteration of each form's cleaned values after validation. Is there a better way of doing this? Note: 'Activity' model already contains data for given example record_form = AddRecordTimeFrame(request.POST) activity_form = EditRecordGeneral(request.POST) activity_form_2 = EditRecordChassisDynoTest2(request.POST) if all([activity_form.is_valid(), activity_form_2.is_valid(), record_form.is_valid()]): test_record = RecordModel.objects.get(id=1) activity_record = test_record.activity for field, value in record_form.cleaned_data.items(): setattr(test_record, field, value) for field, value in activity_form_2.cleaned_data.items(): setattr(activity_record, field, value) for field, value in activity_form.cleaned_data.items(): setattr(activity_record, field, value) I'd like to make use of the form's .save() but only change values of the model that are in the fields of the modelform. -
I got an Operational error after trying to register on a web i developed using django python
https://dpaste.com/BZ8VWDUTG OperationalError at /reg_form/ no such table: selection_user Request Method: POST Request URL: http://127.0.0.1:8000/reg_form/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such table: selection_user Exception Location: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\HP\Downloads\django implementation\Hostel-Management-System\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\hhms', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python37', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv', 'C:\Users\HP\Downloads\django ' 'implementation\Hostel-Management-System\venv\lib\site-packages'] -
how to disappear html tags in django (safe tag not working properly)
I am making a blogging website like this I want to remove these tags (<p> <em>) which are being displayed in these cards page-html (before adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> page-html (after adding safe tag): <div class="container"> <div class="card-deck"> {% for post in top_posts %} <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title|truncatechars:14|safe}}</h5> <p class="card-text text-justify">{{post.content|truncatechars:190|safe}}</p> <br> <p class="card-text"><small class="text-muted">{{post.timeStamp|timesince}}</small></p> <div> <a href="/blog/{{post.slug}}" class="btn btn-primary">ReadMore</a> </div> </div> </div> {% endfor %} </div> </div> how page looks: help me to remove these italics and display the text in original cards style. -
Django's m2m_changed signal on User's groups is not triggered
I created an m2m_changed signal to automatically set is_staff attribute of users when they join/leave a specific group, but the signal is never fired. Here is the signal's definition : @receiver(m2m_changed, sender=User.groups.through) def moderator_group_is_staff(sender: Type[User], instance: Union[User, Group], action: str, reverse: bool, model: Union[Type[User], Type[Group]], pk_set: Set[int]): """Set `is_staff` attribute of users to `True` or `False` when they respectively join or leave the moderator's group.""" moderator_pk = Group.objects.get(name=settings.GROUPNAME_MODERATOR).pk # instance is User, pk_set is Groups' pk if not reverse and moderator_pk in pk_set: if action == "post_add": instance.is_staff = True if action == "post_remove" or action == "post_clear": instance.is_staff = False # instance is Group, pk_set is Users' pk elif reverse and instance.pk == moderator_pk: if action == "post_add": instance.user_set.update(is_staff=True) if action == "post_remove": User.objects.filter(id__in=pk_set).update(is_staff=False) if action == "pre_clear": instance.user_set.update(is_staff=False) I tried from django's admin interface and the manage.py shell, but the function was never called. Any idea ? -
Django all-auth allow users to login only if the user email address is verified
How do i override AllAuth default LoginView to allow users to login only if their email address is verified? -
I want to show JSON data in my Django template when Django's URL is roaded
I want to show JSON data in my Django template when Django's URL is roaded. My Django server structure is like polls(Django's parent app) has urls.py &views.py and templates has app has top.html. polls has app(Django's children app) has urls.py &views.py. I wrote urls.py of app from django.urls import path, include from . import views app_name = 'app' urlpatterns = [ path('index/', views.Top.as_view(), name='index'), ] views.py of app class Top(LoginRequiredMixin, TemplateView): template_name = 'app/top.html' login_url = '/login/' @csrf_exempt def index(request): if request.is_ajax: if request.method == 'POST': json_data = json.loads(request.body.decode("utf-8") dict['A'] = json_data[1]['A'] dict['B'] = json_data[1]['B'] else: dict = [] return render(request, 'app/top.html', dict) I wrote urls.py of polls urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ] I made test folder has test.html&test.js. I wrote test.html like <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript" src="test.js"></script> </head> <body> <p>TEST</p> </body> </html> and test.js var info = [ { "A": "key", "B": "123, }, ]; const csrftoken = Cookies.get("csrftoken"); var xhr = new XMLHttpRequest(); var json = JSON.stringify(info); xhr.open("POST", "http://127.0.0.1:8000/app/index/"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(json); I run Django server & opened test.html in Google browser.However Console of Google browser said POST http://127.0.0.1:8000/app/index/ 403 … -
Set up db_password for django and postgres in docker
I've a docker image with django 3.1 and postgresql. In the docker-compose.yml I wrote: version: '3' services: app: build: context: . ports: - "8001:8001" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8001" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=password depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password In the Django app's settings.py I read the database password from the .txt file excluded from the .git ... DB_PASSWORD = '' with open('database_password.txt') as f: DB_PASSWORD = f.read().strip() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': DB_PASSWORD, } } ... What is the best practice to make Django and Docker securely read the same password from the same place? The most suitable information about this I found here: https://medium.com/swlh/setting-up-a-secure-django-project-repository-with-docker-and-django-environ-4af72ce037f0 The author offers to use the django-environ package for django. The docker part in this article descibed like this: If you specifed a different user and password in the DATABASE_URL variable in the .env file above, you should include them here (although this will compromise the security of the database, as the docker-compose.yml file will be committed to the repository). When it comes time to deploy the … -
How to create an image sitemap in Django
My model is the Station and the field holding the image url is the image I find difficulty on how to build my sitemaps.py file in order to be able to present also in sitemap.xml file the <image:loc> tag based on the image url. The source here : image sitemap just presents the xml format. I want to build a xml file like this based on the code written in sitemaps.py file. urls.py from .sitemaps import StationSitemap sitemaps = { 'station' : StationSitemap, } urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), ] sitemaps.py from django.contrib.sitemaps import Sitemap from stations.models import Station class StationSitemap(Sitemap): def items(self): return Station.objects.all() def location(self,item): return item -
I got an error name 'LOGIN_REDIRECT_URL' is not defined
I use django and when I put LOGIN_REDIRECT_URL in settings.py on the bottom, I got an error like this name 'LOGIN_REDIRECT_URL' is not defined What problems in my code? https://www.youtube.com/watch?v=3aVqWaLjqS4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=7 I refer to this and I completely write same code. Please tell meeeeeeee! -
Django template loop many-to-many iteration query efficiency
Models: class ItemManager(models.Manager): def get_queryset(self): return super(AssetsManager, self).get_queryset().prefetch_related( models.Prefetch("assignments", queryset=Assignments.objects.select_related("userid"))) class Item(models.Model): objects = ItemManager() id = UnsignedAutoField(db_column='Id', primary_key=True) user = models.ManyToManyField('Owner', through='Assignments', through_fields=('itemid', 'userid')) @property def owner(self): return self.assignments.select_related("userid").last().userid class User(models.Model): id = UnsignedAutoField(db_column='Id', primary_key=True) item = models.ManyToManyField('Item', through='Assignments', through_fields=('userid', 'itemid')) class Assignments(models.Model): id = UnsignedAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') userid = models.ForeignKey('User', default=None, blank=True, null=True, on_delete=models.SET_DEFAULT) itemid = models.ForeignKey('Item', on_delete=models.SET_DEFAULT, related_name='assignments') In my template I am trying to iterate over the Item queryset while also displaying the owner. The problem is that a new SQL query will be made for every step of the loop. Template loop: {% if item_list %} {% for item in item_list %} {{item}} - {{item.owner}} {% endfor %} {% endif %} The view is a ListView where the queryset is "Item.objects.filter(Q(id__gte=1) & Q(id__lte=5))". The context_object_name is item_list. Using Django Debug Toolbar I notice the following: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` IN (1, 3, 5, 2, 4) This query corresponds to {% if item_list %} Then a new query is made for every iteration: SELECT ••• FROM `Assignments` LEFT OUTER JOIN `User` ON (`Assignments`.`UserId` = `User`.`Id`) WHERE `Assignments`.`ItemId` = 1 ORDER BY `Assignments`.`id` DESC LIMIT 1 … -
Django REST endpoints for Watchlists feature
I wanted a system of multiple watchlists per user (upto 5) where users can add/remove products into individual watchlists. I have the following models is my models.py: class Product(models.Model): name = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100) sku = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100, verbose_name='Stock Keeping Unit') description = models.TextField(blank=True) price = models.FloatField(blank=True) class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) display_name = models.CharField(max_length=30) subscription = models.CharField(null=False, blank=False, choices=SubscriptionChoices.choices, default=SubscriptionChoices.SILVER, max_length=100) class Watchlist(models.Model): from .choices import WatchlistChoices profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ManyToManyField(Product) wl_num = models.CharField(null=False, blank=False, choices=WatchlistChoices.choices, default=WatchlistChoices.WL1, max_length=30) name = models.CharField(null=False, blank=False, max_length=20, default='NewWatchList') I have the following choices in a choices.py file: class WatchlistChoices(models.TextChoices): WL1 = 'WL1', _('Watchlist_1') WL2 = 'WL2', _('Watchlist_2') WL3 = 'WL3', _('Watchlist_3') WL4 = 'WL4', _('Watchlist_4') WL5 = 'WL5', _('Watchlist_5') I have put in the choices so that at any given time only the five predetermined watchlists can be used, hence limiting the number of watchlists per user to only 5. How can I build REST endpoints using DRF for the following tasks: Add/remove products into a specified watchlist Change the name of the watchlist Can this be done with class based views or does it need to be done with function based views? -
How to send request using a field in DjangoRestFramework UI
I am making a request from some external source, I am successfully able to make the request both manually and by passing the "ref_no" in my url, but I will like to have a way whereby I can put the "ref_no" in the DRF UI and make a post to the requested source and then get the data. I don't know if this is possible but I would be glad to get a way across this. views.py class Pay(APIView): def get(self, request, reference_id): url = f"https://api.paystack.co/transaction/verify/{reference_id}" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) urls.py from django.urls import path, include from .views import * urlpatterns = [ path('pay/<str:reference_id>', Pay.as_view(), name='pay'), ] -
I want to iterate a range of years using for loop in django
I want to display a set range of years using for loop with some start year to the current year and then after each passing years the current year will be that particular year. Example: start year is 2010 current year is 2020 It will display from year '2010' to '2020' So when 2021 comes the range will display from '2010' to '2021' my code is: import datetime def daterange(start, end, step=datetime.timedelta(1)): current_year = start while current_year < end: yield curr curr += step -
Not able to post the data in Django Restframework
I have added the experience details for the user using following models models.py class WorkExperienceData(BaseObjectModel): class Meta: db_table = 'workexperience' verbose_name = 'WorkExperience Data' user = models.ForeignKey(User, related_name="related_experience_detail", on_delete=models.PROTECT) company = models.CharField(max_length=500) designation = models.CharField(max_length=500) description = models.TextField(max_length=4000, default="") from_date = models.DateField(null=True) to_date = models.DateField(null=True, blank=True) reference_name_and_position = models.CharField(max_length=250) reference_mailid = models.EmailField(max_length=255, unique=True, db_index=True) My serializers are following Serializers.py class WorkExperienceSerialzer(BaseModelSerializer): hidden_fields_to_add = {"created_by": None, "user": None} def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(WorkExperienceSerialzer, self).__init__(many=many, *args, **kwargs) class Meta(BaseModelSerializer.Meta): model = WorkExperienceData fields = [ "company", "designation", "description", "from_date", "to_date", "reference_name", "reference_mailid", "user", "id", ] My views are following views.py class WorkExperienceListView(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): experience = WorkExperienceData.objects.all() serializer = WorkExperienceSerialzer(experience, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = WorkExperienceSerialzer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class WorkExperienceDetailsView(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return WorkExperienceData.objects.get(pk=pk) except WorkExperienceData.DoesNotExist: raise Http404 def get(self, request, pk, format=None): experience = self.get_object(pk) serializer = WorkExperienceSerialzer(experience, many=True) return Response(serializer.data) def put(self, request, pk, format=None): experience = self.get_object(pk) serializer = WorkExperienceSerialzer(experience, many=True, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def … -
How to get a better formatted JSON Response in DjangoRestFramework UI
I have an APIVIEW in DRF which I have written some views in it to get some Response, I would like to get a better formatted JSONResponse. Views.py class Pay(APIView): def get(self, request): url = "https://api.paystack.co/transaction/verify/262762380" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) This is a pictorial representation of the bad formatted JSONResponse I am getting which I would like to improve. Thanks -
How to import images from media_url to template.html in Django?
Well I am encountering a strange issue in my Django app. My app (in a loop) import an image into the media_url and then it goes to the next page and shows the image and goes back to first page. This was working very well yesterday. Today when I restart the server, the image goes to the media_url as before, but what I see in the next page is not what it is on the media_url and actually it is a picture that was imported before. here is the important part of the code: settings.py: MEDIA_ROOT = 'media//' # I test the MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media//' views.py: def scraping(request): .... template_name = "scraping.html" response2 = {'media_root': Config.MEDIA_ROOT, 'media_url': Config.MEDIA_URL} return render(request, template_name, response2) scraping.html <img src='{{media_url}}/pic.jpg//'> # I also tried {{media_url}}pic.jpg {{media_url}}/pic.jpg/ {{media_url}}//pic.jpg// ... It is surprisingly showing different images for each line Can you help me please? It seems that maybe! the media_url is not updating after each loop. I have no idea! -
how show favorite list in django
I have a list of favorites and I want to show them when I click on the interest button after I click on the list and my heart will be bold. The second part, ie filling the heart, is done correctly, but when I want to show the list, it does not show anything and gives the following error. Reverse for 'show_Book' not found. 'show_Book' is not a valid view function or pattern name. model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE) Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE) translator=models.ForeignKey('Translator',null='true',blank='true',on_delete=models.SET_NULL) favorit=models.ManyToManyField('orderapp.Customer',related_name='favorit', blank=True) view.py def show_Book(request,BookID): showBook=get_object_or_404(Book,BookID=BookID) is_favorite=False if showBook.favorit.filter(id=request.user.id).exists(): is_favorite=True return render (request , 'showBook.html', {'is_favorite':is_favorite,}) def favoritbook (request, BookID): showBook=get_object_or_404(Book,BookID=BookID) if showBook.favorit.filter(id=request.user.id).exists(): showBook.favorit.remove(request.user) else: showBook.favorit.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) def favoritlist(request): user=request.user favoritbooks=user.favorit.all() context={'favoritbooks':favoritbooks} return render (request,'favotritlist.html',context) url.py path('showbookstor/<int:id>', views.show_BookStor, name='show_BookStor'), path('books/favorit/<int:BookID>/', views.favoritbook, name='favoritbook'), path('books/favorit/', views.favoritlist, name='favoritlist'), showbook.html {% if is_favorite %} <li id="sell"><a href="{% url 'favoritbook' showBook.BookID %}">add to favorit <i class="fas fa-heart"></i></a> </li> {% else %} <li id="sell"><a href="{% url 'favoritbook' showBook.BookID %}"> delete favorit <i class="far fa-heart"></i></a> </li> {% endif %} favoritlist.html {% for Book in favoritbooks %} <section id="card" class="col-md-6 col-lg-3 col-sm-6 col-xs-12"> <a href="{% url 'show_Book' Book.BookID %}"><img src= {{Book.Image.url}}></a> <h1 id="bookname">{{Book.Titel}}</h1> <p>{{Book.Author}}</p> </section> {% endfor %}