Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What can be the filename of uploading location for ImageField?
Whenever I create Cloth Model with cloth_image, the image uploads to upload_location. My problem is instance.id returns None because the instance is not yet created. What can be the best upload_location for ImageField? def upload_location(instance, filename): new_id = instance.id ext = filename.split('.')[-1] return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) <- Right Here! class Cloth(models.Model): cloth_image = models.ImageField(upload_to=upload_location, null=True, blank=True) I'm using AWS S3. -
How it should be done properly to send and receive message with user ID using websockets in Django and Angular?
I am going to create chatbot using websockets. Each user can have their own account. I have Django backend and frontend written in Angular. At the moment I have a problem with message object. To wit I get this in backend: django_1 | django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint django_1 | DETAIL: Failing row contains (212, {"message":"Hello"}, null). It looks as I wouldn't send user ID from frontend. I wonder how can I solve it and how it should be done properly? My Django message model looks in this way: class Message(models.Model): user = models.ForeignKey('auth.User') message = models.CharField(max_length=200) This is my backend consumer: @channel_session_user_from_http def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) @channel_session_user def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Can we start?' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) This is part of my Angular component: export class HomeComponent { response: string; response2: string; constructor( private chatService: ChatService, private router: Router, private http: Http, ) { chatService.messages.subscribe(msg => { this.response … -
Create an integer field with a drop down box. Django Custom Widget?
I am trying to create an integer field connected with a drop down box to collect a time period from a user. From there i would like to store it in a table in some sort of readable format for the machine e.g 12W from that i can split the object and add 12 weeks on to todays date and fill a Due Date field. For example [12][Days] [weeks] [Months] Would this be a customer widget? or is there a better way of completed it? -
Parse Django JsonResponse with Angular 4
I'm using Django for send JsonResponse. If I map response.json() Angular return me an error that I can't handle. Furthermore, if I use response.text() for visualizing data it return something like that: Response: {u'foo': u'bar', u'title': u'hello world'} In Angular 4 I've this code: return this._http.post(this.serverUrl, JSON.stringify(data), {headers: headers}) .map((response:Response) => response.json()) .catch(this.handleError); In Django Python I've this code: response= {'foo': 'bar', 'title': 'hello world'} return JsonResponse(response, safe=False); I've also tryed this: return HttpResponse(json.dumps(response), content_type='application/json; charset=utf-8',) return HttpResponse(json.dumps(response)) return json.dumps(response) return response -
css is not working in firefox, but with chrome and safari it does
I am trying to adapt my website to firefox, but never made it. But nothing is working, totally nothing with firefox. I made a research on firefox standards, but nothing of them is helping. I believe theres something wrong with the structure. PS: I am going to implement all this in Django and Pywebview, but I have to make it running on firefox first, because the Pywebview is using the Mozilla's core. body { height: 100%; width: 100%; margin: 0; display: flex; display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Chrome */ flex-direction: column; overflow-y: hidden; } #info p { margin: 4; } #svg { width: calc(77% - 2px); height: 100%; margin: 0 auto 0 auto; border-left: 1px solid #000; left: 0; right: 0; cursor: crosshair; /* disable text selection on svg */ -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently not supported by any browser */ } … -
L10N Support for Bootstrap Datetimepicker in Django
When using the datetimepicker of Bootstrap in a Django form, the language and date format can be set like this $(function () { $('#datetimepicker1').datetimepicker({ locale: 'de', format: 'DD.MM.YYYY HH:mm' }); }); Is there an elegant way to automatically fill in these two parameters so that changing the language code in Django will change the locale and format for the datetimepicker accordingly? -
How to import models from one app to another app in Django?
I am trying to reference a model (Person) from one app, in the views-file of another app. Unfortunately, I get an "unresolved reference"-error. Is it possible to reference models from other apps in Django? If so, what am I doing wrong? Let me demonstrate with an example: The image below shows my project. I am currently in the views.py (marked in green), in the app called "autocomplete". I want to reference a person-model in the file "models.py" (marked in red), that belongs to the app "resultregistration". However, I get the error "Unresolved reference Person", even though the class Person does exist in models.py Any help would be strongly appreciated! Thank you for your time! -
How to use slice in forloop django?
right now I am trying to use slice in my template but it is showing the this error:- TemplateSyntaxError at /post/ 'for' statements should use the format 'for x in y': for item in user_basic_info |slice:"2" what I am doing is: {%for item in user_basic_info |slice:"2"%} <li> <div class="userimg_sec"> <div class="userimg"> <img src="{{ item.profileImage }}"> </div> </div> <div class="userdetails"> <p class="username">{{ item.name }}</p> <p class="usernickname">@{{ item.username }}, <span>teacher</span></p> </div> </li> {% endfor %} -
what is the best alternative for django's formfield_for_foreignkey
I need an alternative to wagtail for djangos formfield_for_foreignkey in admin. How can I do this? -
How to add more attributes with json data
I have implemented code like this. message_body = "message body" message_title = "message title" badge = 1 data_message = { "type":"1100", "class_id":"10", } if(condition): # add more attributes with already existing attributes data_message = { "message_body" : message_body, "message_title" : message_title, "badge" : badge, } return data_message else: # without any changes in data_message return data_message If pass the if condition I got only message_body, message_title, badge. I could not receive type and class_id. i want to get all of these if pass the IF conditon. could anyone suggest anyway to do this? -
How to get rest-auth and reactJS to work together?
My rest-auth urls are working properly individual. But, i want to integrate both. I mean django views.py and UI is in ReactJS. My js file is below: import React, { Component } from "react"; import ReactDOM from 'react-dom'; import DjangoCSRFToken from 'django-react-csrftoken'; import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap"; var formStyle={ margin: '0 auto', maxWidth: '320px'} var loginStyle={ padding: '60px 0'} class Login extends React.Component { constructor(props) { super(props); this.state = { username : "", email: "", password: "" }; } render() { return ( <div className="Login" style={loginStyle}> <form style={formStyle} method="post" onSubmit> <DjangoCSRFToken/> <FormGroup controlId="username" bsSize="large"> <ControlLabel>Username</ControlLabel> <FormControl autoFocus type="text" name="username" /> </FormGroup> <FormGroup controlId="email" bsSize="large"> <ControlLabel>Email</ControlLabel> <FormControl type="email" name="email" /> </FormGroup> <FormGroup controlId="password" bsSize="large"> <ControlLabel>Password</ControlLabel> <FormControl type="password" name="password" /> </FormGroup> <Button block bsSize="large" type="submit" > Login </Button> </form> </div> ); } } ReactDOM.render(<Login/> , document.getElementById("login")); And i have added all settings for rest-auth in settings.py and its working fine individual. Please Guide me. I am very new in ReactJS. -
List models according to ContentType and object_id. (How to List Generic ForeignKey objects)
This is Star ListAPIView so far I have. [ { "user": 1, "content_type": 26, "object_id": 7 }, { "user": 1, "content_type": 26, "object_id": 8 }, { "user": 1, "content_type": 15, "object_id": 5 }, { "user": 1, "content_type": 15, "object_id": 6 } ] Since content_type of the very first object in the array is 26, its referring object is 'Outfit'. For better understanding, I'm providing Star Model. It contains ContentType and object_id field. It uses two fields to refer Generic foreignKey. class Star(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') objects = StarManager() And here is Serializer and View serializers.py class ListStarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('user', 'content_type', 'object_id') views.py class StarListAPIView(generics.ListAPIView): serializer_class = ListStarSerializer def get_queryset(self): qs = Star.objects.filter(user=self.request.user) return qs Both content_type 26 and 15 have each image fields (called outfit_img and cloth_img) for each. To Achieve this, I want to use different Serializer depending on the content_type For example, if content_type is 26, call OutfitListSerializer. If content_type is 15, call ClothListSerializer. I'm building this Star app having help from this link (def create_comment_serializer). (https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework/blob/master/src/comments/api/serializers.py). Thank you so much! -
django inline formset inside a modal - delete field
I am creating an edit view inside a modal. My view consists of a regular django form and inline formset. I have used django-dynamic-formsets for adding and deleting new formsets and this is where I have a problem. When formset is displayed inside a modal, the "remove" field is blank and I cannot delete a formset. For a quick example I'm using Daniel Chen's "Django Inline formsets example: mybook". my html: <button id="myBtn">Open Modal</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ familymembers.management_form }} <thead> <th>One</th> <th>Two</th> <th>Three</th> <th></th> <th><i class="glyphicon glyphicon-remove"></i></th> </thead> <tbody> {% for form in familymembers.forms %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> <input type="submit" value="Save"/> <a href="{% url 'profile-list' %}">back to the list</a> </form> </div> </div> </div> my js: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'formset/jquery.formset.js' %}"></script> <script> $('.formset_row').formset({ addText: 'add formset', prefix: 'familymember_set' }); var modal = document.getElementById('myModal'); var btn = … -
how to add non-ascii characters into filename?
I have problem when I trying to download pdf file, which contain Russian words into filename. I am used pdfkit tool. def get_pdf_document(request, code): host = request.scheme + "://" + request.META["HTTP_HOST"] uri = reverse('documents:view_signed_document', kwargs={'code': code}) + "?is_pdf=true" obj = get_object_or_404(DownloadCode, code=code) options = { 'page-size': 'A4', 'encoding': "UTF-8", 'no-outline': None, 'margin-bottom': '17', 'margin-left': '10', 'margin-right': '10', 'margin-top': '10', 'footer-html': host + reverse('api:pdf-footer', kwargs={'code': code}), } if obj.doc_type == ACTS_TYPE or obj.doc_type == LISTS_TYPE: options['orientation'] = 'Landscape' result = pdfkit.from_url(host + uri, False, options=options) response = HttpResponse(result, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=\"{}-{}.pdf\"'.format(GET_DOC_TYPE[obj.doc_type], code) response['Content-Length'] = response.tell() return response and i have those constant variables: PDF_INVOICE = u"СЧЕТ-ФАКТУРА" PDF_ACT = u"АКТ" PDF_LIST = u"НАКЛАДНАЯ" PDF_PAYMENT = u"СЧЕТ НА ОПЛАТУ" PDF_RECON = u"АКТ СВЕРКИ" PDF_COMMON = u"НЕФОРМАЛИЗОВАННЫЙ" GET_DOC_TYPE = { INVOICE_TYPE: PDF_INVOICE, ACTS_TYPE: PDF_ACT, LISTS_TYPE: PDF_LIST, PAYMENTS_TYPE: PDF_PAYMENT, RECONS_TYPE: PDF_RECON, COMMONS_TYPE: PDF_COMMON, } and my error message: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) and I don't know to how to resolve this problem. pls help -
TemplateSyntaxError at /accounts/profile/
I got an error,TemplateSyntaxError at /accounts/profile/ must be the first tag in the template. I wrote base.html {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% load staticfiles 'bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <p class="navbar-text">HELLO</p> {% if user.is_authenticated %} <p class="navbar-text">{{ user.get_username }}</p> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> profile.html is {% load staticfiles %} {% extends "registration/accounts/base.html" %} {% block content %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </head> <body> <a href="{% url 'kenshinresults'%}">SEE YOUR PHOTO</a> <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <p>SEND PHOTO</p> <input type="file" name="files[]" multiple> <input type="hidden" value="{{ p_id }}" name="p_id"> <input type="submit" value="Upload"> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </body> </html> {% endblock %} I found only base.html was showed accurately, but when I tried base.html inherit profile.html,this error happens.Before,these 2 files are loaded accurately, but when I added href="{% static … -
How do I return this JSON in django without it being escaped?
In my Django project, I am trying to return a JsonResponse but the data being returned is being escaped 'somewhere'. When I run the code through Jupyter Notebook I don't have a problem. My DataFrame structure is: My Django response reads in my DataFrame pickle and processes it like this: def API_FTEs_month(request, storeCode): df1=pd.read_pickle(storeCode+'.pickle') result=(df1.groupby(['Date','Job Role'], as_index=False) .apply(lambda i: i[['Department', 'Team', 'Days']].to_dict('r')) .reset_index() .rename(columns={0: 'Assignments'}) .to_json(orient='records')) return JsonResponse(result, safe=False) I'm not sure why, but the response gets escaped like this: "[{\"Date\":\"2017-12-31\",\"Job Role\":\"Junior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":12.8311126233},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":9.7797036952},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":12.4532628859},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":13.2005991473},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":11.2217690247},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":9.9799650502}]},{\"Date\":\"2017-12-31\",\"Job Role\":\"Senior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":12.3088204188},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":11.6027520428},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":8.4242249342},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":10.2680664459},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":10.7355819544},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":14.4751405746}]},{\"Date\":\"2018-01-31\",\"Job Role\":\"Junior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":9.8390990646},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":7.8840336082},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":7.4098884623},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":6.5804561812},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":7.9109739164},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":7.6766255979}]},{\"Date\":\"2018-01-31\",\"Job Role\":\"Senior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":5.9779944185},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":7.8300778676},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":7.9050436379},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":6.9225874658},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":7.6001780124},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":6.5897367619}]}]" Recreating the attempt in Jupyter Notebook I seem to get valid JSON: Notebook: I was assuming it's something in my to_json() or JsonResponse that is the problem but I have tried inserting other JSON attempts into my JsonResponse such as the following which gives me valid JSON (but not the required structure) without escaping: def nested_dict(): return collections.defaultdict(nested_dict) result=nested_dict() for row in df4.itertuples(): result[row.Index[0]][row.Index[1]][row[1]][row[2]]['sales'] = row.Days json.dumps(result) -
Django: Login inside another login
I'm currently building a site in django. The company that I work for sells "channels" with a preloaded catalogue of products, and a set of users that can use the channel. Those users are provided by the client. In order for our clients to use that channel. They must be asked to provide a set of credentials to log into their channel. For example: www.mysite.com/channel/clienta if client A wants to log into the channel for their user to use it a log in page must appear. Once inside the channel the client's users can use the channel to search for products and view them. If one of the users associate to the channel wants to perform a task or action on any product in the catalogue. That user must log into the channel for that. Hence the login inside another login. My question is how can I do that. The only thing I can think of is giving a user to log into the channel and when a user associated to the channel wants to perform an action logout the user from the channel and log the other user. Any help would be much appreciated. Thanks. -
Can't import Serializer class between two files
File1 and File2 contain Serializer classes for different models I get a import error if File1 imports a Serializer class from File2 and File2 imports a Serializer class from File1 , it only seems to work if only one of the files imports Serializer classes from the other (only can import one way). Is this to prevent circular imports like in django models?, and is there a way to get around this. error: ...\project\src\app\api\serializers.py" ImportError: cannot import name 'SerializerClass' -
Django admin Model name "s"
class Customer(BaseModel): Name = models.CharField(max_length=250, verbose_name="İsim") Surname = models.CharField(max_length=250, verbose_name="Soyisim") Email = models.EmailField(max_length=70, blank=True, null=True, unique=True,verbose_name="E-Mail") Adress = models.CharField(max_length=600, verbose_name="Adres") FaxNumber = models.CharField(max_length=600, verbose_name="Fax Numarası") class meta: verbose_name = "Customer" i have a model as you can but this model name seems with "s" character in django admin panel picture -
django - MySQL strict mode with database url in settings
I'm using a database URL string in my settings like: DATABASES = { 'default': "mysql://root:@localhost:3306/mydb" } When I migrate I get this warning: MySQL Strict Mode is not set for database connection 'default' Now my question: How can I combine the two things? I cannot use the "regular" way to set the database settings with a dictionary because my database url comes from an environment variable. Thx in advance! -
dateutil parse does not correctly parse timezone
Given the following code. See how on line 73, the tzinfo is UTC while on line 74 the tzinfo is tzlocal(). How can I parse a isoformat string and have the timezone be correct? In [72]: import dateutil.parser In [73]: timezone.now() Out[73]: datetime.datetime(2017, 9, 27, 6, 29, 31, 452211, tzinfo=<UTC>) In [74]: dateutil.parser.parse(timezone.now().isoformat()) Out[74]: datetime.datetime(2017, 9, 27, 6, 29, 56, 64495, tzinfo=tzlocal()) -
foreign key in testing django with factory boy doesn't work
I have a problem with foreign key in library factory boy. My test doesn't execute I thinking that the problem in foreign key. I try to test user model which is in user.models that is how my code look like class Task(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') description = models.CharField(max_length=255, verbose_name='Описание') cost = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='Цена') assignee = models.ForeignKey('users.User', related_name='assignee', null=True, verbose_name='Исполнитель') created_by = models.ForeignKey('users.User', related_name='created_by', verbose_name='Кем был создан') def __str__(self): return self.title I test it with factory boy that is how my factory boy class looks like class UserFactoryCustomer(factory.Factory): class Meta: model = User first_name = 'Ahmed' last_name = 'Asadov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 1 balance = 10000.00 class UserFactoryExecutor(factory.Factory): class Meta: model = User first_name = 'Uluk' last_name = 'Djunusov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 2 balance = 5000.00 class TaskFactory(factory.Factory): class Meta: model = Task title = factory.Sequence(lambda n: 'Title {}'.format(n)) description = factory.Sequence(lambda d: 'Description {}'.format(d)) cost = 5000.00 assignee = factory.SubFactory(UserFactoryExecutor) created_by = factory.SubFactory(UserFactoryCustomer) That is the example of my test class ApiModelTestCase(TestCase): def test_creating_models_instance(self): executor = factories.UserFactoryExecutor() customer = … -
azure app service django deploy keep failing
it's been 1 month and I still can't figure out what's wrong with me or app service in azure I used python 2.7 and django 1.11.3, with this requirements.txt beautifulsoup4==4.6.0 certifi==2017.7.27.1 chardet==3.0.4 Django==1.11.5 idna==2.6 olefile==0.44 Pillow==4.2.1 pytz==2017.2 requests==2.18.4 urllib3==1.22 when I deploy with Local Git Repository to Azure Web Service(Python2.7, Windows) it doesn't seems to install the requirements I tried wheel but it doesn't do anything, and via scm powershell I failed to do install any of the requirements, example: Python -m pip install django give me no permission error -
How to retrieve transaction details from paypal using django-paypal standard ipn?
How can i retrieve all of the transaction details from the standard paypal ipn and save it to the database migrated which is the paypal_ipn im using django and i have installed django-paypal and i just followed the tutorial here http://django-paypal.readthedocs.io/en/stable/standard/ipn.html#. I'm a little bit confused what does the signals do in my system? does the signals can save transaction details when the payment is completed? -
Updating an HTML fragment with ajax response Django using CBV(ListView)
So I have a homepage that consists of a base listview which includes all of the objects from my db(as shown in the cbv .all() query). What I wanted to do is include a search filter, hence I thought it would be a good idea to isolate it into a separate "list.html" fragment in order to make it reusable later on. Currently, I have an ajax call that sends information to the cbv and the return is a render to list.html fragment. However, when I visit the homepage, the page doesn't get rendered to begin with. Help or advice would be very much appreciated, thank you again. urls.py urlpatterns = [ url(r'^$', exp_view.DrugListView.as_view() , name = 'drug_list')] here is my CBV template: views.py class DrugListView(ListView): context_object_name = 'drugs' model = Drug template_name = 'expirations/drug_list.html' def get(self, request): if self.request.is_ajax(): text_to_search = self.request.GET.get('searchText') print(text_to_search) return render(request, "expirations/list.html", {'drug':Drug.objects.filter(name__contains = text_to_search).order_by('name')}) else: return render(request, "expirations/list.html", {'drug':Drug.objects.all().order_by('name')}) here is drug_list.html {% extends 'expirations/index.html' %} {% block content %} {% include 'expirations/list.html' %} {% endblock %} {% block javascript %} <script> $(document).ready(function(){ var input = $("#searchText") input.keyup(function() { $.ajax({ type: "GET", url: "{% url 'drug_list' %}", data: {'searchText' : input.val()}, success: function(data){ $("#list_view").load("expirations/list.html") } …