Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Synchronize local CouchDB database with remote CouchDB database when connecting to the internet
The idea is simple, I don't know how the execution is: I'm using CouchDB as an option because it was the only one I found with something like what I need. I have a local application (Python / Django) that writes to a database (CouchDB). The local database should be synchronized whenever possible with the remote database. The connection to the remote database drops a lot so it is important that this web page works locally on the user's computer. Important notes: The database does not have to be exactly CouchDB, it can be another (if there is a better one for this purpose) I am not developing a mobile application, so I will not use a PouchDB, for example. It is actually an offline, but web application, installed on the user's computer. -
psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations
What my settings.py for DB looks like: ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fishercoder', 'USER': 'fishercoderuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } I have created a new and empty db named "fishercoder" this way: psql -U postgres create database fishercoder; ALTER USER postgres with password 'badpassword!'; CREATE USER fishercoderuser WITH PASSWORD 'password'; ALTER ROLE fishercoderuser SET client_encoding TO 'utf8'; ALTER ROLE fishercoderuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE fishercoderuser SET timezone TO 'PST8PDT'; GRANT ALL PRIVILEGES ON DATABASE fishercoder TO fishercoderuser; Then I've imported my other SQL dump into this new DB successfully by running:psql -U postgres fishercoder < fishercoder_dump.sql Then I tried to run ./manage.py makemigrations on my Django project on this EC2 instance, but got this error: Traceback (most recent call last): File "/home/ubuntu/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations I found these three related posts on SO: One, two and three I tried the commands they suggested: postgres=# GRANT ALL ON ALL TABLES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL SEQUENCES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to fishercoderuser; … -
Is javascript date object compatible to python datetime object
For example in python, a date can be something like: 2020-06-19T11:32:16.548109Z, is there a way that i can use to convert this to a javascript Date object? -
Django... How to use different several models in one view function?
Any help??? How can I use many models in one view function? I have "get" query from the form template under Q name... like this: class UserSearchRequestView(TemplateView): model=ForQuery template_name='do_requests.html' def get_results(self): query=self.request.GET.get("q") if query: our_object=ForQuery.objects.filter(query_id__iexact=query) return our_object Now I need to pass this object through the search through three models to get results... I know, I could do something like this: def index(request): company_info = Company.objects.all() director_info = Director.objects.all() context = { 'company_info' : company_info, 'director_info' : director_info, } return render(request, 'index.html', context=context) But it is only if this function is outside of the class... But my function inside of the class already... So it doesn't work in my case... I could do like this: def get_context_data(self, **qwargs): conObject = super(DirDetailView, self).get_context_data(**qwargs) conObject['mcons'] = RequestSell.objects.all() conObject['fcons'] = DirDict.objects.all() return conObject But, then these objects are only good for using them in template? How can I bring several models into one view function, do operations with them and return the result. I'm kind of confused and probably don't see obvious? -
Django MultipleChoiceField how show only one item
I am creating a combobox with multiple choices using the MultipleChoiceField component. Everything works perfectly, but the list that appears in the combo brings repeated the item and subitem. I looked in the documentation but found nothing regarding this problem. As I understand it, the choice parameter requires bringing a tuple. The choice_test() returns [('test0', 'test0'), ('Test1', 'Test1'), ('test3', 'test3'), ...] Is there a way to show only one item? combo_test = forms.MultipleChoiceField( label=_("Combo test"), required=False, choices=choice_test(), widget= autocomplete.Select2Multiple(url='autocomplete_test') ) -
"This Field is Required" even though I am uploading my file
This is a follow up question to my last question: Lists are currently not supported in HTML Input . I have learned that Lists are simply not supported in Django-Rest-Framework browsable API, and I am trying to test my ability to POST data using Postman. The error I am getting is: "This Field is Required" for my BreedImages field even though I am posting it. Here are some pictures: Here are my models: class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos', null=True, blank=True) My Serializers: class ImageSerializer(serializers.ModelSerializer): class Meta: model = BreedImage fields = ['id', 'breedImage'] class BreedSerializer(serializers.ModelSerializer): BreedImages = ImageSerializer(many=True, allow_null=True, required=True) class Meta: model = Breed fields = ['name', 'BreedImages'] My view: class BreedList(generics.ListCreateAPIView): parser_classes = (MultiPartParser,) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None -
Process Text Files with Python Dictionaries and Upload to Running Web Service lab
I want to write a Python script that will upload the feedback automatically without having to turn it into a dictionary. The script should now follow the structure: List all .txt files under /data/feedback directory that contains the actual feedback to be displayed on the company's website. Hint: Use os.listdir() method for this, which returns a list of all files and directories in the specified path. You should now have a list that contains all of the feedback files from the path /data/feedback. Traverse over each file and, from the contents of these text files, create a dictionary by keeping title, name, date, and feedback as keys for the content value, respectively. Now, you need to have a dictionary with keys and their respective values (content from feedback files). This will be uploaded through the Django REST API. Use the Python requests module to post the dictionary to the company's website. Use the request.post() method to make a POST request to http:///feedback. Replace with 35.193.233.100. Make sure an error message isn't returned. You can print the status_code and text of the response objects to check out what's going on. You can also use the response status_code 201 for created success … -
Can i serve media files on production server in Django?
Actually I created a fully functional web app using Django. I don't have much experience to host a Django web app on a production server. But I'm trying. My problem is that I read from a blog that we can't serve media files using Django. We need Amazon S3 server to serve media files to Django. I'm trying to host my Django app on digital ocean with apache server. Is there any way that I can serve media files using Django in production server. Even I don't have a huge budget to buy a space on Amazon S3. What should I do? -
How to add example in swagger field
I am currently using following libraries of django - Django==2.2.4 django-pdb==0.6.2 django-rest-swagger==2.2.0 django-service-objects==0.5.0 django-timezone-field==3.0 django-windows-tools==0.2.1 djangorestframework==3.10.2 djongo==1.2.33 It is running on Python version 3.7.4 The problem that I am facing is I can able to generate body part of API using corapi.Field in Autoschema. class SwaggerSchemaView(APIView): permission_classes = [AllowAny] renderer_classes = [ renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator() schema = generator.get_schema(request=request) return Response(schema) class ParseResume(APIView): permission_classes = [AllowAny] schema = AutoSchema( manual_fields=[ coreapi.Field( "data", required=True, location="body", description='Send Json Data', type="string", schema=coreschema.Object(), ) ] ) def post(self, request): data = request.data response_data = SetConnections.parse_resume(data) return Response(response_data) Now, I can able to generate Swagger view like as follows - enter image description here But I want to add a sample data inside this body part through coreapi.Field like as follows - { "id": "56-df-pt", "fname": "John", "lname": "Doe", "experience": { "employee": "Company X", "period": "1996 - 2002", "engaged_in": [ { "work": "Jr. Manager", "team_size": 5, "time": "Sep. 1996 - Dec. 1998" }, { "work": "Sr. Manager", "team_size": 5, "time": "Jan. 1999 - Dec. 2002" }, ] } How can I add that? I can't change any version of Django or Python at this moment now. -
How Images can be added to HTML in Django, As i tried by static folder but still not getting image on html page
STATIC_URL = '/static/' {% load static %} Why this is not working in my case ... ? -
How do I know if and where my google cloud clogs are getting written
I have added a google-cloud-logging handler to the LOGGING settings of my django app and added it as a handler for my apps logger as below: from google.cloud import logging as google_cloud_logging gcloud_log_client = google_cloud_logging.Client() LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}, "require_debug_true": {"()": "django.utils.log.RequireDebugTrue"}, }, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "apps_log_file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/tmp/apps_logfile.txt", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "gcloud_log": { "level": "INFO", "class": "google.cloud.logging.handlers.CloudLoggingHandler", "client": gcloud_log_client, }, }, # "root": {"handlers": ["console"], "level": "WARNING"}, "loggers": { "apps": { "level": "DEBUG", "handlers": ["console", "apps_log_file", "mail_admins", "gcloud_log"], } }, } When I run this django app locally, the logs from apps logger are getting written to console and to the file as expected. Similarly, when I run this on GAE, I can see the logs on stdout logs. But I am not able to find the logs associated with gcloud_log handler. The stdout logs are not labeled by severity, so I am looking to log as separate google cloud log. The documentation for the google.cloud.logging is not at … -
Get all value selected from bootstrap selectpicker multiselect
Using bootstrap selectpicker for selecting multiple options but when I fetch it using post method I get only the last value selected. However the selected values are displayed properly in the select box. I am using Django framework and when I fetch value using request.POST['selection'] it returns only the last value selected. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> <select class="selectpicker" name="selection" multiple data-live-search="true"> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> -
Django, queryset to find count in manytomany field
I have below model, class Blog(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=200) class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) How do I find authors count ? Let us say I have an Entry object as Entryobject (Entryobject = Entry.objects.filter(blog__name='a') ), I tried as below but got attribute error. Entryobject.authors.count() # got error here Also please let me know how can I query list of authors in Entryobject . -
Unable Force Download File in Django HttpResponse (HTML/ PDF)
I am trying to output HTML or PDF files for download. I have written few lines of code to generate html & PDF file from a template and download it. However, my code is working for Chrome browser only. When I try to download it from other browser (e.g. DuckDuckGo) I am getting my current page (i.e. roll.html) downloaded instead of the file (i.e. file rendered from html_output_template.html) which I want to export. Here's the code I am trying: views.py def generate_html(request, res): cdict = {'res':res, 'date':datetime.date.today()} if request.method == 'POST': inv_form = InvoiceInfoForm(data= request.POST) if inv_form.is_valid(): inv_data = inv_form.cleaned_data cdict = {'res':res, 'inv_data':inv_data, 'date':datetime.datetime.today().strftime("%d %h %Y")} template = get_template('app_name/html_output_template.html') html = template.render(cdict) response = HttpResponse(html, content_type='application/force-download') filename = "Inv_%s.html" %(datetime.datetime.today().strftime("%d_%h_%y_%H_%M_%S")) content = "attachment; filename= %s" %(filename) response['Content-Disposition'] = content return response def MyView(request): """Some Calculations Here""" if 'download_pdf' in request.POST: if inv_form.is_valid(): return generate_pdf(request, res) elif 'download_html' in request.POST: if inv_form.is_valid(): return generate_html(request, res) return render(request,'app_name/roll.html',context=cdict) Sample of html template: html_output_template.html {% load staticfiles %} <!-- Few Lines here --> <tr> <td style="text-align:left">1</td> <td style="text-align:left">{{inv_data.description}}</td> <td style="text-align:right">{{res.rate_per_gram}} {{res.rate_kilo_gram}}</td> <td style="text-align:right">{{res.wgt_of_goods}}</td> <td style="text-align:right">{{res.total_amount}}</td> </tr> I feel there is some problem with my HttpResponse which is getting auto corrected in Chrome … -
Avoid making multiple Django database calls
I would like to query my Django database once and return a Queryset (assigned the name 'codes'), which I can iterate over to obtain each instance's 'internal_code' attribute without making further calls to the database. Here is my code, but I am unsure as to whether I am querying the database each time I use 'get' on the Queryset, and how I can avoid this: codes = models.RecordType.objects.all() permanent = sorted( [(codes.get(industry_code=category.value).internal_code, self.labels.get(category, category.name)) for category in enums.Category]) -
Render the key value of a dictionary based on an event in Django
I have two dropdowns in my .html file of Django app namely: <select class="form-control" id="exampleFormControlSelect1"> <option>op1</option> </select> <select class="form-control" id="exampleFormControlSelect2"> <option>opt1</option> </select> A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template but no luck.How can I implement it? -
Filter model object by difference in days
My model has a date field and i want to filter the model by the last 7 days. class Count(models.Model): task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE) start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) time_spent = models.PositiveIntegerField() deleted = models.BooleanField(default = False) class Meta(): ordering = ['accesses'] def __str__(self): return f'{self.task.department} - {self.accesses.first().user} [{self.time_spent} min]' def stamped_date(self): if not self.start_time: return self.accesses.first().date return self.start_time def users(self): return list(set(map(lambda x: x.user, list(self.accesses.all())))) I need to filter every count that has "stamped_date" in the last 7 days. What i tried to do (in the model): def daysBy(self): return (datetime.now() - self.stamped_date()).days to filter like this: Count.objects.filter(daysBy__let = 7) However, datetime.now() requires a timezone object, otherwise will throw the follwing error: TypeError: can't subtract offset-naive and offset-aware datetimes I'm also feeling this might not be the most correct way of achieving my goal, please correct me with a better way. Or.. give me a way of inserting a timezone object related to the TIME_ZONE setting. -
Static files are not fetching in django
My settings description. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/css') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Also, I had added static files to urls.py urlpatterns += staticfiles_urlpatterns() My HTML template {% load static %} <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Things I eat</title> </head> <body> <h1> Hello world</h1> </body> findstatic command output: > python manage.py findstatic styles.css Found 'styles.css' here: /project_name/static/css/styles.css I use django == 3.0.7 I followed advice from similar questions [1,2,3] But my static files are not fetching while rendering. Any advice for debugging? -
CORS-Error when using django as backend for ionic app
I'm using Django Rest Framework as a backend for my Ionic app. I set up the API with JWT and with postman everything works fine. As soon as I try making a API call from my Ionic app I get the following error messages: Error 1 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: header ‘password’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). Error 2 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: CORS request did not succeed). I run my django app on a apache2 webserver. django-cors-headers is installed, added to installed_apps, added to the middleware and CORS_ORIGIN_ALLOW_ALL = False In my Ionic app the request looks like this: Service fetchMovies() { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.authService.getToken()}`, 'username': 'USERNAME', 'password': 'PASSWORD' }) } return this.http.get(this.url, httpOptions).pipe(tap(resData => { console.log(resData); })); } I get the token like this: getToken() { return this.http.post('https://www.mywebsite.com/api-token', this.params); } And I use the service as follows: ionViewWillEnter() { this.moviesServcie.fetchMovies().subscribe(); } Does anyone have an idea what I'm doing wrong? If you need more information feel free to write a comment! … -
How to access variables class in a child function in Python/Django
Like I said in title I'm trying to access variables class in a child function. In the class I import Json data from a file and I convert them in dict then in variables so far no worries. but I can't access my variables in JsonForm function below to render them in the Form, I've tried many solution with init and self but any works there is my code : class UpdateSwitch: # folder location of my Json data CWD = os.getcwd() JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, 'mod_switch/EmailDataScript/mailData.json') # I store the data in this viariable CONFIG_PROPRETIES = {} # data are loaded and converted to a dict try: with open(JSON_CONFIG_FILE_PATH) as data_file: CONFIG_PROPRETIES = json.load(data_file) except IOError as e: print (e) print ('IOError: Unable to open mailData.json') exit(1) print (CONFIG_PROPRETIES) # OUTPUT something like this : {'data': 'somedata', 'data2': 'somedata2', 'data3':'somedata3', 'data4': 'somedata4', 'data5': 'somedata5', 'data6': 'somedata6'} # Convert the dict keys to variables and dict values to value of these variables for key,val in CONFIG_PROPRETIES.items(): exec(key + '=val') # And there is what I get(everything work) : data, data1, data2, data3, data4, data5, data6 def JsonForm(request): if request.method == "POST": stackForm = JsonStacksForm() stackForm.Meta.fields = { "ip" : … -
Django: ZipFile does not recognize file as zip: raised BadZipFile or AttributeError
I am trying to handle ZipFile. I have archived 6 images as "images.zip". >>> zf=zipfile.ZipFile('images.zip') >>> zipfile.is_zipfile(zf) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 183, in is_zipfile result = _check_zipfile(fp=filename) File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 169, in _check_zipfile if _EndRecData(fp): File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 241, in _EndRecData fpin.seek(0, 2) AttributeError: 'ZipFile' object has no attribute 'seek' Also when I try to open my file as File in django I get an error. from django.core.files import File f = File(open('images.zip')) >>> zip=ZipFile(f) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1100, in __init__ self._RealGetContents() File "/home/admin1/miniconda3/envs/kuptam_env/lib/python3.6/zipfile.py", line 1168, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file It seems that with the file all is fine, I can unpack it, all images are fine. I can also access other zipfile atributes and functions eg. >>> zf <zipfile.ZipFile filename='images.zip' mode='r'> >>> zf.namelist() ['img6.jpg', 'img5.jpg', 'img4.jpg', 'img4.jpeg', 'img3.jpg', 'img2.jpg', 'img1.jpg'] >>> zf.infolist() [<ZipInfo filename='img6.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=97335 compress_size=97217>, <ZipInfo filename='img5.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=83314 compress_size=83030>, <ZipInfo filename='img4.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=133511 compress_size=132992>, <ZipInfo filename='img4.jpeg' compress_type=deflate filemode='-rw-rw-r--' file_size=154011 compress_size=153871>, <ZipInfo filename='img3.jpg' compress_type=deflate filemode='-rw-rw-r--' file_size=119871 compress_size=119024>, <ZipInfo filename='img2.jpg' compress_type=deflate filemode='-rw-rw-r--' … -
Django Rest Framework is detecting AnonymousUser on PUT requests
I have this viewset class OrderItemViewSet(viewsets.ModelViewSet): serializer_class = OrderItemSerializer def get_queryset(self): print('Current User', self.request.user) return OrderItem.objects.filter(order__owner=self.request.user.profile) take note of the print('Current User', self.request.user) I have used that to identify the root of the problem. urls.py router.register('order_items', shopping_api.OrderItemViewSet, 'order_items') So far so good... But when I make a PUT request; const response = await fetch(api.authurl+'/order_items/'+order_item.id+'/', { method: 'PUT', headers: api.httpHeaders, body: JSON.stringify(order_item) }); This error shows up AttributeError: 'AnonymousUser' object has no attribute 'profile' The print statement identifies these for a GET then a POST request respectively: [19/Jun/2020 20:17:22] "GET /sellers/3/ HTTP/1.1" 200 196 Current User AD [19/Jun/2020 20:17:30] "GET /order_items/ HTTP/1.1" 200 1060 Current User AnonymousUser So I have reason to believe that when I make a get request, the authenticated user is detected, but with a PUT it's suddenly Anonymous. I doubt I have to make frontend authentication right? e.g having Authorization with a token in my headers in the request. Since I have that GET request doing fine. -
Need to get all permissions for groups assigned to a custom table
We are using the standard contrib auth app in Django, which, of course, allows permissions to be assigned directly to users, and/or to groups, with the groups then being assigned to users. Before I knew about the get_all_permissions() method of the User object, I had my own method that returned all permissions for a user using this statement: user_permissions = Permission.objects.filter(Q(user=user) | Q(group__user=user)).all().distinct() I'm sure I found that code after searching about how to get all permissions, and just copy/pasted it into my code. We now want to add groups at a different level in our site. We assign users to projects via the ProjectUser model, which essentially has foreign keys to project and user. We want to add group to that model so that, for example, a user (developer) could be "project lead" on one project, but just a "contractor" on another. I added a many-to-many field named "groups" to the ProjectUser model, but now I'm not sure what the statement equivalent to the one shown above would be to get all project-level permissions. -
Can't create object in django
I'm trying to make django app somthing like instagram where you can post images. I have my code with no errors but can't create object post. I can display template in html but after i fill the fields and click button submit nothing happend besides reloading site. models.py: from django.db import models from django.contrib.auth import get_user_model import datetime # Create your models here. User = get_user_model() class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) image = models.ImageField(upload_to='media') caption = models.TextField(blank=True, null=True) date_of_publication = models.TimeField(blank=True, default=datetime.datetime.now()) forms.py: from django.forms import ModelForm from .models import Post #POST FORMS.PY class PostForm(ModelForm): class Meta: model = Post fields = ['user', 'image', 'caption'] exclude = ['user'] views.py: from django.shortcuts import render from .forms import PostForm from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect # Create your views here. @login_required def create_post(request): if request.user.is_authenticated: if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return HttpResponseRedirect('/about/') else: form = PostForm() return render(request, 'posts/create_post.html', {'form':form}) -
Getting an error: got an unexpected keyword argument 'version'
I was doing the Django haystack tutorial, and when I run the search query, I get the error __call__() got an unexpected keyword argument 'version'. This error is coming from Django. I am fairly new to Django, and I'm not sure what all to add to help debug this. Also, in engine, I am using haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine, and am using ElasticSearch v7