Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload and manipulate xml and image file in django
This code return a TypeError as expected str, bytes or os.PathLike object, not InMemoryUploadedFile I don't know how to pass user data in the form of file and image to my code.py file for making changes to the original. views.py def home(request): new_image = None file = None form = ScanForm() if request.method == 'POST': form = ScanForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] xml_file = request.FILES['xml_file'] new_image = code.create(image, code.search( xml_file)[0], code.search(xml_file)[1]) form.save() return render(request, 'app/home.html', {'form': form, 'new_image': new_image}) else: form = ScanForm() return render(request, 'app/home.html', {'form': form, 'new_image': new_image}) printing image and xml_file successfully prints out their names forms.py class ScanForm(forms.ModelForm): class Meta: model = Scan fields = '__all__' models.py class Scan(models.Model): image = models.ImageField(upload_to='images') xml_file = models.FileField(upload_to='files') processed_at = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=500, null=True) class Meta: ordering = ['-processed_at'] def __str__(self): return self.description Here is the code for manipulation of image according to the data in the xml code.py def search(path): new = [] object_names = [] object_values = [] txt = Path(path).read_text() txt.strip() names = et.fromstring(txt).findall('object') for i in names: object_names.append(i[0].text) values = et.fromstring(txt).findall('object/bndbox') for i in values: for j in i: object_values.append(int(j.text)) return object_names, object_values def create(image, object_names, object_values): img = cv.imread(image) on = … -
How to display latest 5 orders by using for loop in jinja (django)
The code below will display all the orders but now I want to display only 5 latest orders in my template. Can anyone explain to me how can I iterate only 5 latest orders through jinja? code <div class="card card-body"> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for i in orders %} <tr> <td>{{i.product}}</td> <td>{{i.date_created}}</td> <td>{{i.status}}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' i.id %}">Update</a></td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' i.id %}">Delete</a></td> </tr> {% endfor %} </table> </div> -
problems with authentication on the client
I am starting with a project with graphql I use django graphene for the backend and apollo with react but I have problems with authentication I am using django-graphene-auth for this but I don't know how to implement it on the client if I have to save it in a local storage or in a cookie in addition to how do I retrieve the necessary data, for example the profile if the only thing that returns the token is the username, I do not know if you can help me with some books, videos or any type of information where they explain this -
django csrf token not setting in cookie in production
I am using django and react js for my application and when i am passing csrf token in loclhost it ia working fine but in production csrftoken is missing.`axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; class LoginService extends Component { loginUser(formData) { const config = { headers: { 'content-type': 'application/json'}, "X-CSRFToken": Cookies.get('csrftoken'), withCredentials: true } return axios.post(${API_BASE_URL}api/user/v1/account/login_session/,formData,config); }` -
Get Django object attributes from url to use as context
I filtered a list and sent a link from the chosen record to my view. I want to use the attributes of that object as context to filter some models. I tried this code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entity = self.entity context["entity"] = entity This raises the error: 'EffectivenessProcessOwner' object has no attribute 'entity' The local variables reflected are: Variable Value __class__ <class 'internalcontrol.views.EffectivenessProcessOwner'> context {'pk': 1, 'view': <internalcontrol.views.EffectivenessProcessOwner object at 0x00000284A5672040>} kwargs {'pk': 1} self <internalcontrol.views.EffectivenessProcessOwner object at 0x00000284A5672040> How do I get the entity attribute (and others) from the object? -
Tring to deploy django api on aws getting error
CloudFormation stack missing, re-deploy to enable updates ERROR:Could not get API ID. Traceback (most recent call last): File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\core.py", line 2585, in get_api_id response = self.cf_client.describe_stack_resource( File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\client.py", line 386, in _api_call return self._make_api_call(operation_name, kwargs) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\client.py", line 705, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (ValidationError) when calling the DescribeStackResource operation: Stack 'django-react-fa-dev' does not exist Oh no! An error occurred! :( ============== Traceback (most recent call last): File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\cli.py", line 3422, in handle sys.exit(cli.handle()) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\cli.py", line 588, in handle self.dispatch_command(self.command, stage) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\cli.py", line 641, in dispatch_command self.update( File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\cli.py", line 1208, in update self.zappa.add_binary_support(api_id=api_id, cors=self.cors) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\zappa\core.py", line 2082, in add_binary_support response = self.apigateway_client.get_rest_api(restApiId=api_id) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\client.py", line 386, in _api_call return self._make_api_call(operation_name, kwargs) File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\client.py", line 677, in _make_api_call request_dict = self._convert_to_request_dict( File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\client.py", line 725, in _convert_to_request_dict request_dict = self._serializer.serialize_to_request( File "c:\users\tusha.virtualenvs\django_react_faceapp-osxjngpa\lib\site-packages\botocore\validate.py", line 319, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter restApiId, value: None, type: <class 'NoneType'>, valid types: <class 'str'> -
Django custom view "You don't have permission error"
I have created my own view for Django admin. Here, I want to add a link to order to view order without disturbing change_form like this. I added following code to admin.py. def get_urls(self): urls = super(OrderAdmin, self).get_urls() custom_urls = [ path('order/<int:order_id>/view', self.view_order, name="view_order") ] print(urls) return urls + custom_urls def view_order(self, request, order_id): order = Order.objects.get(pk=order_id) return render(request, 'shop/order.html', {'order':order}) Now when I click the link following screen appears. What's the problem ? How can I get the original dashboard retaining what I have done ? -
Django Full Text Search match based on priority fields
I have a Django model which I will use for search. I am implementing a search algorithm to return search results on certain conditions matching priority class Freelancer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) skills = models.ManyToManyField( 'skill.Skills', ) gigs = models.ManyToManyField( 'gig.gigs', ) I am implementing a search API so that it results in the following conditions user first name = 30% skills = 90 % gigs = 50% My search should match/rank with the above condition I perform a search. This is my rest api view: class FreelancerSearchAPIView(generics.ListAPIView): filter_backends = [filters.SearchFilter] serializer_class = FreelanerSearchSerializer queryset = Freelancer.objects.all() search_fields = [ 'user__username', 'skills', 'gigs' ] Currently, it's working away which I don't want. Like I just want to type 'python` in search fields, it should search the table with matching based on priority in all fields. and the result should be based on the priority match Can anyone please tell me how can I achieve this? I have read this doc: https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/search/#weighting-queries but still not sure what is the best possible way to do it -
Is there a way I can make users to pay first before making a post on a Django website?
This is my model from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.urls import reverse class Escort(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.TextField() phone = models.CharField(max_length=14) ethnicity = models.CharField(max_length=20) orientation = models.CharField(max_length=20) location = models.CharField(max_length=40) area = models.TextField() skin_color = models.CharField(max_length=40) hair_color = models.CharField(max_length=40) services = models.CharField(max_length=255) paid = models.BooleanField(default=False) def __str__(self): return self.name + '~' + str(self.author) def get_absolute_url(self): return reverse('escort-details', args=(str(self.id))) These are my views from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Escort #def home(request): #return render(request, 'home.html',{}) class HomeView(ListView): model = Escort template_name = 'home.html' class EscortDetailView(DetailView): model = Escort template_name = 'escort_details.html' class AddEscortView(CreateView): model = Escort template_name = 'add_escort.html' fields = '__all__' These are my urls from django.urls import path from . import views from .views import HomeView, EscortDetailView, AddEscortView urlpatterns = [ #path('', views.home, name="home"), path('', HomeView.as_view(), name="home"), path('escort/<int:pk>', EscortDetailView.as_view(), name="escort-details"), path('postad/', AddEscortView.as_view(), name="add-escort"), ] I also have four templates for the four views What I am basically doing is to create a website to advertise escort services. I want a user to sign up/sign in and click on the link "PostAd" and be redirected to a page with … -
Django - How to group forms.CheckboxSelectMultiple items by unique parent field value?
My category models: class Category(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=255, default='') def __str__(self): return "%s" % (self.name) class SubCategory(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=255, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['name'] Here's my Job class: class Job(models.Model): ... skill_set = models.ManyToManyField(SubCategory) my forms.py: class CustomSelectMultiple(ModelMultipleChoiceField): def label_from_instance(self, obj): return "%s - %s" %(obj.category, obj.name) # return "%s" %(obj.name) class NewJobForm(forms.ModelForm): skill_set = CustomSelectMultiple(widget=forms.CheckboxSelectMultiple, queryset=SubCategory.objects.all()) class Meta: model = Job fields = ['skill_set'] In my template file I have a standard: {{ form|crispy }} In my context: form = NewJobForm() So as expected in my form I see: But I would like my checkboxes to be display as such: How can I achieve that? -
how to build a model on top of the other on django
I have two models Job Position: It's the first object I create and represent a position in a company. ` Job offer: It is related to Job Position through a foreign key and represent a job offer sent out for a specific Job Position Each job position can have multiple job offers associated as you can send multiple job offers out. Now, the Job Position model has some data such as "Salary" that I would like each Job Offer instance to inherit automatically BUT I would also like to be able to change at the Job Offer level (after negotiations). For example: A jobposition is open with salary=50k 10 joboffers are sent out, each with salary 50k After some negotiations, some joboffers are changed to salary 80k Should joboffers have a salary field that I simply set equal to the salary jobposition when I create the object, or should I find a way to tie it initially within the model definition through some sort of foreign key but then make it flexibile? class JobPosition(models.Model): .. salary=models.Integer() class JobOffer(models.Model): position=models.ForeignKey(JobPosition, on_delete=models.CASCADE) ... -
Bulk Delete objects in Django using sqlite
When I use django with sqlite3 and try to delete many objects, FilmPage.objects.all().delete(), I will sometimes run into an error which says django.db.utils.OperationalError: Expression tree is too large (maximum depth 1000) When I tried to limit the number of objects FilmPage.objects.all()[:999].delete(), I will get an error AssertionError: Cannot reorder a query once a slice has been taken. Any suggestions? -
How to use Google One Tap login with django-allauth?
Google One Tap login doesn't use an OAuth flow. My question is how to integrate it into a django app that uses allauth for authentication? I found a tutorial through which you can get the basic details like email, name from the one tap login https://developers.onelogin.com/quickstart/google-ontap-with-onelogin How does one integrate it to complete the login? -
Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead
I have 3 models: Order, orderTimelocation and timeInterval. Order has a relation one to many with orderTimelocation and this has a relation one to many with timeInterval: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation', null=True) class timeInterval(models.Model): start = models.DateTimeField() end = models.DateTimeField() order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE) I am using Writable nested serializers as the documentation suggests. class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order class orderTimelocationSerializer(serializers.ModelSerializer): time_interval = timeIntervalSerializer(many= True) class Meta: model = orderTimelocation fields = ('longitude', 'latitude', 'time_interval') def create(self, validated_data): time_intervals_data = validated_data.pop('time_interval') ordertimelocation = orderTimelocation.objects.create(**validated_data) for time_interval_data in time_intervals_data: orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data) return ordertimelocation class timeIntervalSerializer(serializers.ModelSerializer): class Meta: model = timeInterval fields = ['start', 'end'] The error is the following: Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line … -
unable to get data from django form
forms.py `class ScanForm(forms.Form): image = forms.ImageField() xml_file = forms.FileField() description = forms.CharField(max_length=500)` views.py `def home(request): form = ScanForm() if request.method == 'POST': form = ScanForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] xml_file = form.cleaned_data['xml_file'] description = form.cleaned_data['description'] return render(request,'app/home.html',{'form':form})` home.html `<form enctype="multipart/form-data" method = "POST"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Submit" class="btn btn-success btn-lg"/> </form>` only description is printed on the terminal values of image and xml_file i get is None or NoneType -
Loose Coupling in Django Templates
I am in a situation Really Confusing .. I Have Read alot about loose Coupling And Also i have read that Django is a loose coupled framework But in django tutorial and also in generic class based views like ListView The context which is going to send to template contains queryset or Model instances like : {'object' : Model.objects.get(id=2)} And use like this :{{ object.title }} Well title is a field in a Model and in this way the template system is going to know so much about model layer and with a change in model fields, the template must change to .. Well if django use this way in Its source code then im missing something... Can someone explain how this is not higg coupling ? And what kind of coding in django is loose coupling? -
create user remotely using built in django user model
I'm trying to figure out how to test the process of using the userviewset from the django quickstart guide to create a user account with postman. I'm assuming I have to make a post request to the "create" route, but postman says "this request doesn't have a body" so I have no idea how to send the email, username, and password. I feel like I'm missing something pretty major here, but I have no idea how to find out what it is. -
How to display an input like stackoverflow answer box
I'm working on a Django chat app and I want a <textarea> or <input type="text"> with the markdown format, like this own input, that I can format code, put images, etc. -
django docker postgres issue: password authentication failed
I might be the n person to ask this question but i am sorry because now i spent 5 hours on it and still has not solve it Everything was working great in my django project until i messed around with multi user setup...thats another now postgres is giving me a hard time to work while using docker-compose .env file POSTGRES_NAME=somedb POSTGRES_USER=someuser POSTGRES_PASSWORD=somepassword django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("POSTGRES_NAME"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': '5432', } } docker-compose version: "3.9" services: backend: build: ./backend container_name: backend stdin_open: true tty: true restart: "on-failure" env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - "backend_network" db: image: postgres container_name: db restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - "backend_network" networks: backend_network: driver: bridge volumes: postgres_data: when i spin up the containers with docker-compose -d --build and check the logs with docker-compose logs, here is what i see backend | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend | return func(*args, **kwargs) backend | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect backend | self.connection = self.get_new_connection(conn_params) backend | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend | … -
Getting Error im Django "Exception Value:name 'order_id' is not defined" whne query with a view to List Child records
Getting Error im Django "Exception Value:name 'order_id' is not defined" whne query with a view to List Child records I am making a custom View of a Cart that is Editable where I can still add/Update OrderItems. Problem is the View is showing all OrderItems from all Orders. No matter how I try to Filter the results I get an Error "name "xxxxxxx" is not Defined The View works but list all Child Records I cant format this in view def get_context_data(self, **kwargs): # used to send additional context context = super().get_context_data(**kwargs) context["title"] = 'Edit Sizing' context["savebtn"] = 'Update Sizing' context["delbtn"] = 'Delete Sizing' # data = cartData(request) # cartItems = data['cartItems'] **items = OrderItem.objects.filter(orderitem__in=order_id)** # items = OrderItem.objects.filter(order=order) orders = Order.objects.filter(orderitem__in=items) # items = OrderItem.objects.all() context = {'items': items, 'orders': orders} return context Error in Browser NameError at /sizing/1/edit name 'order_id' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/sizing/1/edit Django Version: 3.2.4 Exception Type: NameError Exception Value: name 'order_id' is not defined Exception Location: C:\Users\LS\source\repos\esstools17\esstools\store\views.py, line 58, in get_context_data Python Executable: C:\Users\LS\source\repos\esstools17\env\Scripts\python.exe Python Version: 3.9.3 Python Path: ['C:\\Users\\LS\\source\\repos\\esstools17\\esstools', 'c:\\python39\\python39.zip', 'c:\\python39\\DLLs', 'c:\\python39\\lib', 'c:\\python39', 'C:\\Users\\LS\\source\\repos\\esstools17\\env', 'C:\\Users\\LS\\source\\repos\\esstools17\\env\\lib\\site-packages'] Server time: Thu, 22 Jul 2021 23:41:03 +0000 Traceback Switch to copy-and-paste view Models.py … -
Django and Powershell
:) I'm having a problem with two things: I'm unable to run PowerShell script from views.py I cannot find a way to send JSON data via POST First problem I've written a dummy python script that's going to call PowerShell script. getaduser.py import subprocess import json def run_powershell_script(ID, Domain): args = ['-SAMACCOUNTNAME', ID, '-DOMAIN', Domain] result = subprocess.check_output([ 'powershell.exe', '.\\getaduser.ps1', *args ]) return json.loads(result) getaduser.ps1 Param( [Parameter(Mandatory)][string]$SAMACCOUNTNAME, [Parameter(Mandatory)][string]$DOMAIN ) $result = [PSCustomObject]@{ samAccountName = $SAMACCOUNTNAME domain = $DOMAIN } return $result | ConvertTo-Json PowerShell script is now only returning what I passed to it, but in the future, it'll take data from Active Directory, also I don't think it's important now. getaduser.py and getaduser.ps1 are working just fine together when I use them off Django. Example of what I'm getting after running the getaduser.py: Path/getaduser.py {'samAccountName': 'exampleID', 'domain': 'exampleDomain'} But when I try to call the script from the views.py I'm getting an error message saying: Command '['powershell.exe', '.\\getaduser.ps1', '-SAMACCOUNTNAME', 'exampleID', '-DOMAIN', 'exampleDomain']' returned non-zero exit status 1. From what I already understood it might mean that the PowerShell script has not been executed properly, but I'm at loss since it's working without Django. And here's how I call it: … -
how to concatinate a date into a string Django
I'm quite new to DRF so sorry in advance. What I want to do is create a function to concatinate the letter "P", the ID value of another model and the year from a submitted date all into one to make a name. Now the value that I want to add this to is the value on the counter model. Any ideas would be appreciated. Here's the models class Order(models.Model): code = models.IntegerField code_year = models.IntegerField date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) def __str__(self): return str(self.code) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField class Counter(models.Model): name = models.CharField(max_length=10) value = models.IntegerField -
How to filter MongoDB collection from Django to find matching string in a list of strings?
Let's assume MongoDB collections has the following document: { _id: ObjectId('asdasd232344'), article: 'some name', type: 'latest', tags: ['books', 'cars', 'code'] },{ _id: ObjectId('asdasd232345'), article: 'some name', type: 'latest', tags: ['books', 'food'] },... Assuming the model is named Story, I am trying to query the articles that have type latest and 'cars', or 'books' and 'cars' tags. Want to do this in a query instead of looping over the result afterward and filtering the ones that have desired tags in them. news = Story.objects(type='latest'). ???? maybe something like find($in: {'books', 'tags'}) I cannot find what I am looking for online since not sure what is this called or how to search it. Thanks, community! -
NoReverseMatch: Reverse for 'edit' with keyword arguments '{'title': ''}' not found
This is the extention of the same problem i asked about in a previous question. The problem i'm having here now is that after fixing the problem with the trans views function and expecting the program to run without problems, i get the following error NoReverseMatch at /wiki/Python/edit Reverse for 'edit' with keyword arguments '{'title': ''}' not found. Which i can't for the life of me understand considering that i AM passing the title argument in the html and set up the edit views function and the urlpath in urls.py to expect the title argument. when i take a closer look at the traceback, it highlights this block of code from the edit views function. return render(request, "encyclopedia/edit.html", { "form": EntryForm(initial={ "title": title, "content": entry }) }) but i don't understand what the problem is here? this is the final part of the project i'm working on so i'll be very grateful for any and all help. below is the relevant code. HTML entry.html <!-- The edit button in the entry's page --> <form action="{% url 'wiki:trans' %}" method="POST"> {% csrf_token %} <input type=hidden value={{title}} name="title"> <input type=submit value="Edit"> </form> edit.html <!-- the edit page --> {% block body %} … -
Django Signals how to create notifications objects for sender and receiver both?
I am building an notification system for send notifications blog subscribers and bog author. I am using Django post_save signals which creating notifications objects. Is it possible to create two separate notification objects for my BlogCommnet model one for sender(blog commenter. Who commented in blog post) and another for receiver(author. Who created blog post). here is my code: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fields #here signals starting def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() post_save.connect(BlogComment.user_comment, sender=BlogComment) Right now it's creating only one notifications objects. see the picture: I want it will create two objects one for sender and another for receiver. is it possible ???