Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I enable users to select their workspace when using Sign in with Slack?
I'm having some trouble with getting Sign in with Slack to work like I want it to. Specifically, I'm seeking to build a platform that people can use for their Slack workspaces, and depending on which workspace they are signing into, different content (in this case, saved slack posts) show up. I've incorporated Sign in with Slack to my website following the Slack provided tutorial. I use https://slack.com/oauth/v2/authorize?user_scope=identity.basic,identity.email,identity.team,identity.avatar&client_id to trigger the process. My redirect URI passes the code parameter to here @csrf_exempt @api_view(['GET', 'POST']) def auth(request): code = request.data['code'] url = 'https://slack.com/api/oauth.v2.access?client_id={}&client_secret={}&code={}'.format(SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, code) response = requests.get(url) response_dict = json.loads(response.text) print(response_dict) if response_dict.get('ok'): user_id = response_dict['authed_user']['id'] team_id = response_dict['team']['id'] access_token = response_dict['authed_user']['access_token'] client = WebClient(token=access_token) user_profile = client.users_identity() email = user_profile.get('user').get('email') display_name = user_profile.get('user').get('name') image = user_profile.get('user').get('image_48') userObject = User.objects.get_or_create(username= user_id + team_id, user_id=user_id, team_id=team_id, email=email)[0] userObject.first_name=display_name userObject.last_name='' userObject.image=image userObject.save() response_dict['model_id'] = userObject.id return Response(json.dumps(response_dict), status=status.HTTP_200_OK) else: return Response(None, status=status.HTTP_400_BAD_REQUEST) I have a couple questions. How do I enable the user to sign into any slack workspace they want when they click the Sign in with Slack button? Currently it defaults to just one workspace and I am not sure how to change that. When I manually enter a different … -
Django Rest Framework - "unique_together" internal server error. How to respond with error
I currently have a model called "Review" where I have a "unique_together" constraint so one user can only write one review per post. class Review(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, related_name='reviews', on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField() comment = models.TextField(blank=True, null=True) class Meta: unique_together = ['user', 'post'] And in my View I am grabbing the user from the request (I'm using token authentication) and use that user to save the object by overwriting the "perform_create" method: class ReviewCreateView(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = ReviewCreateSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) And my serializer looks like this: class ReviewCreateSerializer(ModelSerializer): class Meta: model = Review fields = ['post', 'rating', 'comment'] When I try to submit two reviews to the same post by the same user I get an internal server error. The body of my HTTP POST request looks like this: { "post" : 11, "rating": 1, "comment": "this is a great post" } Instead of getting an error response (for example 403 error). I get this Django server error instead: django.db.utils.IntegrityError: duplicate key value violates unique constraint After spending some time researching I saw that Django Rest Framework provides the "UniqueTogetherValidator". Which I added like this: class ReviewCreateSerializer(ModelSerializer): … -
Ive pushed my django app to production, but when i open the media files it raises a django.views.static.serve error
Page not found (404) Request Method: GET Request URL: http://limitless-cliffs-18209.herokuapp.com/media/image/IMG_2516.JPG Raised by: django.views.static.serve "/code/media/image/IMG_2516.JPG" does not exist -
How to display JSON objects to the template from rapidAPI using Django
Here is my python code for the GET request from django.shortcuts import render import requests def index(request): url = "https://quotes-inspirational-quotes-motivational-quotes.p.rapidapi.com/quote" querystring = {"token":"ipworld.info"} headers = { 'x-rapidapi-key': "fae2454b29mshf5c9ff8e23af3bep105c25jsnc78186056962", 'x-rapidapi-host': "quotes-inspirational-quotes-motivational-quotes.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring).json() print(response) return render(request, 'olops/index.html', {'response': response}) Here is the response from postman click me Here is my code for my template {% for i in response %} {{ i }} {% endfor %} Here is the output in my web page html template output When I add {{i.text}} or {{i.author}} in the template, it's not returning the value. How can I proceed with outputting JSON objects with Django? Thank you -
Django - Hosting Platform query
I have built a Django local web application which I want to host on some platform now. I am using Postgres SQL as database. Any recommendations of hosting platforms with cheaper or free plans? My website will be used by few users only (<50), so I don't need very powerful server/CPU etc. -
Why django TemplateSyntaxError is raised in here?
Im tring to iterate through context of my view and get 'ga:deviceCategory' values only , the code that I'm running in HTML is: <div class="card-body"> {% for i in pvdc %} <p>{{ i.get('ga:deviceCategory') }}</p> {% endfor %} </div> My view in django is : def dashboard(request): context = {'pvdc': [{'ga:deviceCategory': 'desktop', 'ga:pageviews': 673, 'ga:avgSessionDuration': 53.4447946}, {'ga:deviceCategory': 'mobile', 'ga:pageviews': 2373, 'ga:avgSessionDuration': 69.62674418604651}, {'ga:deviceCategory': 'tablet', 'ga:pageviews': 322, 'ga:avgSessionDuration': 26.205426356589147}]} return render(request, 'user/index.html', context) The syntax error that I receive is: Could not parse the remainder: '('ga:deviceCategory')' from 'i.get('ga:deviceCategory')' what is the problem here and how can i get the values? -
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another. So I have an account model and a blog post model, with the author as the foreign key. I am unsure of how i can do the querying of the account. Can anyone advise how this is normally done? Because I tried to do user_id=request.user.id but this would take me to my own account view. Thanks! html <a class="dropdown-item" href="{% url 'account:view' %}">{{blog_post.author}}</a> views.py def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post return render(request, 'HomeFeed/detail_blog.html', context) urls.py for accounts: path('<user_id>/', account_view, name="view"), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Retrieve the same values whose data is there or exists and not the rest.In django
I want to have a data that does not have any empty value in database or in row. I wrote like this in my code. faq = FAQ.objects.values('question','answer','field_id') this the output in my terminal {'question': None, 'answer': None, 'field_id': None} {'question': 'Test question', 'answer': '<p>Testsaddsf description</p>\r\n', 'field_id': 'TestTest'} i don't want None value data. -
upload image and already saved image, this two parts want to display on two different html template
i use modelformset_factory to upload image, but i want to separate the already saved image(A in the below link) and upload image(B in the below link) on two different html template. How do i resolve this problem? thanks for your help!! enter image description here here is my code below: views.py def post_image(request): PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3) if request.method == 'POST': formset = PictureFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return HttpResponse("Upload done!!") else: return HttpResponse("Upload Failed!!") else: formset = PictureFormSet() return render(request, "Image.html", {"formset": formset}) models.py class Picture(models.Model): article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE) photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100) first_photo = models.BooleanField(default=False) urls.py path('post/image/', post_image), html <html lang="zh-Hant-TW"> <head> <meta charset="UTF-8"> <title>post_image</title> </head> <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <input type="submit" value="Sumbit"> </form> -
how to get cart and order for a user who sell the product using django
I am building an ecommerce web-application using django where people come and sell their products. Recently i have done the coding where user come ,login and sell their products and another user come and buy these thing .All the order are coming to the admin panel. but i want the user that sell the products get these specific orders . but how the user who sell ,can get their orders and cart . I do not have any logic kindly anyone please guide me. Thnak you -
AJAX POST request error - `Uncaught TypeError: Illegal invocation`
If I try to do this, I get this error: Uncaught TypeError: Illegal invocation $(document).on('input', '#search-inp', (e) => { $.ajax({ type: 'POST', url: '/search/', dataType: 'json', data: { input: $('#search-inp').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'), }, success: function(data) { console.log(data); } }); }); And if I try to do this, I get this error: 403: Forbidden $(document).on('input', '#search-inp', (e) => { $.ajax({ type: 'POST', url: '/search/', dataType: 'json', processData: false, contentType: false, data: { input: $('#search-inp').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'), }, success: function(data) { console.log(data); } }); }); # This is my views.py def search(request): return JsonResponse(data={ 'test': 'test' }) What could be the problem? Your help is greatly appreciated. Thank you -
Django path regex construction
Am trying to construct Django URL path by a using a regex but the path can't be resolved to my view, the ending of the path should be like 127.0.0.1:8080/watch?v=bXHfrdi_fsU like those urls you see on youtube videos where the bXHfrdi_fsU is some random characters which will be passed to my view as id string using <str:id>. Here is what I have tried but was unsuccessful #urls.py import path, re_path from myapp import views urlpatterns = [ re_path = ('/(watch)\?v\=<str:id>', views.my_view, name='my_view'), ] and here is my views:- def my_view(request, id): string = str(id) return HttpResponse('It works,here is your string'+string) -
Seeding the random generator for tests
I made it work using factory-boy's get_random_state/set_random_state, although it wasn't easy. And the biggest downside is that the values are big. So the thing that comes to mind is to write it to a file. But then if I accidentally run the tests not telling it to seed from the file, the value is lost. Now that I think about it, I can display the value too (think tee). But still I'd like to reduce it to 4-5 digits. My idea is as follows. Normally when you run tests it somewhere says, "seed: 4215." Then to reproduce the same result I've got to do SEED=4215 ./manage.py test or something. I did some experiments with factory-boy, but then I realized that I can't achieve this even with the random module itself. I tried different ideas. All of them failed so far. The simplest is this: import random import os if os.getenv('A'): random.seed(os.getenv('A')) else: seed = random.randint(0, 1000) random.seed(seed) print('seed: {}'.format(seed)) print(random.random()) print(random.random()) /app $ A= python a.py seed: 62 0.9279915658776743 0.17302689004804395 /app $ A=62 python a.py 0.461603098412836 0.7402019819205794 Why do the results differ? And how to make them equal? -
How to change the user display name to their first name in Django
I am using the Django inbuilt user authentication system, from from django.contrib.auth.models import User. And I have realised that in the admin page it always displays the username of the user. Is it possible to change the def __str__ (self): method of that function to display a customized one, something like this. def str (self): return f"{self.first_name}" -
No Post matches the given query in django Error
So i have a project called star social project this project is similar to a socail media that you can post and create group but this project you can only post when you are in a group. So i get an error message that is not familiar to me which is on the title, i tried to search on google and get some result but when i implement it to my project it does not work. So why im getting this error is because i'm trying to create a comment section and when i click the add comment that's when i get the error message. So i'm here to ask someone to help me because i'm not really familiar on this error and i'm just learning django for about 2 months now. models.py ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse from django.utils import timezone User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = … -
Django: Won't Delete Post
I am trying to get my posts to delete on the click of a button that pops up on the screen instead of sending the user to a different delete page. The form works but it won't actually delete the posts. What am i doing wrong here Stack Overflow says im using too much code so ignore the next few lines. too much code too much code too much code too much code Some relevant info: templates: {% block head %} <head> <link rel="stylesheet" type="text/css" href="{% static 'css/my_posts.css' %}"> <title>Create - My Posts</title> <script> function togglePopup(){document.getElementById("popup-1").classList.toggle("active")} </script> </head> {% endblock head %} {% block content %} <div class="content_section"> <div class="btn_container"> <a class="new_post" href="{% url 'newpost' %}"><button class="new_post_btn">New Post</button></a> </div> <div class="content_section_two"> {% for product in products %} <div class="post_short_container"> <div class="title_container"> <a href="#" class="post_link"> <div><b>{{ product.title }}</b></div> </a> </div> <div class="right_btns"> <a href="{% url 'editpost' product.id %}" class="edit_link">Edit</a> <a href="#" class="stats_link">Stats</a> <div class="ad_btn_container"> <div class="ad_btn">Ad</div> </div> <div class="delete_btn_container"> <div class="delete_btn" onclick="togglePopup()">Delete</div> </div> </div> </div> <div class="delete_prompt_container" id="popup-1" action="{% url 'deletepost' product.pk %}"> <form method="POST"> {% csrf_token %} <p class="delete_prompt">Are you sure you want to delete this post?</p> <div class="cancel_delete_container"> <div class="cancel_button" onclick="togglePopup()">Cancel</div> <input value="Delete" type="submit" name="confirm" class="confirm_delete_button"> </div> </form> </div> … -
How to add expiry date in HUEY dynamic periodic task just like in celery tasks?
Is there a way to add expiry date to a Huey Dynamic periodic task ? Just like there is an option in celery task - "some_celery_task.apply_async(args=('foo',), expires=expiry_date)" to add expiry date while creating the task. I want to add the expiry date while creating the Huey Dynamic periodic task. I used "revoke" , it worked as it supposed to , but I want to stop the task completely after the expiry date not revoking it . When the Huey dynamic periodic task is revoked - message is displayed on the Huey terminal that the huey function is revoked (whenever crontab condition becomes true). (I am using Huey in django) (Extra) What I did to meet the need of this expiry date - I created the function which return Days - Months pairs for crontab : For eg. start date = 2021-1-20 , end date = 2021-6-14 then the function will return - Days_Month :[['20-31',1], ['*','2-5'], ['1-14','6']] Then I call the Huey Dynamic periodic task (three times in this case). (the Days_Month function will return Day-Months as per requirement - Daily, Weekly, Monthly or repeating after n days) Is there a better way to do this? Thank you for the help. -
Django Unable to pass a variable name in the next template
Hi I am facing a problem in my project . In the Patient list, if a Click the Notes row present in the Add notes column. The new template load where it will list the recent notes for the patients... and also it allows me add patient notes by selecting the patient ( i am passing the objects of patients through forms ) My problem .. How to add notes to the specified patient only. ( i.e. by not passing through forms) and also filtering to display the specfic Patient notes only. Code Model: class Notes(models.Model): doctorId = models.PositiveIntegerField(null=True) patientName = models.CharField(max_length=40, null=True) report = models.TextField(max_length=500) NoteDate = models.DateTimeField(default=timezone.now) #def __str__(self): # return self.patientName+" "+self.report @property def get_id(self): return self.id View @login_required(login_url='doctorlogin') @user_passes_test(is_doctor) def doctor_add_notes_view(request): appointmentForm=forms.PatientNotesForm() notes = models.Notes.objects.all().order_by('-NoteDate') mydict={'appointmentForm':appointmentForm,'notes':notes} if request.method=='POST': appointmentForm=forms.PatientNotesForm(request.POST) if appointmentForm.is_valid(): appointment=appointmentForm.save(commit=False) appointment.doctorId =request.user.id #request.POST.get('doctorId') doctors = models.Appointment.objects.all().filter(AppointmentStatus=True, status=True) appointment.patientName = models.User.objects.get(id=request.POST.get('patientId')).first_name now = datetime.now() print("Current date and time : ") print(now.strftime("%Y-%m-%d %H:%M:%S")) appointment.NoteDate = now print('doctors', doctors) appointment.save() return HttpResponseRedirect('doctor-view-patient') else: print(appointmentForm.errors) return render(request, 'hospital/doctor_view_patient.html',{'alert_flag': True}) return render(request,'hospital/doctor_add_notes.html',context=mydict) def doctor_view_patient_view(request): appointments1 = models.Appointment.objects.all().filter(AppointmentStatus=False, status=True,doctorId=request.user.id) print('appointments are ', appointments1) patientid = [] for a in appointments1: patientid.append(a.patientId) print('patientid', patientid) patients = models.Patient.objects.all().filter(PatientStatus=True, status=True, user_id__in=patientid) print('patients', patients) … -
Handing image file not found error in Django
I am trying to handle the image not found an error in Django by defining a custom view unhandle_urls. The way I am trying to do this is the following. Define a URL pattern inside urls.py by matching the image URL's pattern to my custom view unhandle_urls Here are my url patterns inside urls.py urlpatterns = [ .... path(r'images/*', unhandle_urls, name="redirecting the user"), ... ] However, I am still getting the same 404 error whenever any image is requested. Here is the error msg: GET https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png 404 (Not Found) I am not sure what the problem is. My guess is that the url pattern r'images/*' is not matching to https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png, but I try to look at this https://docs.djangoproject.com/en/3.1/topics/http/urls/ but could not find what's wrong with my approach. Any type of help will be appreciated. Thanks in advance. -
How to Filter on Related Model Count in Graphene Django
I have 2 models: import uuid from django.db import models class Country(models.Model): name = models.CharField(max_length=255, unique=True) def city_count(self): return self.city_set.count() class City(models.Model): country = models.ForeignKey('country.Country', on_delete=models.CASCADE) name = models.CharField(max_length=255) And 2 Schemas: import graphene from graphene_django.filter import DjangoFilterConnectionField from core.utils import ExtendedDjangoObjectType from .models import Country as CountryModel, City as CityModel class Country(ExtendedDjangoObjectType): class Meta: model = CountryModel filter_fields = { 'name': ['exact'], # 'city_count': ['exact'] => this does not work! } interfaces = (graphene.relay.Node, ) city_count = graphene.Int() def resolve_city_count(self, info): return self.city_count() class City(ExtendedDjangoObjectType): class Meta: model = CityModel filter_fields = ['name'] interfaces = (graphene.relay.Node, ) class Query(graphene.ObjectType): country = graphene.relay.Node.Field(Country) countries = DjangoFilterConnectionField(Country) city = graphene.relay.Node.Field(City) cities = DjangoFilterConnectionField(City) I can query the city_count on countries, but I can't seem to filter on it (exact, or gte greater than / lte less than) i.e. this works: { countries(first: 10) { edges { node { name cityCount } } } } but this doesn't: { countries(cityCount: 5) { edges { node { name cityCount } } } } and triggers the following error: TypeError at /api/graphql/ 'Meta.fields' must not contain non-model field names: city_count Any idea how I can filter/order on non-model fields? -
How to execute a function relative the request method with django rest framework?
I'm trying to just show a message in terminal if a post requisition, for exemple, be executed. Here I've made these function "get" to be executed but it also doesn't work. :/ if request.method == 'POST': print("Requistion made") views.py: from rest_framework import viewsets from piecesapp.api import serializers from piecesapp import models from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt class PiecesViewSet(viewsets.ModelViewSet): serializer_class = serializers.PiecesSerializer queryset = models.Pieces.objects.all() def get(self, request, format=None): print("Oi") return Response(serializer_class.data) class BoardViewSet(viewsets.ModelViewSet): serializer_class = serializers.BoardSerializer queryset = models.Board.objects.all() PS: I will remove this libs, it's just because i've tried some tutorials e it doesn't work. urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'pieces', views.PiecesViewSet) router.register(r'board', views.BoardViewSet) urlpatterns = router.urls models.py: from django.db import models import uuid # Create your models here. COLOR_CHOICES = ( ('white','WHITE'), ('black', 'BLACK'), ) PICES_NAMES = ( ('king','KING'), ('queen','QUEEN'), ('rook','ROOK'), ('bishop','BISHOP'), ('knight','KNIGHT'), ('pawn','PAWN'), ) WHITE_KING_POSITION = ['e1'] BLACK_KING_POSITION = ['e8'] WHITE_QUEEN_POSITION = ['d1'] BLACK_QUEEN_POSITION = ['d8'] WHITE_ROOK_POSITION = ['a1','h1'] BLACK_ROOK_POSITION = ['a8','h8'] WHITE_BISHOP_POSITION = ['c1','f1'] BLACK_BISHOP_POSITION = ['c8','f8'] WHITE_KNIGHT_POSITION = ['b1', … -
Django ckeditor something is wrong
Hello guys i want to add ckeditor add my admin page but i've a error first i installed ckeditor and than i did those: settings.py INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #... SITE_ID = 1 #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'media/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } ################################### urls.py urlpatterns = [ ... path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py (django can't find ckeditor i think error is here) from ckeditor_uploader.fields import RichTextField, RichTextUploadingField class ModelClass: content = RichTextUploadingField() and also i did collectstatic thing but here is my error code ImportError: cannot import name 'RichTextField' from 'ckeditor_uploader.fields' (C:\Users\User\Desktop\Project\venv\lib\site-packages\ckeditor_uploader\fields.py) -
Django Rest Framework - Return S3 Object to client for user to download
I have an app where users can upload audio files (in the WAV format) and then they see some info about them on the frontend. I want a user to be able to click a file and then have it downloaded onto their computer, so they can listen to it and save it. When users initially upload a file, the file gets stored on Amazon S3, and then the S3 URL gets saved to the database. The backend of the application is in Django / Django Rest Framework and the Frontend is in React. With the code I currently have, nothing happens. I am not seeing any errors and nothing gets downloaded. I know that I can use a tag to download the file, but the problem is that the filename uses the key from S3. I want to be able to control the naming. That is why I am doing this server side. Django code: @api_view(['GET']) def download_audio_file(request, pk): audio = Audio.objects.get(pk=pk) s3_client = boto3.client( 's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION ) s3_response_object = s3_client.get_object(Bucket='bucket_name', Key=s3_key+'.wav') object_content = s3_response_object['Body'].read() response = HttpResponse(object_content, content_type='audio/wav') response['Content-Disposition'] = 'attachment; filename="audio.wav' return response React code: const handleDownloadAudio = (audio) => { fetch(API_URL+"api/audio/"+audio.id+"/download", { method: 'GET', … -
How can I render a Django render() response in an ajax function?
In my view, I return html if a form is valid: if form_valid(): return render(request, 'home.html', context=context) else: return HttpResponse(status=204) I'm submitting multiple forms via ajax and want to render the response, if the status code is not 204: $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function (response, status, jqXHR) { if (jqXHR.status !== 204) { document.write(response); // this works, but I lose some functionality. Some buttons stop working. // How can I render the response correctly? } } }); -
Django - Function should show all entries added to a list, but only one entry is appearing. HTML issue?
I am creating a way for a user to add a post to a list on a website. The page should show all the different items on their list, when they go to their watchlist page. Currently the page is only showing one item, not all of the items added. I know the other items are successfully added because when I view the page as admin http://127.0.0.1:8000/admin/ all the items are there. So I think my error is in the html file of the watchlist. Any help is appreciated as I am new to Django. html file {% extends "auctions/layout.html" %} {% block body %} <div class="container"> <h2>Items on your watchlist:</h2> </div> <div class="container" id="listings"> {% for item in items %} {% for i in item %} <div class="card mb-3" style="max-width: 540px;" id="card-listings"> <div class="row no-gutters"> <div class="col-md-4"> <img src="{{ i.image.url }}" alt="..." class="card-img" style="max- height:350px"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{i.title}}</h5> <p class="card-text">{{i.description}}</p> <p class="card-text">${{i.price}}</p> <a href="{% url 'listingpage' i.id %}"><button class="btn btn-outline- success">Bid Now!</button></a> <p class="card-text"><small class="text-muted">{{i.time}}</small></p> </div> </div> </div> </div> {% endfor %} {% empty %} <h3>No listings found in your watchlist...</h3> {% endfor %} </div> {% endblock %} This function is for viewing the page …