Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sub categories Django
I am new to Django and i came across this blog project. The blog is categorized into 3 category. There are posts already organized into each category. I wanted to add subcategory to further classify the post. Admin should be able to add new subcategories through the admin portal. I made class SubCategory model and register it to the admin and add foreign key = Post 2.Admin should be able to specify which subcategory a post belongs to through the admin portal. [Nice to have] Admin should be able to select which subcategory a post belongs to through the post list in the admin portal (/admin/blog/post). 3.A post can exist with or without a subcategory. Users on a blog category page should see a dropdown where they can select a subcategory and the results get filtered to display posts under that subcategory. “All” should be selected by default. The dropdown should look nice on all screen sizes (mobile, tablet, desktop). [Nice to have] The subcategories are displayed in the dropdown in an alphabetical order. [Nice to have] If a category does not have subcategories, the dropdown is not displayed. How do i proceed further ? Especially bring the filter to … -
Serializing a Django object
I am trying to serialize an object so that I can use it to build an API. The model I want to serialize is my Profile model. The problem is when I go to the url: \users the output is: ["[{\"model\": \"network.profile\", \"pk\": 2, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 3, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 4, \"fields\": {\"friends\": []}}]"] I was expecting something like: [{"user": "one", "friends":["foo", "bar", "baz"]}, {"user": "two", "friends":["one", "bar"]}] models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) def serialize(self): return { "user": self.user, "friends": [user.username for user in self.friends.all()] } @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except Profile.DoesNotExist: Profile.objects.create(user=instance) class Post(models.Model): creator = models.ForeignKey("Profile", on_delete=models.CASCADE) content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) def serialize(self): return { "id": self.id, "creator": self.creator.user.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } views.py def allUsers(request): if request.method == "GET": profiles = serializers.serialize("json", Profile.objects.all()) else: return JsonResponse({"error": "Error displaying all users"}, status=400) return JsonResponse([profiles], safe=False) def allPosts(request): if request.method == "GET": posts = Post.objects.all() else: return JsonResponse({"error": "Error displaying all posts"}, status=400) posts = posts.order_by("created").all() return JsonResponse([post.serialize() for post in posts], safe=False) … -
Data Manager Role in Django
I'm a beginner in Django and I'm building a prison management system. I require three types of users -- superuser, data manager, and police officer. The superuser should be able to add any kind of user. The data manager should be able to add a police officer and perform CRUD on prisoner details. The police officer should only be able to view prisoner details. Nobody should be able to register themselves to the website. Here's part of my models.py file for the prison app: from django.db import models as md class User(AbstractUser): is_police = md.BooleanField(default=False) is_data_manager = md.BooleanField(default=False) After doing this, I found that the superuser can no longer add any users, they can only add groups. It would also be desirable for the data manager to be able to use the django-admin interface. -
UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte
Good afternoon! I'm Learning Django. I'm writing my first website in Visual Studio. The following problem occurred. I CAN't solve it. Can you please tell me what to do. When the site starts, the server outputs the following: UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Exception Location: C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.17 76.0_x64__qbz5n2kfra8p0\lib\codecs.py, line 322, in decode Python Executable: C:\Users\DNS\AppData\Local\Microsoft\WindowsApps\PythonSoftw areFoundation.Python.3.8_qbz5n2kfra8p0\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\DNS\\djangoset1\\learning_log', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\python38.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\DNS\\AppData\\Local\\Microsoft\\WindowsApps\\Pyt honSoftwareFoundation.Python.3.8_qbz5n2kfra8p0', 'C:\\Users\\DNS\\AppData\\Local\\Packages\\PythonSoftwareFou ndation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib\\site-packages'] Server time: Sat, 31 Oct 2020 21:15:37 +0000 -
clone a specific attribute from Class A to Class B OneToOneField Django
i want to clone some attributes from user class from django, to an "Employee" class, so when i register a new user with the fields: "First Name" and "Last Name" clone and save on the "Employee" class too. The idea is something like this. class Employee(models.Model): id_em= models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = ATTRIBUTE "FIRST_NAME" FROM DJANGO USER AUTH MODEL. last_name = ATTRIBUTE "LAST_NAME" FROM DJANGO USER AUTH MODEL. bye! -
Django: Referencing uploaded file name in django web pages
Hello I am very new to python / django and I am working on a web app that will take a file that a user uploads, push it to a public S3 bucket and return a link to the file that the user can use elsewhere. After lots of trial and error I was able to get the basic functionality of the system to work. The one part I am struggling with is returning the link of the file that has been uploaded. Here is my views.py: def index(request): """The home page for the upload tool""" if request.method == 'POST': uploaded_file = request.FILES['image'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) get_uploaded_file() return render(request, 'upload_tool_app/success.html') return render(request, 'upload_tool_app/index.html') Here is my sucess.html file that I want to contain the link to the uploaded file: {% block content %} <h1>SUCCESS!</h1> <h2>Your image can be accessed from the following link:</h2> <a href="https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}"> https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}</a> {% endblock %} My question is how do I reference the request.Files['image'] from views in the HTML? I would really appreciate any input on this matter. -
Refactoring a field and it's references in Django
I have a model that is as follows: class Car(models.Model): make = models.CharField(max_length=128, verbose_name=_("car make"), blank=True) I now need to refactor this so that make becomes a class of it's own. class Car(models.Model): make = ForeignKey(CarMake, verbose_name=_("car make"), null=True, on_delete=models.CASCADE, blank=True) One way I thought of was changing make to legacy_make and adding a new field, _make, and then a property / getter, but it doesn't work (I understand you can't do queries this way?) Is the best ways really to a) Migrate old data to use new make class or b) Change all references to take into account possible new car make if it is present -
Django form: phone field not showing
I would like to create a contact form on my Django website. For now, this is my code: models.py: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Client(models.Model): phone = PhoneNumberField(null=False, blank=True, unique=True) forms.py: from django import forms from phonenumber_field.modelfields import PhoneNumberField class ContactForm(forms.Form): fullName = forms.CharField(max_length=100) email = forms.EmailField() phone = PhoneNumberField() message = forms.CharField(widget=forms.Textarea) views.py: def contact(request): # return render(request, 'contact.html') if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # send email code goes here return HttpResponse('Thanks for contacting us!') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) html: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> I of course installed phonenumber_field and added it in settings.py This is the result, phone field missing: Any help is hugely appreciated! Thanks for your time. -
How to make the filter not be deleted when changing pages with django-filter and paginate
I have a problem, it turns out that I made a filter with django_filter in my ListView, the situation is that the filter works perfect but when performing a search that has more than 4 results (I have my paginate_by = 4) and want to go to On page 2 the filter is erased and shows everything as in the beginning before filtering, I will attach my code and images so you can see. My views.py @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employee'): return redirect(reverse_lazy('home')) return super(EmployeeListView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset()) return context def get_queryset(self): queryset = super().get_queryset() return EmployeeFilter(self.request.GET, queryset=queryset).qs filter.py import django_filters from .models import Employee, Accident class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = { 'rutEmployee' : ['startswith'] } my employee_list.html {% extends 'core/base.html' %} {% load bootstrap %} {% load static %} {% block title %}EMPLEADOS{% endblock %} {% block content %} <main role="main"> <div class="row"> <div class="col-md-12 stretch-card"> <div class="card"> <div class="card-body"> <p class="card-title">Lista de Empleados</p> <div class="table-responsive"> <form method="GET"> {{ filter.form|bootstrap }} <button type="submit" class="btn btn-primary">Filtrar</button> </form> <hr> <table class="table table-bordered"> … -
Django backend, make email or phone required
Is an email automatically set to required when using Django? I'm trying to build an API where email or phone is required. This is the backend I built from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from accounts.models import User class UserBackend(ModelBackend): def authenticate(self, request, **kwargs): email = kwargs['username'] phone_number = kwargs['username'] password = kwargs['password'] try: app_user = User.objects.get(email=email) if app_user.check_password(password) is True : return app_user except User.DoesNotExist: app_user = User.objects.get(phone_number=phone_number) if app_user .check_password(password) is True : return app_user except User.DoesNotExist: pass -
Django Geolocation with API maps
I am making an IP address tracker with Django, I am using the Google Maps API to create the map and geolocate this API https://ip-api.com/docs/api:json, I want my location to be displayed on the map automatically when you open the page and if it's another IP address the location on the map of that IP address, but I don't know how to integrate the Javascript code with Django or if there is another way to make it easier or with other APIs. views.py: from django.shortcuts import render from django.views.generic import View import requests def home(request): response = requests.get('http://ip-api.com/json/') geodata = response.json() data= { 'query': geodata['query'], 'country': geodata['country'], 'timezone':geodata['timezone'], 'lat': geodata['lat'], 'lon': geodata['lon'], 'isp':geodata['isp'], 'api_key':'My api key', } return render(request, 'geolocationip/home.html', data) script.js: function initMap(){ var coord = {lat: -34.397, lng: 150.644}; var map = new google.maps.Map(document.getElementById('map'),{ zoom: 10, center: coord }); var marker = new google.maps.Marker({ position: coord, map: map }); } home.html: {% extends 'base.html' %} {% load static %} {% block content %} <h1 id="ip">IP Address Tracker</h1> <form method="get"id="form"> <input><button type="submit">Search</button> </form> <div id="card"> <p>Your ip address is <strong>{{ query }}</strong>, and you are probably in <strong>{{ country }}</strong> right now, and <strong>{{timezone}}</strong> and <strong>{{isp}}</strong></p> </div> <div id="map"></div> … -
django: delete pevious photo while adding a new photo
I am developing a user profile where users can add profile picture. Adding the picture is working fine but when I want to add a new photo, old photo doesn't go away. My django version is 3.1 and I have tried django-smartfields but still it is not working. Can anyone help? views.py from smartfields import fields class Profile_Pic(models.Model): user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic') profile_pic = fields.ImageField(upload_to='media', default='admin_car/static/images/img_avatar.png', blank=True) class Meta: db_table = 'Profile_Pic' user_image.html {% extends 'datas/base.html' %} {% block content %} {% load static %} <h1 class="text-center" style="color: white">Add Profile Picture</h1> <br><br> <div class= "col-md-6.offset-md-3"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> <p>Data Error, Please Check Again.....</p> {% for field in form %} {% if field.errors %} {{ field.errors }} {% endif %} {% endfor %} </div> {% endif %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"> </form> </div> {% endblock %} -
How to use variables in webpage address in Django?
I am creating a search bar such that if the name of a webpage is entered, I want the user to be redirected to that page. To implement this, I have written the following code in my views.py file- if(request.method=="POST"): for entry in entries: if(entry==request.POST['q']): return HttpResponseRedirect("wiki/{{entry}}") ("entries" represents the set of valid strings that have a page attached to them) I am facing a problem in the last line where the browser is interpreting {{entry}} literally, instead of replacing the value of entry variable there. On running this, I am getting an error - TypeError, decoding to str: need a bytes-like object, NoneType found This is strange, because I have written a similar line in an html page which is working just fine - <a href="wiki/{{entry}}">{{entry}}</a> Is there a different way to write in .py files compared to .html files? If so, how can I write it? P.S. - For Reference, I am also attaching the url from the urls.py file that is being accessed by these lines of code path("wiki/<str:name>",views.addr,name="addr") -
How can I display javascriptfunctions results from one python django template in another?
I have a template in my Python Django project, which has a point counter based on the script below: function nowScrolling( last_known_scroll_position ) { let percentage = last_known_scroll_position / ( window_height - client_height ) * 100; progressbar.style.right = "calc( 100% - " + Math.round( percentage ) + "% )"; document.getElementsByClassName('score')[0].innerText= "Congrats! You have just earned " + Math.round(percentage)/2 +" points!"; } I wonder how to refer the score (function result) on another template / page (Profile, which is going to summarize users points? Thank you very much! -
chartjs data isn't passing to django webpage
I'm trying to build a webpage with a chart in it. For the chart i'm using Chartjs. Hardcoded data is no problem for the Chartjs chart. But if I'm trying to pass dynamic data the chart doesn't render. The labels and results output is 46 (the dataframe is 46 rows with 1 column) View.py def results(request): return render(request, 'results.html') def result(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['file'] # handle_uploaded_file(data) data = pd.read_csv(data,header=0, sep=',') df = data.values df2 = pd.DataFrame(df.reshape(-1,len(data.columns))) x = getPredictions(df2) x = np.array(x) result = x.reshape(-1,1).round() df = pd.DataFrame(data=result, columns=['output']) labels = len(df) # result = list(result) return render(request, 'results.html', {'result': result, 'labels': labels}) else: form = UploadFileForm() return render(request, 'index.html', {'form': form}) html page {% extends "base.html" %} {% block content %} <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <div class="content"> <div class="row"> <div class="col-sm-8"> <div class="card card-tasks"> <h4>Chart.</h4> <canvas id="line-chart" width="500" height="350"></canvas> <script> new Chart(document.getElementById("line-chart"), { type: 'line', data: { labels: {labels|safe}, datasets: [{ data: {result|safe}, label: "output chart", borderColor: "#3e95cd", fill: false } ] }, options: { title: { display: true, text: 'output chart' } } }); </script> </div> </div> </div> </div> {% endblock content %} -
MySQL GROUP BY slows down query x1000 times
I'm struggling with setting up proper, effective index for my Django application which uses MySQL database. The problem is about article table which for now has a little more than 1 million rows and querying isn't as fast as we want. Article table structure looks more or less like below: Field Type id int date_published datetime(6) date_retrieved datetime(6) title varchar(500) author varchar(200) content longtext source_id int online tinyint(1) main_article_of_duplicate_group tinyint(1) After many tries I came that below index gives best performance: CREATE INDEX search_index ON newsarticle(date_published DESC, main_article_of_duplicate_group, source_id, online); And the problematic query is: SELECT `newsarticle`.`id`, `newsarticle`.`url`, `newsarticle`.`date_published`, `newsarticle`.`date_retrieved`, `newsarticle`.`title`, `newsarticle`.`summary_provided`, `newsarticle`.`summary_generated`, `newsarticle`.`source_id`, COUNT(CASE WHEN `newsarticlefeedback`.`is_relevant` THEN `newsarticlefeedback`.`id` ELSE NULL END) AS `count_relevent`, COUNT(`newsarticlefeedback`.`id`) AS `count_nonrelevent`, ( SELECT U0.`is_relevant` FROM `newsarticlefeedback` U0 WHERE (U0.`news_id_id` = `newsarticle`.`id` AND U0.`user_id_id` = 27) ORDER BY U0.`created_date` DESC LIMIT 1 ) AS `is_relevant`, CASE WHEN `newsarticle`.`content` = '' THEN 0 ELSE 1 END AS `is_content`, `newsproviders_newsprovider`.`id`, `newsproviders_newsprovider`.`name_long` FROM `newsarticle` USE INDEX (SEARCH_INDEX) INNER JOIN `newsarticle_topics` ON (`newsarticle`.`id` = `newsarticle_topics`.`newsarticle_id`) LEFT OUTER JOIN `newsarticlefeedback` ON (`newsarticle`.`id` = `newsarticlefeedback`.`news_id_id`) LEFT OUTER JOIN `newsproviders_newsprovider` ON (`newsarticle`.`source_id` = `newsproviders_newsprovider`.`id`) WHERE ((1) AND `newsarticle`.`main_article_of_duplicate_group` AND `newsarticle`.`online` AND `newsarticle_topics`.`newstopic_id` = 42 AND `newsarticle`.`date_published` >= '2020-08-08 08:39:03.199488') GROUP BY `newsarticle`.`id` … -
Accessing foreignkey in models
I'v been created a django project a these are my models class User(AbstractUser): phone = models.CharField(max_length=11, blank=False,null=False, verbose_name='تلفن') customer_basket = models.ManyToManyField(basket, blank=True,verbose_name='سبد سفارشات',related_name="basket") customer_slug = models.SlugField(null=True,unique=True, max_length=100, verbose_name='نامک') is_worker=models.BooleanField(default=False,verbose_name="اپراتور سفارش") And this one : class basket(models.Model): id = models.AutoField(auto_created=True, primary_key=True,serialize=False, verbose_name='ID') created_date = models.DateField(auto_now_add=True, verbose_name='تاریخ سفارش') total_money = models.IntegerField(default=0, blank=True, verbose_name='قیمت کل سفارشات') prepaid = models.IntegerField(default=0, blank=True, null=True, verbose_name='پیش پرداخت') deliver_date = models.DateField(auto_now=True, verbose_name='تاریخ تحویل') orders = models.ManyToManyField(order,blank=True, verbose_name='سفارش ها',related_name='orders',editable=True) def __str__(self): return str(self.id)+' '+str(self.created_date) class Meta: verbose_name = 'سبد خرید' verbose_name_plural = 'سبد های خرید' as you can see customer_basket in User class is Many to many I want to perform something like this: 'SELECT id FROM basket WHERE id=customer_basket_id But I don't know how to do that in midel form I want to use the result in limit_choices={'id':customer_basket_id} But when i run this it sais customer_basket_id is not defined I mean: How to access foreignkey id of a model inside of another model(customer_basket id in User model) Second how to access name of User in basket model? -
How can I get the app name in Django 3+ within a template?
I am looking for something like {{ appname }} to access the current app name of a site within a template. Unfortunately, answers for older versions of Django seem to produce errors at various positions in the code. Thank you! -
Trigger timers depending on datetime in database and render a template when each timer stops using Django
I have a datetime column in database. Each raw in this column expresses the start time of a lesson which may be any datetime through the current year. What I want to do is a try to trigger a function/view to start video call for instructor and redirect each client has this lesson before one minute to join lesson page. What I want to understand is what's the best practice to do that in Django? where I have to set this timers if they have to be contained in all pages to do redirection in any time? and how to do those redirections? Note I'm trying not to return timers as context in every view. So I want the best practice to return timers from one place and contains them in all pages. -
django - how to save api data into model from template button
I am using the Yelp API to search bars in a any location. This uses a template called results.html that has a button. Clicking this button should save the Yelp API unique ID of a Bar into my models. In my results dictionary that I loop over I call this 'id'. This is where I am having issues, taking the id from the template, saving it in the add_list views to the model BarList. This will not save to my database, I believe the main problem is my logic in add_list. Views.py def index(request): if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): city = form.cleaned_data['city_name'] API_KEY = 'MyAppKey' url = 'https://api.yelp.com/v3/businesses/search' headers = {'Authorization': 'Bearer {}'.format(API_KEY)} params = {'term':'bar','location':city} req = requests.get(url, params=params, headers=headers) parsed = json.loads(req.text) businesses = parsed["businesses"] final_result = [] for business in businesses: results = { 'id': business['id'], 'business': business['name'], 'rating': business['rating'], 'image_url': business['image_url'] } final_result.append(results) context = {'final_result': final_result} return render(request, 'API/results.html', context) else: form = CityForm() return render(request, 'API/home.html', {'form':form}) def add_list(request): if request.method == 'POST': api_id = results.get("id") Bar = BarList(api_id=api_id) Bar.save() else: return render(request, 'API/results.html') Models.py class BarList(models.Model): api_id = models.CharField(max_length=100) Urls.py urlpatterns = [ path('', views.index, name='API-home'), path('list', views.list, name='API-list'), … -
Integrating Scrapy to a Django project
I am following a tutorial: https://medium.com/@tiago.piovesan.tp/make-a-crawler-with-django-and-scrapy-a41adfdd24d9 github: https://github.com/TiagoPiovesan/scrapy_rottentomatoes to integrate scrapy to my django project. After doing the exact same things as shown here, there is no data in my database after crawling. Also downloaded the source code from git and nothing happens with no errors shown. Steps I made after downloading the project from github: 1.cd into source folder 2.created virtual environment 3.installed django, scrapy, scrapy-djangoitem, Pillow 4.makemigrations, migrate 5.created superuser 6.cd into crawling folder and run: scrapy crawl rottentomatoes The spider runs perfectly: 2020-10-31 20:10:52 [scrapy.core.engine] INFO: Spider closed (finished) but nothing happens. When I followed the code I had errors with importing the movies.models module in scrapy settings, but it seemed a pylint error only as the code run successfully. By simply opening the github version there is no visible errors, i can simply see no results. -
how to enable delete button in my form in Django?
I have a table containing records of a database table.In the table, I have put a Delete button for each row(each row shows 1 record).I need to call a view for deleting that record but I don't want to reload a new page.I need staying in same template and just by clicking a delete button,the related row gets deleted. The needed part of the template : {% for each in power_recs %} <tr> <td>{{ each.power }}</td> <td><form method="post" action="{% url 'app:name' %}"> {% csrf_token %} <input name="key" value="{{ each.pk }}" hidden> <button class="btn btn-outline-danger" type="submit">Delete</button></form> </td> </tr> {% endfor %} the view for deleting each row : def filter(request): pk = request.POST.get("key",None) record = Model.objects.get(pk=pk) record.delete() return render(request) ***I don't know what should I render here**** How can I call this view without changing the page that I am in it?(Imagine you have a table with 10 records.You want to delete 3 of the records 1 by 1.You click first record and it gets deleted and now you are again in the same page so you can click the next one and delete it.) Thanks. -
Django channels - connection timed out
I created a django-channels app that works without any problem in local. I'm now trying to deploy it to a DigitalOcean droplet. The whole Django WSGI part works, the only part not working is Django-Channels. If i try to connect to any consumer like below: ws://MYURL:9000/main I get the following error on my Chrome console: WebSocket connection to 'ws://MYURL:9000/main' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT Daphne service: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://MYURL/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } What am i doing wront here? The exact same code works locally, but it looks like whenever i try to access django channels from outside i get refused. -
Django Channel Custom Authentication Middleware __call__() missing 2 required positional arguments: 'receive' and 'send'
I am writing a custom authentication middleware for django channels as follows: class TokenAuthMiddleware: def __init__(self, inner): # Store the ASGI application we were passed self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): ## my logic to get validate user and store the user in user data ... ... ... self.scope['user'] = user_data inner = self.inner(self.scope) return await inner(receive, send) but on trying to connect to web socket from front end I get the following error TypeError: __call__() missing 2 required positional arguments: 'receive' and 'send' -
how can I add Image to my django database and display it in frontend
I am making a blogging website in Django. I want to add a functionality with which the user can upload an image in the form, which will be used as a thumbnail for that blog. I have added imageField in models.py file, now I am not getting how shall I take the image input from the user in the form section? post models.py: class Post(models.Model): sno = models.AutoField(primary_key=True) thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") title = models.CharField(max_length=50) content = RichTextField(blank=True, null=True) author = models.CharField(max_length=50) slug = models.CharField(max_length=200) timeStamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timeStamp'] def __str__(self): return self.title + " by " + self.author html forms: <form action = "{% url 'addblog' %}" method="post"> <div class="form-group"> <label for="title" id="Title">Title</label> <input type="text" class="form-control" id="title" name="title"/> </div> {% csrf_token %} <div class="form-group"> <textarea name="content"></textarea> <script type = 'text/javascript'> CKEDITOR.replace("content") </script> </div> <button type="submit" class="btn btn-primary my-1" id='contact-button'>Post</button> </form> currently the add blog page looks like this: now I want a choose file option after the content text area where the user can upload an image and then that image gets saved in the database, after which I can display the image in the blog section at frontend.