Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Board game multi-player server using Django Channels
I have some experience in building web applications with Django, and now I'm trying to create a multiplayer server where users will be able to play board games (checkers, reversi, etc.). I've heard that Django Channels is suitable for this task. Can someone point me in the right direction (with ideas, advises, information, examples) how should I implement it? I found only multi-user chat example, but it's a very small part of the whole project. -
django-tenant: cannot find location of temporary file upload
I am running a multi-tenant app with nginx and gunicorn and when uploading small files (<2.5mo) everything works well, however when files gets bigger, I get a 502 bad gateway from nginx. From Where does django store temporary upload files?, I found it that small and big files are not handled the same way by django. The underlying issue is that nginx 'client_max_body_size' parameter is not pointing toward the temporary upload folder for the tenants. Here is what my setup looks like django.settings.py TENANT_MODEL = "customers.Client" TENANT_DOMAIN_MODEL = "customers.Domain" DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = "tenants/%s" upload forms.py class ETL(forms.Form): Historical = forms.FileField() Pre_processing = forms.FileField() Supplier = forms.FileField() parameters = forms.FileField() views.py @method_decorator(login_required, name='dispatch') class Getfiles(LoginRequiredMixin,FormView): template_name = 'upload.html' form_class = ETL success_url = 'dash.html' def form_valid(self, form): url = self.request.build_absolute_uri() form.process_data(url) return super().form_valid(form) and nginx/sites-enabled/django.conf: server { server_name mysite; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite/fullchain.pem; # managed$ ssl_certificate_key /etc/letsencrypt/mysite/privkey.pem; # manag$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location /static/ { autoindex on; alias /home/ubuntu/mysite/static/; } location / { client_max_body_size 20M; include proxy_params; proxy_pass http://unix:/home/ubuntu/mysite/app.sock; } I have seen there Django+gunicorn+nginx upload large file 502 error that I should provide the … -
Why docker allows removal of other people's containers/images?
So I am new to docker. I have created my own container and image for a Django app to try out. When I use this command in ubuntu, I can see a list of containers and images docker ps -a and this command to delete a container docker rm -f <container_id> What puzzles me is that it is possible for me to delete containers and images created by someone else (of course I tried it on "hello-world" projects only). Why is this allowed? What happen to real production containers/images? -
How can I access a Django returned json object in javascript / on the client-side?
I'm having hard times to find a way to use my Django returned data on the clientside. I think I mix up several concepts here. This is my view that calls the model StocksPrice and returns all data in the table column stockName: def getStocksAvailable(request, *args, **kwargs): StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName)) return HttpResponse({"data": StocksAvailable}) and according Javascript part for testing purposes: var received_data = "{{ StocksAvailable }}" console.log(received_data); # Outputs: {{ StocksAvailable }} I also tried it using render in the view: def getStocksAvailable(request, *args, **kwargs): StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName)) return render({"data": StocksAvailable}) Why does JS logs it as a string whereas it is supposed to be a variable containing the returned json object? And how could I basically print the returned data from the view for debugging (maybe s.th. is wrong with the json itself)? -
How to choose a specific object from a many to many field relationship inside a template in django
I am passing in a bunch of Project objects into my template as the variable 'projects'. Then I loop over each of them like this: {% for project in projects %} <div class="conflict"> <h2>{{ project.title }}</h2> <div class="conflictdata"> <p>A conflict with *USER*</p> <p>Created on *DATE*</p> <p>MORE INFO HERE?</p> </div> </div> {% endfor %} Now the project models has a many to many relationship with the Django user model (but each project only has two users) (while every user can have many projects). What I would like to do is exclude the current logged in {{user}} from the Project.users queryset and display it in my template (because that would be the user with whom the current logged in user shares said project). How could I achieve this? Also here's my view in case it helps: @login_required def myconflicts(request): form = ProjectForm(request.POST or None) if request.method == "POST": form = ProjectForm(request.POST) if form.is_valid(): project = form.save() project.users.add(request.user) project.users.add(User.objects.last()) return redirect('problemdashboard:problem-dashboard', project_id=project.pk) form = NeedForm() else: form = NeedForm() return render(request, 'conflictmanagement/myconflicts.html', { 'form': form, 'projects': request.user.project_set.all() }) -
Can anyone help me with this error using Django channels
I was developing chatting app using channels. Here is the link to the documentation . https://channels.readthedocs.io/en/latest/tutorial/part_2.html Trying to resolve it for 2 days. When I try to communicate with Redis. It is giving this error. Installed that library. Implement the document step by step got this error. Please help me to resolve this error. >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\hp\Desktop\django\venv\lib\site-packages\asgiref\sync.py", line 120, in __call__ return call_result.result() File "c:\users\hp\appdata\local\programs\python\python36\lib\concurrent\futures\_base.py", line 425, in result return self.__get_result() File "c:\users\hp\appdata\local\programs\python\python36\lib\concurrent\futures\_base.py", line 384, in __get_result raise self._exception File "C:\Users\hp\Desktop\django\venv\lib\site-packages\asgiref\sync.py", line 180, in main_wrap result = await self.awaitable(*args, **kwargs) File "C:\Users\hp\Desktop\django\venv\lib\site-packages\channels_redis\core.py", line 299, in send async with self.connection(index) as connection: File "C:\Users\hp\Desktop\django\venv\lib\site-packages\channels_redis\core.py", line 835, in __aenter__ self.conn = await self.pool.pop() File "C:\Users\hp\Desktop\django\venv\lib\site-packages\channels_redis\core.py", line 73, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "C:\Users\hp\Desktop\django\venv\lib\site-packages\aioredis\commands\__init__.py", line 175, in create_redis loop=loop) File "C:\Users\hp\Desktop\django\venv\lib\site-packages\aioredis\connection.py", line 113, in create_connection timeout) File "c:\users\hp\appdata\local\programs\python\python36\lib\asyncio\tasks.py", line 339, in wait_for return (yield from fut) File "C:\Users\hp\Desktop\django\venv\lib\site-packages\aioredis\stream.py", line 24, in open_connection lambda: protocol, host, port, **kwds) File "c:\users\hp\appdata\local\programs\python\python36\lib\asyncio\base_events.py", line 778, in create_connection raise exceptions[0] File "c:\users\hp\appdata\local\programs\python\python36\lib\asyncio\base_events.py", line 765, in create_connection yield from self.sock_connect(sock, address) File … -
Getting an error when trying to call PRAW grabbing values from Model but no errors if I hard code values
# This works without any issues, removed real values :) - Approach 1 reddit = praw.Reddit(client_id='text1', client_secret='text2', user_agent='text3', username='text4', password='text5') # I check to see if these values are in the model - Approach 2 if user.profile.has_api: reddit = praw.Reddit( client_id = user.profile.client_id_red, client_secret = user.profile.client_secret_red, user_agent = user.profile.user_agent_red, username = user.profile.username_red, password = user.profile.password_red, ) print(reddit) Trying to get some info on a subreddit. If I call praw with the credentials hard coded (approach 1), it works fine with no issues. I instead want to check if these values are available for the current user (approach 2). I'm able to grab and print the variables. If I print the reddit object I get this: <praw.reddit.Reddit object at 0x10aed1d90> Which is a good sign, if I continue to fetch the subreddit with this approach 2 I get these errors: Internal Server Error: /reddits/create/ Traceback (most recent call last): File "/Users/bob/Sites/django/testsite/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/bob/Sites/django/testsite/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/bob/Sites/django/testsite/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/bob/Sites/django/testsite/src/reddits/views.py", line 85, in createReddits if subreddit.community_icon != '': File "/Users/bob/Sites/django/testsite/lib/python3.8/site-packages/praw/models/reddit/base.py", line 33, in __getattr__ self._fetch() File "/Users/bob/Sites/django/testsite/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 519, in … -
Sweet Alert not displaying but response message is showing but opens in new browser . how can i solve this?
code from custom.js everything is working fine but when i want to show the json response from djngo library it opens in new tab $(document).ready(function() { $('#send_mail_ajax').on('click', function (event) { event.preventDefault(); let sender = $('#id_sender').val(); let subject = $('#id_subject').val(); let message = $('#id_message').val(); let data = { sender: sender, subject: subject, message: message }; $.ajax({ type: 'post', url: 'http://127.0.0.1:8000', data: data, csrftoken= jQuery("input[name=csrfmiddlewaretoken]").val(), success: function (response) { Swal.fire( 'Mail', response.message, 'success' ) } }) }); }); code from views.py def contact(request): if request.method == 'POST': sender = request.POST.get('sender') subject = request.POST.get('subject') message = request.POST.get('message') send_mail(subject, message, sender, ['razeevstha002@gmail.com']) resData = dict() resData['message'] = "Successfully Send" return JsonResponse(resData) else: data = { 'my_form':ContactForm } return render(request, 'frontend/pages/contact/contact2.html',data) -
Django with AWS S3 Error: This XML file does not appear to have any style information associated with it
I just integrated an S3 bucket to my django app and I am able to upload images to the S3 bucket. However, I am not able to view those images in the HTML page it doesnt work and when I try to inspect in chrome and use the src link I am presented with this error: When I try to use the placeholder image that I've already uploaded to the S3 bucket, it doesn't display too. Here is a portion of my template where I display the image: {% for post in posts %} ... <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> ... {% endfor %} This is my model for the images part: class Post(models.Model): ... image = models.ImageField(upload_to='post-covers', default='placeholder.jpg') ... -
Why is my model form failing to validate and save in Django?
I am sending django 2 forms in a post request 1 which works as intended and the other which fails to validate and as such is not saved. the code for the form is here : class Pick_Vulns(ModelForm): class Meta: model = ReportVuln fields = "__all__" widgets = { 'Vuln' : Select(attrs={'class':'form-control'}), 'Report' : HiddenInput(attrs={'Value': reportcount}), } This form loads correctly on the page with no issues but when the post request is sent it seems to be not be accepted and fails to validate. an example of the post request : a post request to the server the first param being a csrf token the next for being the working form the last two being part of the form that does not function. The code for the post request within my django view is as follows : def post(self, request): forminput = Reportform(request.POST or None) returnedvulns = Pick_Vulns(request.POST or None) if request.user.is_staff == True: if forminput.is_valid(): forminput.save() if returnedvulns.is_valid(): returnedvulns.save() forminput = Reportform inoutform = { 'Reportform': forminput, 'reportvulns': pickvulns, 'ReportCount': Reportcount } return render(request, self.template_name, inoutform, ) the model to which the form is saved is here : class ReportVuln(models.Model): Vuln = models.ForeignKey(Vulnerability, on_delete=models.SET_NULL, null=True, related_name='Vulnerability') Report = … -
Filtering django queryset by slug
I would like to filter the Post objects also with the slug, how should one go about this? The model looks as follows: class Post(models.Model): slug = models.SlugField() title = models.CharField(max_length=100) post_json = models.CharField(max_length=100000, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) and the view looks like this. def load_post_json(request): obj = Post.objects.filter(author_id=request.user.id) data = list(obj.values()) return JsonResponse({'posts': data}) -
Check for data in Django and print message not founds if not found data
Views.py get_camp = input name in form title,location is objects in class Campgrounds in model file def campSearch(request): camp = Campground.objects.all() template_name = 'home.html' search_query = request.GET.get('get_camp') if search_query: campgrounds = camp.filter(Q(title__icontains=search_query) | Q(location__icontains=search_query)).distinct() context = { 'campgrounds':campgrounds } else: messages.warning(request, 'please Enter name or location') context = { 'Not found':None } return render(request, template_name,context) html File {% for post in campgrounds %} <div class="col-md-3 col-sm-6" > <div class="thumbnail"> <img src="{{ post.image.url }}" style="width:340px;height:240px"> <div class="caption"> <h4>{{ post.title }}</h4> </div> <p> <a href="{% url 'src:detail' post.pk %}" class="btn btn-primary">More Info</a> </p> </div> </div> {% endfor %} -
How can I exclude rest-auth endpoint from the Django built-in API documentation?
To hide the endpoint in the Django documentation just @schema(None) has to be added for example to GenericAPIView, however I have a problem with these three urls: url(r'^swagger/', schema_view), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), I am not able to add @schema(None) decorator because I do not have declared views for these urls. Any ideas how to work it around? -
Adding Model constraints using another Model
I am currently working on an application tracking app with Candidate, Application and Job models. Ideally I would want a candidate to only apply once for a job, but the candidate should be able to apply to another Job if they wish. The problem I am encountering is since the Application model is sitting in between the Candidate and Job, I am not sure where to add the constraint - where the Application model 'detects' whether the Candidate already exists in a Job or not through the defined relationships in the Application model. Adding a unique constraint would only allow a Candidate to apply once throughout, so that would not be ideal. Candidate A -> Application A -> Job A # should work Candidate A -> Application A -> Job A # should throw error Candidate A -> Application B -> Job B # should work Here's my models.py class Candidate(models.Model): # Candidate Personal and Contact Information date_created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) email = models.EmailField() phone = models.CharField(max_length=30) # Candidate Location Information city = models.CharField(max_length=120) state = models.CharField(max_length=120) country = CountryField(blank_label='Select Country') zip_code = models.CharField(max_length=10) def __str__(self): return f'{self.first_name} {self.last_name}' class Application(models.Model): # Application Status Choices … -
Open pdf on input click in django
I'm trying to open a pdf file on the input click. Please let me know if it's possible on not? This is my form <form> <input type="text" name="response"/> </form> I know if I want to open a file I should take type=file and when I click Enter I want to open a pdf file. view to open a pdf file. def pdf_view(request): try: return FileResponse(open('resume.pdf', 'rb'), content_type='application/pdf') except FileNotFoundError: raise Http404() The above view works fine i.e when I click /pdf/ it renders the pdf in browser but is it possible to open a file when I type pdf in text field and it renders a file for me ? -
Part of my django website looks worse on smartphone than rest, what is causing it?
I wanted to ask you for your help with my django website. I pushed my website to heroku, everything is working fine I think. Except "final view" on smartphones. On PC it is good, but on phone I am able to scroll a little bit horizontally and vertically. I suppose that is because I used "zoom" css functions on my images to make them align how I wanted. But still, images were small I used zoom to make them bigger, not in the other way so it should be fine? Can I somehow patch it without destroying rest of my work? I found this stackoverflow topic: DISABLE the Horizontal Scroll But "countering" user scrolling with JS looks like a plan "B" or "C" to me :P Here are screenshots that shows my problem: Here is template of this page: {% extends "builder/base.html" %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <meta charset="UTF-8"> <title>Robot Builder</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!--Main jumbotron with all content inside--> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">{{ robot_id }} <!--Button for reloading page to randomize robot elements … -
Django how to hide form based on value of another one
I have a question for you. I'm trying to customize my crispy form based on my needs. But I have a problem that I wanna overcome. Imagine that we have 3 forms <div class="form-row"> <div class="form-group col-2 0 mb-0" > {{form.tipologia|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.descrizione|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.prezzo|as_crispy_field}} </div> </div> And that I wanna hide the form.prezzo if descrizione is equal to "Hello World". How could I get that? -
I am getting error 404 when accessing django served with gunicorn and nginx
I have an angular app that loads on https://xxx.xxx.xxx.xxx/ being served behind a proxy-server (Nginx). On the same server, I have hosted my backend(django) and when I try to access any 'API' services with domain-ip/api/users I get Page not found (404) Request Method: GET Request URL: http://xxx.xx.xx.xxx/api/users/ When I inspect the nginx logs, there's no recent log that is recorded to highlight any error. Here's my /etc/nginx/sites-available/default server { listen 80 default_server; listen [::]:80 default_server; #root points to my angular app root /home/bc_sparrow/bc_s/frontend/dist; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name 138.xx.55.xxx; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.html; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; #proxy_set_header Host $http_host; #adding this line made things worse proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } } With this configuration above, when I run these two commands I do not get an error. sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled sudo nginx -t Also when I run sudo systemctl status gunicorn I get gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: active (running) since … -
How to split .xls export based on values in model [django]
I got this snippet, that takes care of my now working export function, that takes a list and export it if it hasn't been exported before. views.py @login_required(login_url='/log-in/') def export_shipments_xls(request, *args, **kwargs): # Make a variable list with checked rows checked = request.POST.getlist("rows[]") # Find relevant rows for export if request.method == "POST" and checked: if not None: # Change boolean from False to True, to track exported lists exported = models.NewShipment.objects.filter(id__in=checked) exported.update(exported=True) # Set response type response = HttpResponse(content_type='application/ms-excel') # Set filename response['Content-Disposition'] = 'attachment; filename="shipments.xls"' # Workbook and Worksheet wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('NewShipment') # Sheet header, first row row_num = 0 # Font settings for header row font_style = xlwt.XFStyle() font_style.font.bold = True # Values and order for header row columns = [ 'Order ID', 'Full Name', 'Street', 'Postal Code', 'City', 'E-mail', 'Telephone', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() # Values and order for table objects rows = models.NewShipment.objects.filter(id__in=checked).values_list( 'increment_id', 'full_name', 'street', 'zip_code', 'city', 'email', 'telephone', ) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response else: return HttpResponse("Data") models.py class NewShipment(models.Model): increment_id = models.CharField(max_length=9) full_name … -
starting a django server with cmd
i created a virtual environment for django and im trying to start the server but i keep running into this problem (Django-8VqULu7_) C:\Users\rondo11\Documents\learn how to program\learning python\Django>py manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? what is the problem? -
Django Channels VS Django 3.0 / 3.1?
Can someone clarify the differences or complementarities between Django Channels Project and new Django native async support? From what I understood, Django-Channels is a project that have been started outside of Django, and then, started to be integrated in the core Django. But the current state of this work remains confusing to me. For example, today I'm using Django 2.2, and I'd like to add WebSocket support to my project. Should I: Upgrade to the latest Django version? Use Django Channels package? Do both actions? -
How to combine django datefield and timefield
I have tried with below query,It gives error like, AttributeError: 'decimal.Decimal' object has no attribute 'tzinfo' start_date = DateField() strt_time = TimeField() obj=model.objects.annotate( datetimeobj=ExpressionWrapper(F('start_date') + F('strt_time'), output_field=DateTimeField() also tried with another solution, data=model.objects.annotate(datetime=datetime.combine('start_date','start_time')) it gives below error, TypeError: combine() argument 1 must be datetime.date, not str Thank you.. -
Add count whenever any entity is fetched Django REST Framework
My model looks like class Article(models.Model): article_type = models.ForeignKey( ArticleType, on_delete=models.CASCADE, related_name='articles' ) title = models.CharField( max_length=100, verbose_name='Article Title' ) count = models.IntegerField( verbose_name='Frequency Count' ) def __str__(self): return self.title and my urls.py router = DefaultRouter() router.register('article', ArticleViewSet, basename='article') urlpatterns = [ path('viewset/', include(router.urls)), ] Now I wan't to add functionality such that whenever any article is fetched i.e http://127.0.0.1:8000/viewset/article/{pk} than 'count' of article of id=pk becomes count = count+1 so that I can sort them according to this count. -
Why is the view path /slug:slug/slug:url/ doesn't find django
I’m trying to understand why my page at 127.0.0.1/* manganame / * numberchaper does not open. Error 404, path / * manganame / * numberchaper not found. The path / * manganame / opens correctly, there I display links to the passage to the chapter. I keep chapters in the Add_chapters model. Why does not it work? urls.py from django.urls import path, re_path, include from . import views from django.conf.urls import url extra_patterns = [ path("<slug:url>/", views.ChapterDetailView.as_view()), path("", views.ArticleDetailView.as_view(), name='manga_index'), ] urlpatterns = [ path("", views.Get_list.as_view()), path('<str:slug>/', include(extra_patterns)), ] models.py class Manga(models.Model): title = models.CharField("Название", max_length=100) another_name = models.CharField("Другие названия", max_length=150, default="") description = models.TextField("Описание") poster = models.ImageField("Постер", upload_to="manga/") part = models.PositiveSmallIntegerField("Томов", default="0") chapter = models.PositiveSmallIntegerField("Глав", default="0") year = models.PositiveSmallIntegerField("год выпуска", default="") author = models.ManyToManyField(Author, verbose_name="Авторы", related_name="manga_author") genre = models.ManyToManyField(Genre, verbose_name="Жанры") artist = models.ManyToManyField(Artist, verbose_name="Художники") manga_shots = models.ImageField("Изображения", upload_to="manga_shots/") category = models.ForeignKey( Category, verbose_name="Категория", on_delete=models.SET_NULL, null=True ) url = models.SlugField(max_length=130, unique=True) class Add_chapter(models.Model): chapter_name = models.ForeignKey( Manga, verbose_name="Манга", on_delete=models.SET_NULL, null=True, max_length=100, default="" ) volume = models.PositiveSmallIntegerField("Том", default="0") date_upd = models.DateTimeField(auto_now=True) chapter = models.PositiveSmallIntegerField("Глава", unique=True) files = models.FileField("Глава", upload_to=user_directory_path) url = models.SlugField(max_length=130, unique=True, default="") views.py class ArticleDetailView(DetailView): model = Manga template_name = "mangaHTML/article_detail.html" slug_field = "url" def get_context_data(self, **kwargs): context = … -
How to parse django view object to JavaScript object?
I am trying to build this : There is a button, and if the button is clicked, it sends some request to django server and server returns some form. After that, put the form into a div. So, my idea is 1. make a event handling function to handle button click event 2. put AJAX operation into the event handling function to send request and put a form into a div 3. Write view to receive request and return form that fits with request 4. the AJAX operation at Step 2 put returned form into the div But the problem is, at step 3, returning form. The form is form = EventForm({'date':date(year,month,day)}), which is ModelForm based on model Event. Because Javascript cannot understand Django form object, I need something to parse it into javascript object, like div node, or just HTML string, but I don't know :( I know there is {{ form.as_p }} for template, but I wonder if there is such function for view codes