Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pagination with no primary key
I have this function in views.py that will display all categories in a research management system following several tutorials: def CategoryView(request): cat_menu=Category.objects.all(); return render(request, 'Category.html',{'cat_menu':cat_menu}) When a user clicks on a category, they will get all the research papers that are under this category Views.py def ResearchCategoryView(request,cats): category_research=ResearchesList.objects.filter(research_category=cats.replace('_',' ')) return render(request,'Researches-Guest.html',{'cats':cats.title().replace('_',' '),'category_research':category_research,}) I would like to add a paginator to ResearchCategoryView, except I can't link to the same url as the category is not a primary key in the research table. Is there a way to do this without having to rewrite ResearchCategoryView? urls.py path('',views.GuestHome,name="GuestHome"), path('FeedBackForm',views.Form2,name="FeedBackForm"), path('FeedBackRecieved',views.ThankYou,name="ThankYou"), path('Category/',CategoryView,name='Categorys'), path('Category/<str:cats>',ResearchCategoryView,name='researchcategory'), path('Category/cats',ResearchCategoryView,name='researchcategory2'), path('Research/<int:pk>',AbstractView.as_view(),name='abstract'), path('search_research', views.search_research, name='search_research'), ** models.py inspected from mySQL** class ResearchesList(models.Model): research_id = models.AutoField(primary_key=True) title = models.TextField() auther = models.TextField() auther1 = models.TextField(blank=True, null=True) auther2 = models.TextField(blank=True, null=True) auther3 = models.TextField(blank=True, null=True) auther4 = models.TextField(blank=True, null=True) auther5 = models.TextField(blank=True, null=True) auther6 = models.TextField(blank=True, null=True) abstract = models.TextField() publish_date = models.DateField() start_date = models.DateField() finish_date = models.DateField() research_url = models.TextField() journal_name = models.CharField(max_length=100) research_category = models.CharField(max_length=70) data_type = models.CharField(max_length=45, blank=True, null=True) data_source = models.TextField(blank=True, null=True) geo_area = models.CharField(max_length=45, blank=True, null=True) is_collected_via_socialmedia = models.CharField(max_length=45, blank=True, null=True) collecation_start_date = models.DateField(blank=True, null=True) finishing_colleaction_date = models.DateField(blank=True, null=True) date_of_the_data = models.DateField(blank=True, null=True) sample_size = models.IntegerField(blank=True, null=True) … -
How to run a .py file when clicked the html button using django
i create a gui-app using python and the file named gui.py and also create a simple website using django. now in my website there is a button named 'open the gui-app'. now whenever someone click the button, the gui-app i mean the gui.py file will run. how to do this. here is the html code: <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Hello, world!</title> </head> <body><h1>Hello, world!</h1> <button type="button" class="btn btn-primary">Open the gui-app </button> //using bootstrap </body> </html>``` -
Can't connect to Websocket on Django with Heroku
I'm trying to deploy my Django app to Heroku. The thing is, when I try to test the Websocket I implemented, it doesn't connect. (Btw, I'm using the Postgres service that Heroku gives to storage my data). This is what I get when I try to test it: It's from a website called https://hoppscotch.io/realtime/ Here's the config of my Procfile: web: gunicorn kuropoly.wsgi. The routing.py part is configured like this: from django.conf.urls import url from apps.websocket.consumers import KuropolyConsumer websocket_urlpatterns = [ url(r'^wss/play/(?P<idRoom>\w+)/$', KuropolyConsumer.as_asgi()), ] And, as it says there on the code, I'm using ASGI, here's the config for that: asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import apps.websocket.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kuropoly.settings') # application = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( apps.websocket.routing.websocket_urlpatterns ) ), }) On my settings.py I have this: ASGI_APPLICATION = "kuropoly.asgi.application" CHANNEL_LAYERS = { 'default': { ## Via In-memory channel layer "BACKEND": "channels.layers.InMemoryChannelLayer" }, } # Activate Django-Heroku. import django_heroku django_heroku.settings(locals()) import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) I've tried changing my Procfile but that didn't work, I don't know if it's because of the fact that I'm using gunicorn (and I used that following the Heroku … -
how to have an integer along with ManytoMany field in django
So I am trying to finish up a recipe app, however storing my ingredients volume is a bit hard. eg: 3 - eggs, 1 butter, etc I did my models like this: class IngredientList(models.Model): name = models.CharField(max_length=100) recipes = models.ManyToManyField('RecipeList', through='ShoppingList') def __str__(self): return self.name class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField( 'IngredientList', through='ShoppingList') instructions = models.TextField(max_length=400) amount_made = models.IntegerField() def __str__(self): return self.name class ShoppingList(models.Model): ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE) amount_needed = models.IntegerField(default=1) if this is correct, how do I go forward with my views.py and outputing in my template? from django.shortcuts import render from .models import IngredientList, RecipeList, ShoppingList def index(request): recipe = RecipeList.objects.all() context = {'recipe': recipe} return render(request, 'recipe/home.html', context) and {% for i in recipe %} <div class="card col-sm-3 m-2 p-2"> <img class="card-img-top img-fluid" src="https://www.seriouseats.com/recipes/images/2014/09/20140919-easy-italian-american-red-sauce-vicky-wasik-19-1500x1125.jpg "> <div class="card-body"> <h4>{{ i.name}} <span class="badge badge-info">{{i.cuisine}}</span></h4> <p class="card-text">Ingredients: {% for k in i.ingredients.all %} {{k}}, {% endfor %}</p> <p class="card-text">Instructions: {{i.instructions}}</p> <p class="card-text">This makes {{ i.amount}} meals</p> </div> </div> {% endfor %} but this only outputs the name of the ingredient, but i want to add the amount when saving the ingredients needed for recipe -
how to annotate each object with random value
I want to have items with random annotations. I tried this: items = Item.objects.all()).annotate(random_value=Value(randint(1,6)),output_field=PositiveIntegerField())) And it is random, but THE SAME for EVERY Item in QuerySet. But I want to have DIFFERENT value for EACH Item... Any ideas? -
Matching query does not exist issue Django
I am trying to create a web app that has a Like button option for the Post. Everything works fine but when I click on the Like button it shows DoesNotExist error. This is the model part of the code: class Like(models.Model): user = models.ForeignKey(Yatru, on_delete=models.CASCADE) location = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.location}-{self.value}" This is the views: def like_unlike(request): user = request.user if request.method == 'POST': location_id = request.POST.get('location_id') location_obj = Post.objects.get(id=location_id) profile = Yatru.objects.get(user=user) if profile in location_obj.liked.all(): location_obj.liked.remove(profile) else: location_obj.liked.add(profile) like, created = Like.objects.get_or_create(user=profile, location_id=location_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' location_obj.save() like.save() return redirect('posts:post_views') When I try to load the page it shows this error: -
django.db.utils.OperationalError: fe_sendauth: no password supplied when migrating django app
I'm a beginner with Django working on an open source project, which has been very challenging since it only gives build instructions for Mac, and not Linux. So, on my Ubuntu server, I've managed to install all the packages and fix a few initial bugs, but now, when I do python manage.py migrate, I'm stuck with this error: django.db.utils.OperationalError: fe_sendauth: no password supplied I'm totally stuck here: I'm having a tough time understanding the error message, and other solutions aren't much help. Other solutions indicate that you have to change the DATABASES setting in the settings.py, but the setting has no PASSWORD attribute and it's only linked to sqlite: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'] = dj_database_url.config() The error doesn't trace back to any specific lines of code so I'm guessing its more related to psycopg2 or django than the code itself, but I'm not sure how to go about fixing it. I'm using Python 2.7.17 and Ubuntu 18.04.5. Here's the full error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line … -
Django: "extends" not working in template
I followed the latest Django documentation, using the {% extends %} keyword the same way they do in their example but I can't get it to work. What am I doing wrong? base.html: the content block defined in transaction_detail.html below works: <div class="row"> <div class="col-md-8"> {% if messages %} {% endif %} {% block content %}{% endblock %} <!--This block defined in transaction_detail.html is displaying correctly --> </div> ... transaction_detail.html: Note that the test block is contained within the content block. Is that allowed? {% extends 'blog/base.html' %} {% block content %} <!-- This block displays correctly --> <div class="content-section"> <!-- Chat --> {% block test %} <!-- This block does not display at all --> {% endblock %} <div> ... room.html: {% extends 'blog/transaction_detail.html' %} {% block test %} <div class="messages"> <ul id="chat-log"> </ul> <div class="message-input"> <div class="wrap"> <input id="chat-message-input" type="text" placeholder="Write your message..." /> <button id="chat-message-submit" class="submit"> <i class="fa fa-paper-plane" aria-hidden="true"></i> </button> </div> </div> </div> {% endblock %} settings.py (TEMPLATES variable only): I have all apps listed in INSTALLED_APPS TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #DIRS: a list of directories where the engine should look for template source files, in search order. 'DIRS': [os.path.join(BASE_DIR, ''), # root directory … -
Is there a way to maintain structure of nested serializer output across different levels?
I've included a simple example below which will help illustrate the question I'm trying to ask. May have typos/errors since I'm not running the code. Suppose we have models Singer, Album and Track. A singer can have multiple albums and an album multiple tracks (just a series of one to many relationships). ### Models ### class Singer(Model): singer_name = models.CharField(max_length=20) class Album(Model): singer_id = models.ForeignKey(Singer) album_name = models.CharField(max_length=20) class Track(Model): album_id = models.ForeignKey(Album) track_name = models.ChairField(max_length=20) ### Serializers ### class TrackSerializer(ModelSerializer): class Meta: model = Track fields = ['track_name'] class AlbumSerializer(ModelSerializer): tracks = TrackSerializer(read_only=True,many=True) class Meta: model = Singer fields = ['album_name','tracks'] class SingerSerializer(ModelSerializer): albums = AlbumSerializer(read_only=True,many=True) class Meta: model = Singer fields = ['singer_name','albums'] If we have a simple view that requires a singer's name for input, the Singer Serializer would output the following. ### SingerSerializer Output ### { "singer_name":"Singer A", "albums": [ { "album_name":"Album 1", "tracks": [ {"track_name":"Track 1"}, {"track_name":"Track 2"} ] }, { "album_name":"Album 2", "tracks": [ {"track_name":"Track 3"}, {"track_name":"Track 4"} ] } ] } Now suppose in a separate view, I would like people to be able to input an album name (let's say Album 1 in this case). I'd like the output to maintain the … -
ImportError: Couldn't import Django. Working in virtual environment
Hello! As the image shows, I activate the env where I already installed Django. After that, I try to run python3 manage.py runserver and an error message appears, saying Django couldn't be imported. I'm working on Windows 10. I followed the steps given by Delicia Brummitt here but couldn't get it working. What am I doing wrong? Thanks in advance. -
Django Display Live Data without page Refresh
I have developed django application, which basically do tracer route on Cisco devices at a time multiple devices , everything is working fine, but output is displaying after getting output from all devices, I want output to be displayed once we got output from first device, and after getting second that output to be displayed in web page and it go one, please help how to accomplish. How to use ajax here if we have to use -
Mostrar un dataframe en una tabla de un template de Django
Estoy construyendo una tabla con información obtenida de varios dataframe en Django, consigo mostrar correctamente aquellas que conozco el nombre de la columna pero tengo un dataframe que las columnas son dinámicas en función de los días que tiene el mes y esas no consigo mostrarlas. El DataFrame lo creo así vector_notas2=[] sqlconsulta2="SELECT NOTAS,DAY(FECHA) FROM HISTORICOS WHERE MONTH(FECHA)=" + str(mes) + " AND YEAR(FECHA)=" + str(ano) +" AND NOMBRE='" + nombre + "' ORDER BY FECHA" cur2.execute(sqlconsulta2) for notas2,fecha in cur2.fetchall(): vector_notas2.append(round(notas2)) df[nombre]=vector_notas2 El nombre de las columnas está en función de los clientes que tienen datos 5 2758.0 1215.0 ... 0.0 0.0 6 3538.0 1712.0 ... 2.0 2.0 7 2885.0 1774.0 ... 11.0 1.0 8 2459.0 1573.0 ... 7.0 1.0 9 2425.0 1668.0 ... 1.0 0.0 10 2879.0 1987.0 ... 2.0 0.0 11 2614.0 1059.0 ... 0.0 0.0 12 3152.0 1519.0 ... 0.0 0.0 13 2660.0 1609.0 ... 0.0 1.0 14 2464.0 1565.0 ... 5.0 0.0 15 2786.0 1959.0 ... 1.0 2.0 16 1054.0 1040.0 ... 8.0 0.0 17 2987.0 1034.0 ... 0.0 0.0 18 3146.0 1489.0 ... 1.0 0.0 19 2691.0 1697.0 ... 4.0 0.0 20 2329.0 1653.0 ... 7.0 2.0 21 2455.0 2159.0 ... 3.0 0.0 22 … -
Django Attribute Error - 'ForwardManyToOneDescriptor' object has no attribute 'courses'
I have created different models and in the Division model I am taking reference of many models and their primary key is referenced as a foreign key in Division Model. I have declared courses as a model attribute in the Batch Model. This is my models.py file class lab_load(models.Model): lab_code = models.CharField(max_length=10,null=True) subject_name = models.CharField(max_length=100,null=True) subject_abv = models.CharField(max_length=10,null=True) lab_load = models.IntegerField(null=True) semester = models.IntegerField(null=True) max_numb_students = models.CharField(max_length=65,null=True) instructors = models.ManyToManyField(Instructor) def __str__(self): return f'{self.lab_code} {self.subject_name} {self.subject_abv}' class Batch(models.Model): bat_name = models.CharField(max_length=50) courses = models.ManyToManyField(lab_load) @property def get_courses(self): return self.courses def __str__(self): return self.bat_name class Division(models.Model): division_id = models.CharField(max_length=25, primary_key=True) batch = models.ForeignKey(Batch, on_delete=models.CASCADE,blank=True, null=True) num_lab_in_week = models.IntegerField(default=0) course = models.ForeignKey(lab_load, on_delete=models.CASCADE, blank=True, null=True) lab_time = models.ForeignKey(LabTime, on_delete=models.CASCADE, blank=True, null=True) room = models.ForeignKey(LabRoom,on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, blank=True, null=True) def set_labroom(self, labroom): division = Division.objects.get(pk = self.division_id) division.room = labroom division.save() def set_labTime(self, labTime): division = Division.objects.get(pk = self.division_id) division.lab_time = labTime division.save() def set_instructor(self, instructor): division = Division.objects.get(pk=self.division_id) division.instructor = instructor division.save() My views.py file class Data: def __init__(self): self._rooms = Room.objects.all() self._meetingTimes = MeetingTime.objects.all() self._instructors = Instructor.objects.all() self._courses = Course.objects.all() self._depts = Department.objects.all() self._labrooms = LabRoom.objects.all() self._labTimes = LabTime.objects.all() self._labcourses = lab_load.objects.all() self._bats = Batch.objects.all() def get_rooms(self): … -
Problem with audio in Django,<audio> doesn't work
I want to do audio-player in Django,but i have some problems. Here is my models.py class Music(models.Model): name = models.CharField(max_length=50) author = models.CharField(max_length=100) audio_file = models.FileField(upload_to='D:/pythonProject/music/player/templates/music/', blank=True) def __str__(self): return f"{self.author}---{self.name}" views.py def main_page(request): music_list=Music.objects.all() return render(request, 'player/main_page.html', {'music_list': music_list}) and template {% if music_list %} {% for music in music_list %} <audio controls> <source src="{{music.audio_file}}" type="audio/mpeg"> </audio> {% endfor %} {% endif %} When i started my page,i have this : main_page Also,i have "GET / HTTP/1.1" 200 169" in my terminal. Can someone help me with this? Thank!) -
Choice Field Instance Not Displaying Correct Data But Other Fields Are
I am trying to display a ModelForm with prepopulated instance data. It works fine except for the ChoiceField which always displays the first choice given in forms.py ('LP') rather than the choice provided by the instance. View: def review(request): order = Order.objects.get(user__pk=request.user.id) form = ProjectReviewForm(instance=order) context = { 'form': form, } return render(request, 'users/projectreview.html', context) Forms: class ReviewForm(forms.ModelForm): LAND = 'LP' // #INSTANCE ALWAYS SHOWS THIS RATHER THAN INSTANCE DATA DATA = 'DC' STATIC = 'SW' CHOICES = ( (LAND, 'LP'), (DATA, 'DC'), (STATIC, 'SW') ) product = forms.ChoiceField(choices=CHOICES, widget=forms.Select(attrs={'class': 'form-field w-input'}),) class Meta: model = Order fields = '__all__' template: <form method="POST" class="contact-form"> {% csrf_token %} <h2 class="form-heading-small">Please make sure everything you've submitted is correct.</h2> {{ form }} <button type="submit" data-wait="Please wait..." class="button w-button">Looks good!</button> </form> -
Static media images are not displaying in Django
I am working on an online bookstore app. I have a book details page that displays book information in a table, including the book cover image. I am having an issue where the images display correctly when I runserver, however a team member is unable to get the images to display after pulling my code from Github. **all books template:** {% extends 'bookstore/main.html' %} {% load crispy_forms_tags %} {% load static %} from .models import Product {% block content %} <div class="container"> <p> <h1 style="text-align:center;color:green;"> GeekText Complete List of Books<br> </h1> <h3 style="text-align:center;color:green;"> Click the Book Name for More Details </h3> </p> <!-- Bootstrap table class --> <div class="container"> <div class="col-md-12"> <table id="myTable" class="table table-striped tablesorter"> <thead> <tr> <th scope="col">ID #</td> <th scope="col">Book Title</td> <th scope="col">Genre</th> <th data-sorter="false" scope="col">Cover Image</td> <th scope="col">Author</td> </tr> </thead> <tbody> {% for item in items %} <tr> <td scope="row">{{ item.id }}</td> <td><a href="{% url 'book_details_with_pk' id=item.id %}">{{ item.name }}</a></td> <td>{{ item.genre }}</td> <td><img src="{% static item.image %}" width="75" height="100"/></td> <td>{{ item.author }}</td> <td><a href="{% url 'addtocart' item.id %}" class="btn btn-primary">Add To Cart</a> </tr> {% endfor %} </tbody> </table> {% endblock %} </div> </div> </div> **views.py** from django.shortcuts import render, redirect from django.db.models import Q from … -
Which framework could adapt Graphql more better (Django , Flask or FastAPI)?
I have a project which is to build a server-side backend application using Graphql. I have told just to build api endpoints using python(on any of the framework). So I decided to implement graphql . I am having a issue to select between (Django , Flask and FastAPI). So, which framework could adapt the graphql environment in more efficient way(Django , Flask or FastAPI) ? Speed of api also matters alot because real time will transfer . -
Extract title from a webpage using Python
I want to extract title from a webpage using Python. I followed the instructions in below link and got the title of most websites. https://www.geeksforgeeks.org/extract-title-from-a-webpage-using-python/ # importing the modules import requests from bs4 import BeautifulSoup # target url url = 'https://www.geeksforgeeks.org/' # making requests instance reqs = requests.get(url) # using the BeaitifulSoup module soup = BeautifulSoup(reqs.text, 'html.parser') # displaying the title print("Title of the website is : ") for title in soup.find_all('title'): print(title.get_text()) But I can't get title of website 1688.com. Example: https://detail.1688.com/offer/629606486448.html Can you help me to get the title of this page? Thanks! -
Why does template see only one file in static?
I am trying to display a photo. Created new folder 'img' in static, but the template does not see new folder, it sees only old one. Or when I add new files in the old folder it does not see it. Could not find the problem. Maybe it should be updated somehow? -
Post fullcalendar calendar.getevents() array object to bakend
When I try to send fullcalendar events to my Django backend, it seems that ajax is not sending the proper data... How can I send those events to the backend properly? I am using jquery ajax, here is my code: $.ajax({ url: '/home/update_event/', method: 'POST', data: calendar.getEvents(), success: (e)=>{ $('#information').text('Your event is saved') } }); -
Django admin action not repeating
I have the following Admin action (in my admin.py file) which in designed to download pdf files for selected items. It seems to be working apart from the fact that it will only create and download a pdf for the first item in the queryset. I think the problem lies in the 'return response' line but I don't know what else to use in its place. Any input would be great, I'm stomped! @admin.register(ReleaseForm) class ReleaseAdmin(admin.ModelAdmin): def participant(self, obj): return str(obj.customer.last_name) + ", " + str(obj.customer.first_name) def training(self, obj): return str(obj.order.training_registered.name) def print_release(self, request, queryset): updated=queryset.count() print (updated) for obj in queryset.all(): customer=obj.customer order=Order.objects.get(customer=customer) firstname = obj.customer.first_name lastname = obj.customer.last_name nwta = order.training_registered.name data = {'order':order,'firstname': firstname, 'lastname': lastname, 'nwta':nwta,} pdf=release_render_to_pdf('accounts/pdf_template.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Release_%s_%s.pdf" %(lastname,nwta,) content="attachment; filename=%s" %(filename) response['Content-Disposition'] = content print(obj.customer) return response self.message_user(request, ngettext( '%d Relase Form was successfully printed.', '%d Relase Forms were successfully printed.', updated, ) % updated, messages.SUCCESS) print_release.short_description="Print Release Form(s)" list_display = ('participant','release_status','release_date_submitted' ,'note' ) actions = ['print_release'] ordering = ('customer',) list_filter = ('customer__order__training_registered__training__name','customer__order__training_registered', 'customer__order__regstatus','release_status','release_date_submitted' ,'note') search_fields = ('participant','note') -
How to Deploy Django website to GCP Cloud Run using VS Code
I need guidance to deploy my existing django website which is in my windows machine to Google Cloud Platform's Cloud Run using VS Code. I saw there's a documentation related to it but I'm not able to understand what all to change in my django's settings.py and how will the database would be configured. Please guide me as what all should I change to my django app so that I can deploy it through my VS Code. -
Domain Not Getting Linked to Amazon AWS fby Django Nginx
I have used this tutorial - https://dev.to/subhamuralikrishna/deploying-django-application-to-aws-ec2-instance-2a81 ( I changed the os to ubuntu from ami and I skipped the database part as I wanted it to be db.sqllite3 only. I bought my domain from Hostinger- gyanism.in and gyanism.xyz . i Created two ec2 instances for each domain following the same procedure and both of them didn't work. After hosting with nginx they both show only loading but they never load. I changed the nameservers properly and it has been more than one day now but the site doesn't seem to load either. I am attaching screenshots of the rest details - Hostinger nameservers spec for gyanism.in -- Route 53 Spec - My server file in etc/nginx/sites-available - my server file in etc/nginx/sites-enabled - Nginx is working fine and gunicorn is working fine too. But on domain the site is not showing! Please Help urgently -
Django. Remind to email events
I'm new to django, and I need to create a browser-based event reminder application and an email that I will write in the application. Is it possible to do this on pure django, or do you need something to use in addition. In which direction should I look for information? -
Update multiple objects in django rest
I have blogs and I do reorder. When I send multiple objects by postman and then update and save by loop I get an error. These are the objects of what i send -> [ { "id":18, "name": "a", "is_active": true, "author_name": 1, "category": 1, "tag": [1,2], "order": 888888 }, { "id": 17, "name": "a", "is_active": true, "author_name": 1, "category": 1, "tag": [ 1 ], "order": 999999999 } ] but i have this error -> { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } this is my code- > serializer.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ['id', 'name', 'is_active', 'author_name','category','tag','order'] extra_kwargs = { 'is_active': {'read_only': True}, 'id':{"read_only":False} } view.py class UpdateOrder(generics.UpdateAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() def put(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) for i in serializer.validated_data: blog = Blog.objects.get(id=i["id"]) serializer = BlogSerializer(instance=blog, data=request.data) serializer.is_valid(raise_exception=True) serializer.save()