Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement RBAC(role-based-access-control ) in distributed microservices architecture?
I created authentication server and resource server. I used django oauth toolkit library for the implementation. The authorization works fine. https://django-oauth-toolkit.readthedocs.io/en/latest/ I would like to implement RBAC(role-based-access-control) in the resource server. I don't find any reference for that. Can someone guide me to implement the RBAC(role-based-access-control) in distributed microservices architecture? -
Unable to get output in server localhost by returing using loop in django python?
for k in range(len(data[0])): fi = data[0][k] return render(request, "a.html", {'result': fi}) i return by sing render function in a loop but get no output. when i return same thing outside the for loop than it gives me correct output. is it any possilbe way to get my output using loop? -
Django: Prevent form from resetting when a form is not valid
I am trying to prevent the form from resetting when there is an invalid input, but when there is an invalid input my whole form is resetting and I don't understand why. This is basically a registration form and the point is to not have the form reset when form.is_valid() is false. Also, if you could help with displaying messages. How do I incorporate a strength password bar under the password field. <center><div class= 'form-container'> <h1 style="font-weight:normal;font-family: 'Google Sans','Noto Sans Myanmar UI',arial,sans-serif;position: relative;top: 20px;">Sign-up</h1> <form method="post" id = "register-inputs" action = {% url 'register' %}> {% csrf_token %} <div> <div class="user-register"> <input type = 'text' name = 'first_name' required> <span class="highlight"></span> <span class="bar"></span> <label>First name</label> </div> <div class="user-register"> <input type = 'text' name = 'last_name' required> <span class="highlight"></span> <span class="bar"></span> <label>Last name</label> </div> <div class="user-register"> <input type = 'text' name = 'email' required> <span class="highlight"></span> <span class="bar"></span> <label>Email</label> </div> <div class="user-register"> <input type = 'text' name = 'username' required> <span class="highlight"></span> <span class="bar"></span> <label>Username</label> </div> <div class="user-register"> <input type = 'password' name="password1" required> <span class="highlight"></span> <span class="bar"></span> <label>Password</label> </div> <div class="user-register"> <input type = 'password' name="password2" required> <span class="highlight"></span> <span class="bar"></span> <label>Confirm Password</label> </div> <input class="btn btn-primary" type="submit" value="Sign up!"> … -
How to implement file upload in django with TinyMCE?
I'm quite new to django and I wanted to make my text editor to my Django admin page accept file upload and file browsing. I currently have the editor set up, however I'm not able to browse for files. image of my current file upload pop up (notice there's no browse button) I understand that there are documents on the official TinyMCE website (https://www.tiny.cloud/docs-4x/configure/file-image-upload/) regarding implementing file and image upload and file_picker and what not, but they're all provided in JavaScript instead of Python. How would I go about doing this using Python? If that process is too complicated, how would I implement the file upload to my django project if I'm using the default admin page that django provides? -
Problem in the button not working in django
I created articles blog but user can not create article with create button , my code in git hub: https://github.com/MohammadGhanbari1/firstBlog -
permission to users with few model instances
models.py How can i setup custom permission for users(who are my employees) to only view those dealer pages that admin assigns to them and can change those permission anytime. class Dealer(models.Model): name = models.CharField(max_length=200) mob_num = models.IntegerField(blank=True, null=True) address = models.TextField(blank=True) def __str__(self): return self.name class Ledger(models.Model): date = models.DateTimeField(auto_now_add=True) particulars = models.CharField(max_length=100,blank=True) debit = models.IntegerField(blank=True, default=0) credit = models.IntegerField(blank=True, default=0) paymode = models.CharField(max_length=10, choices=(('Cash','Cash'), ('Cheque','Cheque'),)) dr_cr = models.CharField(max_length=10, default='', choices=(('Dr','Dr'), ('Cr','Cr'),)) invoice = models.ImageField(upload_to=None, blank=True) dealer = models.ForeignKey(Dealer, null=True, on_delete=models.SET_NULL) balance = models.IntegerField(default=0) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name = 'home'), path('ledger/<int:pk>/', views.ledger, name = 'ledger'), path('dealer/<int:pk>/', views.dealer, name = 'dealer'), This picture shows that each dealer has his own ledger instances i want to restrict my users to only few of those dealer pages, and can customize that anytime, some help would really be appreciated. -
Handling Multiple Forms on the Same Page in Django without Django's default model form
I am trying to develop a webpage with two forms on the same page with Django. Anyone will able to fillup any single form and submit it, then that data will be saved in the database. Here I try to avoid Django's default model form and any type of js stuff also. My HTML: <!DOCTYPE html> <html> <head> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- animated css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/> <!-- font awsome css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- custom css link --> <link rel="stylesheet" type="text/css" href="#"> </head> <body> <div class="row m-0 bg-info"> <h2 class="mx-auto my-4">Multiple form in one page</h2> </div> <div style="height: 40px;"></div> <div class="container-fluid my-5"> <div class="row m-0 d-flex justify-content-center"> <div class="col-md-3"> <h2>Employee Profile</h2> <form class="#" method="POST" id="EmployeeProfile"> <div class="form-group"> <label>Ranks</label> <input type="text" class="form-control" name="ranks" placeholder="Enter ranks"> </div> <div class="form-group"> <label>salary</label> <input type="text" class="form-control" name="salary" placeholder="Enter salary"> </div> <div class="row d-flex justify-content-center"> <button type="submit" class="btn btn-primary m-2">Submit</button> </div> </form> </div> <div class="col-md-2"></div> <div class="col-md-3"> <h2>Inspector Profile</h2> <form class="#" method="POST" id="InspectorProfile"> <div class="form-group"> <label>Ranks</label> <input type="text" class="form-control" name="ranks" placeholder="Enter ranks"> </div> <div … -
WSGI Daemon doesn't recognize python 3.8 env path Django 3.1.4
WSGI Daemon doesn't recognize python 3.8 env path. This results in him not being able to load 'django' module which. The mod_wsgi was intialy installed with python3.6 so this might be the case. Inside the /usr/lib/apache2/modules/ there are two files concerning mod_wsgi: mod_wsgi.so mod_wsgi.so-3.6 From this I can assume that in order to run WSGIDaemon with python 3.8 I will have to create a mod_wsgi.so-3.8 How can i achieve this ? -
Django paginator issue
I am currently working on a django blog and I've coded a search bar where you type something and, if there's any post that contains what you've typed in the title, it should appear all the posts. This part is perfectly well-written. However, there's an error with the pagination. As you'll see in the views.py. The maximum num of posts per page is 3. However, you can see there's four. However, the paginator detects there should be another page for the fourth posts. Here's an image that shows that. Here's the views.py: class ElementSearchView(View): elements_list = Element.objects.all() def get(self, request, *args, **kwargs): paginator = Paginator(self.elements_list, 3) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) queryset = Element.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) ).distinct() context = { 'query': queryset, 'queryset': paginated_queryset, 'page_request_var': page_request_var, } return render(request, 'periodic/search_results_table.html', context) And here's the html template: The pagination is at the end of the template. {% load static %} <html> {% include 'periodic/head_search.html' %} <body> {% include 'periodic/header.html' %} <br> <br> <div class="container"> <div class="row"> <!-- Latest Posts --> <main class="posts-listing col-lg-8"> <div class="container"> <div class="row"> <!-- post … -
Using Django REST framework with TCP Server socket
I am developing a web api using the Django REST Framework. At the same time, I am receiving stream data from IoT devices as an HTTP Post message. In this, I use tcp socket server in python. When I try to use these two things together, Django REST Framework does not work for HTTP requests, only the TCP socket works. How can I run Django REST Framework and TCP socket together? TCP Server Socket code here: class RFIDServer(Thread): def __init__(self, address="", port=8000): super().__init__() self.gateways = dict() self.tag_list = {} self.rfidData = dict() self.rfidDataLocker = Lock() self.address=address self.port=port self.socket_setup=False self.setup_socket() def setup_socket(self): try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except: exit("Couldn't create a socket") try: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except: exit("Couldn't set socket options") try: self.sock.bind((self.address, self.port)) except: print("Couldn't bind socket to server address") self.socket_setup=True def listen(self): if self.socket_setup!=True: print("Socket hasn't been setup. Do that first!") return self.sock.listen(1) while True: c, addr = self.sock.accept() threading.Thread(target = self.listenToClient, args = (c,addr)).start() self.sock.close() def listenToClient(self, c, addr): print('Got connection from', addr) opt = { "received_from": "client request", "body_required": True, "normalize_newlines": True } while True: data = c.recv(8196).decode("utf-8") try: parsed_data = python_http_parser.parse(data, opt) print(parsed_data['body']) except: print("Parsed Errors") print(data) c.close() -
Error when trying to use through table for many to many relationships in Django models
from django.db import models class Category(models.Model) : name = models.CharField(max_length=128) def __str__(self) : return self.name class State(models.Model) : name = models.CharField(max_length=128) iso = models.CharField(max_length=2) def __str__(self) : return self.name class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=3000) justification = models.CharField(max_length=3000) longitude = models.DecimalField(max_digits=15, decimal_places=10) latitude = models.DecimalField(max_digits=15, decimal_places=10) area_hectares = models.DecimalField(max_digits=15, decimal_places=5) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self) : return self.name class Region(models.Model): name = models.CharField(max_length=128) sites = models.ManyToManyField(Site, through='Site_Region_Junction') def __str__(self) : return self.name class Site_Region_Junction: site = models.ForeignKey(Site, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) The above code is my models.py for an app called unesco inside a django project. One site can have many regions and one region can have many sites. I have tried implementing this manytomany relationship with the through table just in case I have to add more attributes to the junction table. But I get an error when I run python manage.py check. The errors shown are : SystemCheckError: System check identified some issues: ERRORS: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f9ba5dee950>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f9ba5dee950> contains a lazy reference to unesco.site_region_junction, but app 'unesco' doesn't provide model 'site_region_junction'. unesco.Region.sites: (fields.E331) Field specifies a many-to-many relation through model 'Site_Region_Junction', which … -
1048, "Column 'last_name' cannot be null" Django AbstractUser
I'm trying to create a registration for each new account using the UserCreationForm in CreateView class-base view generics from my customize auth model using AbstractUser but everytime submit the form it gives me this error: 1048, "Column 'last_name' cannot be null" But I already fill in the last_name input here is my views for creating account: class AccountCreateView(LoginRequiredMixin, CreateView): template_name = 'components/crud/form.html' form_class = AccountForm def get_context_data(self, **kwargs): kwargs['context_title'] = 'New Account' kwargs['context_icon'] = '<em class="fa fa-plus"></em>' kwargs['context_button_title'] = 'Create Account' return super().get_context_data(**kwargs) def form_valid(self, form): print(self.request.POST.get('last_name')) try: self.object = form.save() messages.success(self.request, '<em class="fa fa-check"></em> Account created!') except IntegrityError as e: messages.error(self.request, f'<em class="fa fa-exclamation"></em> {e}') return self.form_invalid(form) return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_success_url(self): return reverse_lazy('apps:newaccount') Here is the form: class AccountForm(UserCreationForm): def clean_first_name(self): data = self.cleaned_data.get('first_name') if data == '': raise forms.ValidationError(_('What\'s your name?')) return data def clean_last_name(self): data = self.cleaned_data.get('last_name') if data == '': raise forms.ValidationError(_('What\'s your last name?')) def clean_email(self): data = self.cleaned_data.get('email') if data == '': raise forms.ValidationError(_('What\'s was the email address for this account?')) return data def clean_username(self): data = self.cleaned_data.get('username') if data == '': raise forms.ValidationError(_('Provide your username.')) return data def __init__(self, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.pop('autofocus', None) self.fields['first_name'].widget.attrs.update({ 'autofocus': … -
How to improve automated (every 3 sec) calls in celery-beat, celery-worker with Redis?
I use celery-beat, worker, and Redis as a broker to schedule tasks and call a specific function in the background. The interval for the call is 3 seconds, and I may have multiple calls every 3 seconds. def theFunction(arg1, arg2): obj = Model.objects.get(id=arg1) # call to a Modbus server result = Modbus.call(ip=obj.ip, obj.port) # just an example Data.objects.create(value=result) I have set from the Django administration with celery-beat-schedule, all the tasks to call this function with a different id. I use supervisor to automate the commands separately: celery -A project worker --log-level=info celery -A project beat --log-level=info The server is 16GB of RAM, when Redis is running it consumes up to 14GB of the RAM and the server becomes slow. When I use celery purge to kill all tasks, I sometimes see more than 1 million tasks in the queue. How to improve that, to have a result every 3 seconds to display live data in a graph. In case there is another technology that I can use, let me know. -
directory issue using aws s3 bucket as media and static files storage for my django webapp
I am just trying to add my django webapp media and static files to aws s3 bucket. All the things are working fine but the directory tree changed.how do I upload static files to s3 bucket's static/ directory. like ├───media │ └───profile_pics ├───static │ ├───css │ └───img my settings.py file settings are STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_S3_PATH = 'media/' DEFAULT_S3_PATH = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' my current folder structure in s3 bucket how do I get like this project structure in aws s3 bucket -
Check if user is logged in or not django by username
in django login, we can type if request.user.is_authenticated to check if the user is logged in... but if we want to check the login status of a particular user by entering the username... eg: #Python def checkLoginStatus(username): #do some checks here.... return True or False -
Django models and managers circular import error
so In my project I have two directories: managers and models. here's my code: how I've imported objects around. I also use objects as typehints, for example: @classmethod def get_overwrite_objects(cls, parent_object: DataSheetsCluster): return parent_object.roles models/data_sheets.py from django.db import models from django import dispatch from api_backend.managers import (FieldDataManager, RolesManager) ... managers/positions.py from django.db import (models, transaction) from api_backend.models import (Role, DataSheetsCluster, DataSheet, DataSheetField, DataSheetsCategory) ... I need these models, however I cannot import them due to django's circular import error. File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\__init__.py", line 4, in <module> from .positions import (PositionalManager, RolesPositionManager, DataSheetFieldPositionManager, File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\positions.py", line 2, in <module> from api_backend.models import (Role, DataSheetsCluster, DataSheet, DataSheetField, DataSheetsCategory) ImportError: cannot import name 'Role' from partially initialized module 'api_backend.models' (most likely due to a circular import) (C:\Users\iyapp\OneDr ive\Desktop\python projects\DataSheet-ledger\api_backend\models\__init__.py) Is there a way around this? please help me! thanks a lot! -
CRITICAL WORKER TIMEOUT Error on gunicorn for Dockerized Django Application while Calling from Angular Application as Client on Nginx
Docker File Command: CMD gunicorn app.wsgi:application --bind :8000 --workers 3 --timeout 120 --keep-alive 120 --threads 3 --worker-class gthread Stil its giving me same Error while calling an API which usually takes more than 30 secs because I'm running Objects.all() Query set to retrieve data from Database. -
Rendering markdown inside of <textarea> adds newline
I am implementing a Wikipedia-like webapp with Django. Data for the different entries is stored in Markdown files on the server. I use markdown2 for the conversions. Everything works just fine but I run into a problem when I try to edit an existing entry. The server serves "edit.html" to the client, passing a django form populated with the existing data. views.py class EditPageForm(forms.Form): title = forms.CharField(widget=forms.HiddenInput, label="title") content = forms.CharField(widget=forms.Textarea, label="content" def edit(request): if request.method == "POST": form = SearchForm(request.POST) ## a form with only a "title" input if form.is_valid(): title = form.cleaned_data["title"] content = util.get_entry(title) ## read the existing file.md form = EditPageForm(initial={ "title": title, "content": content }) return render(request, "encyclopedia/edit.html", { "title": title, "form": form }) edit.html <h1>Edit content for "{{ title }}"</h1> <form action="{% url 'save' %}" method="post"> {% csrf_token %} {{ form }} ## undesired newlines added here <input type="submit" value="Save"> </form> When the browser renders the textarea which includes the data to be edited, newlines are inserted without my consent. This behaviour loops everytime I edit a text so that more and more newlines are added. I don't really understand what is going on. Does anyone have an idea? -
Use modern GET parameters with DRF Router
The goal is to accept GET parameters after the question mark, for example api/items?name=apple?starting=10_10_2020 Strange but simple router path('api/items) is not working Should I add something? Thank you -
I got Google SMTPAuthenticationError when I send email via django with NON-gmail smtp server, even though I don't use smtp.gmail.com
I'm running a website made with django. This website has a contact form, and when you submit, you and administrator will receive an email. message = render_to_string('email/contact_us_message.txt', context) send_async_mail.delay(_('subject'), message, settings.DEFAULT_FROM_EMAIL, [contact.email]) message_for_admin = render_to_string('email/contact_us_message_for_admin.txt', context) send_async_mail.delay(_('subject'), message_for_admin, settings.DEFAULT_FROM_EMAIL, [settings.ADMIN_EMAIL]) I used to subscribe to gsuite and use that smtp server. There was no problem sending and receiving emails. I decided to use another email hosting service two days ago, so I modified my dns record, canceled gsuite and deleted my account. The new email hosting service worked fine in the local environment. However, in production, email can't be sent sometimes. When I check the task results of celery results, it says 535, "b'5.7.8 Username and Password not accepted." I understand that this error message is displayed when connecting to the google service. For example, the app password is not set. But I don't use smtp.gmail.com or services related to google anymore. EMAIL_URL=smtp+tls://no-reply@mydomain.com:password@new-smtp-server.com:587 so I don't understand why I get this error message. Since I changed the dns record and it's been a little while, do I get this error related smtp.gmail.com? If I wait and the dns cache will be updated, will the error disappear? -
django common templates for apps with variables
I want to make project-wide templates, but with app variables and app base subtemplates: /home/project/ templates/document.html app1/templates/app1/base.html app2/templates/app2/base.html And app1/views.py: def page1(request): document = get_document('title',app_email='test@example.com') context = { 'document' : document, 'app_title_header' : document.header } return render(request,'document.html', context) templates/document.html {% extends app_name|add:'/base.html' %} {% load static %} {% block content %} {% autoescape off %} {{ document.body }} {% endautoescape %} {% endblock %} (app_name is set by context_processors.py registered in settings.py) def appname(request): return {'app_name': request.host.name, 'app_base' : '{}/base.html'.format(request.host.name) } app1/templates/app1/base.html (almost identical like app2) {% load static app1 %} <--- difference with app2 <!doctype html> <html lang="pl"> <head> <meta charset="utf-8"> {% block head %} {% endblock %} <title>{% app_title %} - {{ app_title_header }}</title> {% include "app1/google.html" %} </head> app1/templates/app1/google.html {% load app1 %} <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id={% g_tag %}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '{% g_tag %}'); </script> and now: render takes document.html from project/templates. First it extends app_name/base.html - so it is including google.html (Google Analytics ). And it works. But now I want to move google.html and fb.html to project templates, but theres unique G_TAG, so it has to be … -
DJango React Not found
I am new to DJango and React. I created a DJango project in Pycharm and then a React app using npm create-react-app frontend. I added to folder "src" some JavaScript file and edited a created automaticly index.css. I built React app and then launched DJango server. Console printed: Not Found: /src/index.css Not Found: /src/seigaiha.js [25/Dec/2020 14:23:31] "GET /src/index.css HTTP/1.1" 404 2201 [25/Dec/2020 14:23:31] "GET /src/seigaiha.js HTTP/1.1" 404 2207 But .css fle is visibale on launched site. .js isn't. Order in folder: - frontend/ - - build/ - - - static/ - - - - css/ #here .css file after build has the same structure as index.css, so it buil - - - - js/ - - - - media/ - - node-modules/ - - public/ - - src/ - - - index.css - - - seigaiha.js In settings.py: 'DIRS': [ os.path.join(BASE_DIR / 'frontend/build') ] In public/index.html: ***some code*** <link rel="stylesheet" type="text/css" href="./src/index.css"> ***some code*** <div class="pattern"> <canvas id="canvas">Canvas not supported.</canvas> <script src="src/seigaiha.js"></script> </div> ***some code*** What I am doing wrong? Maybe I need to place this files in another folder? Or maybe a path is wrong? .js file name? When I have just .html, .css and js files (not in … -
Crash after transition from SQLite3 to PostgresSQL in my django progect
I've use SQLite3 in my django project and after transition to PostgesSQL was crash: ** ProgrammingError at / ОШИБКА: функция lower(timestamp with time zone) не существует LINE 1: ..., "blog_post"."updated" FROM "blog_post" ORDER BY LOWER("blo... ^ HINT: Функция с данными именем и типами аргументов не найдена. Возможно, вам следует добавить явные приведения типов. ProgrammingError at / ERROR: function lower (timestamp with time zone) does not exist LINE 1: ..., "blog_post". "Updated" FROM "blog_post" ORDER BY LOWER ("blo ... ^ HINT: Function with given name and argument types was not found. Perhaps you should add explicit casts. ** #views.py from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.utils import timezone from django.db.models.functions import Lower, Now from .models import Post from .forms import PostForm def post_list(request): order_by = request.GET.get('order_by') direction = request.GET.get('direction') ordering = Lower(order_by) if direction == 'desc': ordering = '-{}'.format(ordering) elif order_by == None: order_by = 'publish' post = Post.objects.all().order_by(ordering) paginator = Paginator(post, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'order_by': order_by, 'direction': direction, 'page': page } return render(request, 'blog/post/list.html', context) def post_detail(request, year, month, day, post): post = … -
How I merge different two project in django?
I designed a website in django. I want to add this chat which someone else did ..to my website. However, I could not combine the two projects. I share here my code... please help me. How can I combine both? projectname --> lubdub appname --> accounts My codes; https://hizliresim.com/LZ60vp --> views.py https://hizliresim.com/IstSCI --> account/urls.py and lubdub/ urls.py https://hizliresim.com/PhWdr3 --> models.py And, my setting.py; INSTALLED_APPS = [ 'accounts', ] STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') The project I want to add is this https://github.com/Joetib/djangoajaxchat This is different project and inside different app from me.. Different models here and different urls.. What I want to do is; when someone goes to "/chat" a joint chat will be opened. İn my models , I have a model that keeps the registered user.. And I want, same user, sent message a chat. But I can't make it. Would anyone help me please? -
Django rest Framework Endpoint
I need to get this endpoint /comments/int:post_id/ I can GET and POST comments and posts but I need to show all comments to specific post. I don´t know how to connect it. My code look like comment urls urlpatterns = [ path('', views.CommentsView.as_view()), path('<int:post_id>/', views.CreateCommentsView.as_view()), ] comment view.py # I get all comments/ class CommentsView(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer # Comments to specific post class CreateCommentsView(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer lookup_url_kwarg = 'post_id' def perform_create(self,serializer): post = self.kwargs.get('post_id') post =set.get_queryset().filter(id = 'post_id') post.comments.add(comment) post = Post.objects.filter(id=self.kwargs.get('post_id')) serializer.save(user=self.request.user, post=post) comment serializer from rest_framework import serializers from .models import Comment from django.contrib.auth import get_user_model User = get_user_model() class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'post', 'content', 'created'] class UserSimpleSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class CommentSimpleSerializer(serializers.ModelSerializer): user = UserSimpleSerializer() class Meta: model = Comment fields = ['user', 'content', 'created'] post.view.py class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class LikePost(generics.UpdateAPIView): permission_classes = [IsNotPostUser] queryset = Post.objects.all() serializer_class = PostSerializer