Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble Setting Up React and running npm run dev
I am getting the error Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation. If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing. when I go to run npm run dev. I am very new to React and have limited knowledge; I am currently following a tutorial and got lost setting up the React. In my 'presets' section, I already have @babel/preset-react in there, so I don't know why the error is occurring or how to fix it. Here is my babel.config.JSON: { "presets": [ [ "@babel/preset-env", { "targets": { "node": "10" } } ], "@babel/preset-react" ], "plugins": ["@babel/plugin-proposal-class-properties"] } -
Voice chat integration with Django Channels
I'm developing django + angular app, that's use django channels and need voice chat functional. I found simple realization of the voice chat with socket, threading and pyaudio packages. Server example: class Server: PORT = 6655 def __init__(self): self.ip = socket.gethostbyname(socket.gethostname()) while True: try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.ip, self.PORT)) break except socket.error: print("Couldn't bind to that port") self.connections = [] self.accept_connections() def accept_connections(self): self.socket.listen(100) print('Running on IP: ' + self.ip) print('Running on port: ' + str(self.PORT)) while True: connection, addr = self.socket.accept() self.connections.append(connection) threading.Thread(target=self.handle_client, args=(connection, addr)).start() def broadcast(self, sock, data): for client in self.connections: if client != self.socket and client != sock: try: client.send(data) except: pass def handle_client(self, connection, addr): while True: try: data = connection.recv(1024) self.broadcast(connection, data) except socket.error: connection.close() And have some questions about it: Can I realize this solution on django channels? Can I use such threads in django channels, is thread safe? -
Is PyCharm Community Edition doesn't have Database Tool?
I'm using pycharm 2020.3 community edition. but id doesn't showing database tool. it means this edition comes without that option? or any action we have to do for this? *Note: some people saying add plugin data base browser. but that is not built in. I want database tool. -
Django : 'collections.OrderedDict' object is not callable
I am trying to make a post request to module User which inherits AbstractUser using serializer UserSerializer, but I'm getting the error 'collections.OrderedDict' object is not callable on-field "PhoneNumber". Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model= User fields="__all__" def save(self, **kwargs): user = User( username = self.validated_data.get('username'), first_name =self.validated_data.get('first_name'), last_name = self.validated_data.get('last_name'), email=self.validated_data.get('email'), Address=self.validated_data.get('Address'), PhoneNumber=self.validated_data('PhoneNumber')) user.save() User Model: class User(AbstractUser): Address=models.TextField(blank=True,null=True) PhoneNumber = models.CharField(max_length=15, blank=True,verbose_name='PhoneNumber') cdNumber = models.CharField(max_length=16, blank=True,verbose_name='cdNumber') cdDate=models.DateField(blank=True,null=True,verbose_name='cdDate') cdName = models.CharField(max_length=16, blank=True,verbose_name='cdName') def __str__(self): return self.first_name+" "+self.last_name -
Cant pinpoint the cause of a Module Not Found error
Here is the traceback for a project called zealplaza. (venv) mike@system76-pc:~/projects/zealplaza$ python3 manage.py migrate Traceback (most recent call last): File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'zealmarkets' … -
What is the best way to get parent model data in serializer?
I have two models: Company(DateTimeModel): title = models.CharField(max_length=100) ... Contract(DataTimeModel): ... company = models.ForeignKey(Company, on_delete=models.CASCADE) When I want to create a contract I want to send only company id For example my input: { "some_fields": "foo", ..., "company": 1 } But in output I want to get id and title { "id": 1, ..., "company": { "id": 1, "title": "company title", } } This is my serializer: class ContractSerializer(serializers.ModelSerializer): company_id = serializers.IntegerField(write_only=True) company = CompanyRelatedSerializer(read_only=True) But I should create validation for company_id manualy and it is two different fields. I guess there is a better implementation than mine. How do it better? -
DJANGO Error: UnboundLocalError at local variable 'cart_obj' referenced before assignment
I have limited experience in coding, but I like django and python and I am trying to learn by completing a udemy course called "Build a DJANGO ecommerce web application. It appears the course has some issues, but I have already invested several hours and want to get to the end! Please help !!! I am having problems with the cart build. When I navigate to localhost/cart/cart I receive the above error. I have not posted the settings.py as I think thhe error is limited to the views and models configuration. The relevant information is below: traceback Internal Server Error: /cart/cart/ Traceback (most recent call last): File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\views.py", line 14, in cart_home cart_obj, new_obj = cart.objects.new_or_get(request) File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\models.py", line 22, in new_or_get return cart_obj, new_obj UnboundLocalError: local variable 'cart_obj' referenced before assignment [28/Mar/2021 10:38:40] "GET /cart/cart/ HTTP/1.1" 500 72446 cart/models.py from django.db import models from django.conf import settings from store.models import product, customer from django.contrib.auth.models import User from django.db.models.signals import pre_save, post_save, m2m_changed # Create your models here. User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", default= … -
I need help integrating stripe payments with raspberry pi
I am currently working on a program from a raspberry pi using stripe to send payments after a customer has scanned their card. The card will be read by the raspberry pi using NFC, so I need some way to send the debit/credit card data to the stripe API which can charge the card. I am getting my code from https://github.com/justdjango/django-stripe-tutorial. -
Django: The best / canonical way to preserve / access form fields' 'old' values (before they are updated)
Use cases: I want to programmatically access the value of a form field prior to the update, for one of the following scenarios (just 2 examples, to illustrate the case) a) I want to detect if the original value of a field has been changed in the form, before it's saved in the database b) I want to detect / prevent changing the field value in a very specific way, e.g. if a field value is set to "Approved", it should never change back to "Pending approval", etc. Constraint: Ideally, I would prefer not to do another trip to the database (to check for the old value), for performance reasons. -
Filtro en django
estoy haciendo mi función para filtrar con django_filters este es mi código: class Redaccion(models.Model): titulo = models.CharField(max_length=100) texto = models.TextField() fecha = models.DateField(default=timezone.now) categoria = models.CharField(max_length=255, default='coding') autor = models.ForeignKey(User, on_delete=models.CASCADE) nombre = models.CharField(max_length=255) en filters.py import django_filters from .models import Redaccion class RedaccionFiltro(django_filters.filterset): class Meta: model = Redaccion fields = [ 'categoria', 'fecha', ] y en views es def FiltroViews(request): context = {} filtro_redaccion = RedaccionFiltro( request.GET, queryset = Redaccion.objects.all() ) context['filtro_redaccion'] = filtro_redaccion return render(request ,'categorias/listar_noticias.html', context=context) el problema es que cuando quiero hacer una makemigrations me sale este error File "C:\Users\Rosmari\Desktop\Proyectoparaelmartes\TrabajoFinal\apps\categorias\filters.py", line 5, in class RedacionFiltro(django_filters.filterset): TypeError: module() takes at most 2 arguments (3 given) no estoy entendiendo, estoy siguiendo un tutorial y en este sale bien el código sin problemas gracias desde ya. -
Django how to hide ID from URL
I'm using Django. I want to hide Id from URL. url: path('<int:news_pk>/', views.newsDetailView, name='detail'), View: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) return render(request, "news/pages/index-inner.html", { 'news': news, }) Model: class News(models.Model): title = models.CharField(max_length=100, verbose_name='title') verbose_name='snippet') content = RichTextUploadingField(blank=True, null=True, verbose_name='content') class Meta: verbose_name = "news" verbose_name_plural = verbose_name def __str__(self): return self.title Any friend can help? -
Create a One to One Queryset In Django
I am having trouble creating a queryset by joining two one to one fields. Does anyone know how to solve this problem? I am trying this example here but not getting it to work. Django one to one relation queryset class Category_Driving (models.Model): ACCEPTABLE_UNACCEPTABLE = ( ('acceptable', 'ACCEPTABLE'), ('unacceptable', 'UNACCEPTABLE'), ) bbso_record_id = models.OneToOneField(BBSO_Records, on_delete=models.CASCADE, primary_key=True) vehicle_condition = models.CharField(max_length=12, blank=True, choices=ACCEPTABLE_UNACCEPTABLE, verbose_name="Vehicle in Safe Condition") seat_belt_secured = models.CharField(max_length=12, blank=True, choices=ACCEPTABLE_UNACCEPTABLE) def __str__(self): return self.vehicle_condition class Meta: verbose_name_plural = "CategoryDriving" class BBSO_Records(models.Model): severityLevel = ( ('Level 1', 'Level 1'), ('Level 2', 'Level 2'), ('Level 3', 'Level 3'), ) severity_level = models.CharField(max_length=7, default= "Level 3" , choices=severityLevel) date_recorded = models.DateField() location_details = models.CharField(max_length=50, help_text='e.g. In the kitchen on the 4th floor.', blank=True) # I am trying this code in my view but it is not working. queryset = Category_Driving.objects.filter(id=id).values('vehicle_condition').\ annotate(record_count=Count('vehicle_condition')).order_by('vehicle_condition') This is the error message I am getting: Cannot resolve keyword 'id' into field. Choices are: bbso_record_id, bbso_record_id_id, distracted, inspection, seat_belt_secured, speed, spotter, vehicle_condition Any help will be greatly appreciated. note: I did not show all the fields in my model in the example given. I cut them down not to show all the code. -
Field 'id' expected a number but got 'search'
I got stuck for a couple of hours already, I'm not able to find what could be the mistake. When I click search btn on the form I'm getting the following error. (ValueError at /vehicles/search Field 'id' expected a number but got 'search'.) Why this field is expecting a number when should redirect to 'search'. Any suggestions or help is appreciated! Thank you! view:: def vehicle_detail(request, pk): ad_vehicle = AdVehicle.objects.get(pk=pk) comment_form = CommentVehicleForm() if request.method == 'POST': comment_form = CommentVehicleForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.ad_vehicle = ad_vehicle comment.save() return HttpResponseRedirect(reverse('detail_view_ad_vehicle', kwargs={'pk':pk})) return render(request, 'vehicles/single-vehicle.html', context={'ad_vehicle':ad_vehicle, 'comment_form':comment_form}) def search(request): vehicles = AdVehicle.objects.order_by('-publish_date') model_search = AdVehicle.objects.values_list('model', flat = True).distinct() brand_search = AdVehicle.objects.values_list('brand', flat = True).distinct() year_search = AdVehicle.objects.values_list('year', flat = True).distinct() price_search = AdVehicle.objects.values_list('price', flat=True).distinct() # keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: vehicles = vehicles.filter(description__icontains=keywords) if 'model' in request.GET: model = request.GET['model'] if model: vehicles = vehicles.filter(model__iexact=model) if 'transmission' in request.GET: transmission = request.GET['transmission'] if transmission: vehicles = vehicles.filter(transmission__iexact = transmission) if 'year' in request.GET: year = request.GET['year'] if year: vehicles = vehicles.filter(year__iexact=year) if 'price' in request.GET: price = request.GET['price'] if price: vehicles = vehicles.filter(price__lte = price) context = { 'vehicles':vehicles, 'model_search' : model_search, … -
Django: safely store auth token to be share along all django users
I build a Django site wheres requires all users to be authenticated using the standard authentication of Django. In some of the pages django will be doing Request to a third party site which also require authentication. This third party site is not a django site and only has one user, this means that all django users will be sharing that 1 user to retrieve the information. The authentication to this third party site, is with a JWT Flow. We first retrieve an auth token and then we send this token to the desire end point adding the Django user ID, to retrieve that user ID information. I want to avoid all users in django doing multiple request to get the same auth token as this should be the same for all of them. Is there a way in Django to storage this auth Token safely? and perhaps if a user fail due to expiry token, django retrieves a new one and keep it safely store for all users to use? -
Django Rest Framework: 'RelatedManager' object has no attribute 'body' error when using nested serializer
With Django DRF, I am trying to display the comments for a particular post in a blog using a nested serializer. I have run into the following error: 'RelatedManager' object has no attribute 'body' Here is my code: comment model: class Comment(models.Model): #adapted from https://blog.logrocket.com/use-django-rest-framework-to-build-a-blog/ created = models.DateTimeField(auto_now_add=True) body = models.TextField(blank=False) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments', on_delete=models.CASCADE) post = models.ForeignKey('Posts', related_name='comments', on_delete=models.CASCADE) @property def time_left(self): return self.post.time_left Post model: class Posts(models.Model): title = models.CharField(max_length=100) topic = MultiSelectField(choices=TOPIC_CHOICES) creation_timestamp = models.DateTimeField(auto_now_add=True) expiration_timestamp = models.DateTimeField(default=expiration) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #related_name='posts' likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="likes",blank=True) dislikes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="dislikes",blank=True) @property def is_expired(self): #taken from https://stackoverflow.com/questions/41505243/how-to-automatically-change-model-fields-in-django if now() > self.expiration_timestamp: return True return False @property def time_left(self): return self.expiration_timestamp - now() serializers.py: class CommentSerializer(serializers.ModelSerializer): time_left = serializers.ReadOnlyField() class Meta: model = Comment fields = ('created', 'body', 'user_id', 'post','time_left') class PostsSerializer(serializers.ModelSerializer): is_expired = serializers.ReadOnlyField() time_left = serializers.ReadOnlyField() comments = CommentSerializer(source='comments.body',) ########## THIS IS THE PROBLEMATIC LINE ####### class Meta: #make sure that the relevant fields are read only model = Posts fields = ('comments','title','topic','creation_timestamp','expiration_timestamp','body','user_id','likes','dislikes','is_expired','time_left') I believe the problematic line is the following one from serializers.py: comments = CommentSerializer(source='comments.body',) -
I need to customize all requests to have a response for every error can occur besides Making Event object mandatory in ingest event request
example :- GET/admin/clients/reset/{apikey}/{client_name} in this request, we need 2 response if adding apikey wrong or client name is wrong separately with 2 different responses POST/ingest/event { "sessionId": "string", "clientApiKey": "string", "category": "string", "action": "string", "interactive": "boolean", "label": "string", "amount": "double", "eventData": Object } response for each variable and the rest as above -Make Event object mandatory in the ingest event request POST/ingest/event { "sessionId": "string", "clientApiKey": "string", "category": "string", "action": "string", "interactive": "boolean", "label": "string", "amount": "double", "eventData": Object } -
Django reset oneToOneField on Custom User Model
I have a custom User model, which has a one-to-one relationship with a UserProfile model. I want to create a new UserProfile object and switch the existing related UserProfile object with the newly created one. This is essentially what I am trying to do: **views.py** def perform_create(self, serializer): club = serializer.save(created_by=self.request.user) user = self.request.user user.current_userprofile = None user.save() UserProfile.objects.create( user_account=self.request.user, club=club, current_active_userprofile=self.request.user, is_admin=True ) **models.py** class UserProfile(models.Model): user_account = models.ForeignKey(UserAccount, related_name='userprofiles', on_delete=models.CASCADE) club = models.ForeignKey(Club, related_name='club_userprofiles', on_delete=models.CASCADE) current_active_userprofile = models.OneToOneField(UserAccount, related_name='current_userprofile', on_delete=models.SET_NULL, blank=True, null=True) is_admin = models.BooleanField(default=False) However, the perform_create method triggers an integrity error: UNIQUE constraint failed: userprofile_userprofile.current_active_userprofile_id How do I reset the field to NULL so that I can connect it to the newly created object? -
NameError: name *model* is not defined; ManyToManyField/ForeignKey
Here is a relationship I'm aiming for in terms of a User, Question, Bookmark relationship; Bookmark being an intermediary table: A user can bookmark many Questions (topic pages) A Question (topic page) can be bookmarked by several users The keyword here being bookmark(ed), I have created a Bookmark model to show this relationship. However there's a problem of trying to make migrations due to a NameError being raised. Depending where they are defined in the script it's raising either: NameError: name 'Question' is not defined NameError: name 'Bookmark' is not defined How can I get past this error in order to push the Bookmark into the migrations directory with its ForeignKey references? class Question(models.Model): title = models.CharField(unique=True, max_length=40) body = models.TextField() created = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True ) views = models.ManyToManyField( View, related_name="+" ) tags = models.ManyToManyField( Tag, related_name="questions" ) bookmarks = models.ManyToManyField( Bookmark, related_name="+", ) def __str__(self): return self.title class Bookmark(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="+" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="bookmarks" ) -
Implement f-string like syntax, with Django SafeString support
I implemented a fun little method h() which is Django's format_html() on steroids: It works fine, except the last assert fails, and I am unsure how to implement it: def test_h(): amp = '&' assert h('{amp}') == '&amp;' foo = format_html('<span>{bar}</span>', bar='&') assert h('<div>{foo}</div>') == '<div><span>&amp;</span></div>' assert h('{') == '{' assert h('') == '' name='foo' assert h('{name.upper()}') == 'FOO' assert h('{{}}') == '{}' # <--------------- how to get this working? Implementation: def h(html): """ Django's format_html() on steroids """ def replacer(match): call_frame = sys._getframe(3) return conditional_escape( eval(match.group(1), call_frame.f_globals, call_frame.f_locals)) return mark_safe(re.sub(r'{(.*?)}', replacer, html)) -
How create invalid email in python
I tried to find a function for my django project that creates invalid email, but I didn't find any. I found only functions that create valid emails and validators for them like this: import random import string DOMAINS = ["hotmail.com", "gmail.com", "aol.com", "mail.com", "yahoo.com", "mail.ru"] letters = string.ascii_letters def get_one_random_domain(): return random.choice(DOMAINS) def get_one_random_name(length=7): return ''.join(random.choice(letters) for i in range(length)) def get_random_email(): return get_one_random_name(letters) + '@' + get_one_random_domain() Please advise sites with similar information or links to ready-made solutions -
Nav item links not properly linking to new page
I am using Django to do this, I have a nav list with tabs and I want each tab to go to a new page and new corresponding view, the new pages will all have the same nav list, just with a different active tab. For some reason when I click on the tab, it won't change the page, I'm not sure what I'm doing wrong. Here is my code in the main page with the tabs: <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#summary">Summary</a> </li> <li class="nav-item"> <a class="nav-link external" data-toggle="tab" href="{% url 'financials:description' ticker %}">Description</a> </li> </ul> I know the link is correct, because I have tested it outside the nav links and it works fine. When I hover over the tab I see the proper URL at the bottom of page, but when I click nothing happens. I'm not sure if this has to do with javascript (I don't understand javascript yet and got the website template online). Thanks, any help greatly appreciated! -
Django Inline Formset That Allows for Creation of Parent and First Child Object on same page
Looking for examples how to build an inline formset that has the parent and one child model associated. End goal: one page with one form that creates the parent and first child object when the submit button is clicked. I'm struggling to find examples and/or literature explaining how to do this. This is my first complex django project. Thank you. -
Can't send GET request to Django via Postman
I perform request http://167.71.57.114/api/users/list-exercises And receive error User matching query does not exist. How can I fix the error? Found out that reason of the error is that request didn't have any data But you can see that I am sendig the "user_id" My code class WorkoutUserProgramListViewAPI(GenericAPIView): permission_classes = (IsAuthenticated,) serializer_class = WorkoutUserProgramListSerializer def get(self, request): response = {} user = request.data.get("user_id") # user is None user = User.objects.get(pk=user) # Error User matching query does not exist. -
Convenient and simple solution to receive and answer emails in a small Django app
I am developing a Django app which uses Email in some of its components (but not at its core). I am looking for a simple and cheap solution that satisfies the following requirements: Only the custom domain of the app is used (no username@gmail address) Django can send emails programmatically (error reporting, user data from forms) The admin can receive and and answer mails through an email client of their choice Solutions I have considered so far: Using my hosting provider: They understandably don't support custom email accounts for VPS customers Amazon SES: would work for sending email, but received emails would land in a S3 bucket; it is unclear to me how to connect this to an email client Sendgrid: would work for sending email, but the only way to handle inbound mail is to forward it as HTTP POST request to a view Django extensions to read and send email through the admin interface: I can't use my email client Google Workspace: seems like this could work. My issue is that it includes a lot of functionality I don't really need. Does anyone have experience with this? All I really need is to alias a standard email account … -
Approve application [closed]
Hello Django Professionals I am new to Django and I would like to add an approve application function to my project here is my views: def view_application(request, application_id): if request.user.userprofile.is_client: application = get_object_or_404(Application, pk=application_id ,job__created_by=request.user) else: application = get_object_or_404(Application, pk=application_id, created_by=request.user) if request.method == 'POST': content = request.POST.get('content') if content: conversationmessage = ConversationMessage.objects.create(application=application, content=content, created_by=request.user) create_notification(request,application.created_by, 'message',extra_id=application.id) return redirect('view_application',application_id=application_id) return render(request, 'view_application.html', {'application':application})