Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Custom Sequence Format
I would like to create custom sequence like "PO-0001" for Purchase Order, "SO-0001" for Sales Order, etc. I have try something like this: class Requisitions(models.Model): number = models.CharField(max_length=20, verbose_name='Number') transDate = models.DateField(verbose_name='Date') businessUnit = models.ForeignKey(BusinessUnit, verbose_name='Unit') division = models.ForeignKey(Division, verbose_name='Division') remarks = models.TextField status = models.IntegerField(verbose_name='Status') def save(self, *args, **kwargs): letter = 'REQ-' lastNumber = 1 self.number = '%s%03d'(letter,lastNumber) super(self.__class__, self).save(*args, **kwargs) i got some errors in my admin page when i save new record like this: 'str' object is not callable Request Method: POST Request URL: http://localhost:8000/admin/procurement/requisitions/add/ Django Version: 1.11.3 Exception Type: TypeError Exception Value: 'str' object is not callable how i solve that error..? thanks for your help regards, -
Django update model with unique field
I am trying to allow users to edit a topic. Whenever I try to update the topic I get the following error: Title: Topic with this Title already exists. # views.py ... def post(self, request, title): topic = Topic.objects.all().get(title=title) form = self.form_class(request.POST) if (form.is_valid()): topic.update( title=form.cleanded_data('title'), tags=form.cleanded_data('tags'), ) return redirect('/topics/' + topic.title) else: return render(request, self.template_name, {'topic': topic, 'form': form}) # models.py class Topic(models.Model): ... title = models.CharField(max_length=256, unique=True) ... -
Using Ajax to post a form, no response
Django version 1.11.1 I have a form on my template, wanna use ajax to post it which can only change the form, my form code like: <form action="" class="poster" id="posterForm"> {% csrf_token %} <input type="file" accept="image/png,image/gif,image/jpeg" id="img_input" class="file_btn"> <input type="button" class="file_front_btn" value="选择图片" name="image"> <input type="text" name="title" id="title" class="title_area" placeholder="标题(不超过20字):"> <span class="img_root">已选图片:<span id="img_root" class="hidden">无</span></span> <textarea name="content" id="content" name="content" class="content_area" placeholder="输入内容(不超过2000字):"></textarea> <div id="title_error"></div> <div id="content_error"></div> <input type="button" class="submit" id="submitBtn" value="发布"> <div id="img_error"></div> And my jQuery: $(function(){ $('#submitBtn').on('click', function(){ $.ajax({ cache: false, type: "POST", url:"{% url 'community:poster' %}", data:$('#posterForm').serialize(), async: true, success: function(data) { if(data.status == 'success'){ $('#posterForm')[0].reset(); alert("发布成功") }else if(data.status == 'fail'){ $('#img_error').html(data.msg) } }, }); }); }) And my views is: class PosterView(View): def post(self, request): poster_form = PostForm(request.POST) if poster_form.is_valid(): poster = poster_form.save(commit=True) return HttpResponse("{'status':'success'}", content_type='application/json') else: return HttpResponse("{'status':'fail', 'msg':{0}}".format(poster_form.errors), content_type='application/json') I use a ModelForm to commit the form, the forms is: class PostForm(forms.ModelForm): class Meta: model = Posts fields = ['image', 'title', 'content'] I can't see where the problem is, but when I click the submit button, nothing happened, no fail status. -
What the right way to make this kind of complicated request over ORM?
Lets say we have follow models: class Bundle(models.Model): # ... class Order(models.Model): # ... bundle = models.ForeignKey( Bundle, on_delete=models.CASCADE, verbose_name=_('бандл'), related_name='orders') class CommentThread(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments", on_delete=models.SET_NULL) content_type = models.ForeignKey( ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) object_pk = models.TextField(_('object ID')) content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") datetime = models.DateTimeField(verbose_name=_('last time thread was read'), default=None, null=True, blank=True) class Comments(models.Model): content_type = models.ForeignKey( ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments", on_delete=models.SET_NULL) content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") object_pk = models.TextField(_('object ID')) text = models.TextField(max_length=COMMENT_MAX_LENGTH) submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True) By design, we may attach comments to everyone models, but in this case, we attach comments to Bundle over content type \ object id generics. To implement "read \ unread comments for each user in the thread" we use CommentThread model with the same content type object generic (I know, this is terrible idea, but this is kind of legacy code). If Bundle instance have attached comments with comment.submit_date > comment_thread.objects.filter(user=user, content_object=bundle).datetimethis mean comment is new for current user. So, I need to get list of Orders with new comments for user, ordered by time of submitting last comment, attached to Order.bundle with count of this … -
Ensuring calling application is authorized without username and password with Outh Toolkit and DRF in django
I have an app that is well functioning. I am using Rest framework with auth toolkit. I have a mobile application with its own client id. During login, I am asked to provide client id, user name and password, which is fine for the most portions of the application. For registration, which assumes the member is not registered and not trying to login, does not expect Bearer Token. With that information missing, how would I know that in fact the calling application is what it claims it is or that is list of allowed applications? -
Display images in stored in ImageField with django templates
I'm in in production environment about to fully deploy my app using digitalocean but i got this little problem. I have been trying to display user uploded images but they dont seem to display even though they get uploaded and saved here is my code settings.py STATIC_ROOT = '/home/kingiyk/stylplus/static/' STATIC_URL = '/static/' MEDIA_ROOT = '/home/kingiyk/stylplus/static/' MEDIA_URL = '/media/' Image model (models.py) class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=2000) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='/home/kingiyk/stylplus/static/') description = models.TextField(blank=True, null=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) class Meta: ordering = ('-created',) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', args=[self.id, self.slug]) please place more emphasis on imagefield(upload_to) nginx conf server { listen 80; server_name 67.207.87.22; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/kingiyk/stylplus/static/; } location /media/ { alias /home/kingiyk/stylplus/media/; } location / { include proxy_params; proxy_pass http://unix:/home/kingiyk/stylplus/stylplus.sock; } } views.py def image_detail(request, id, slug): image = get_object_or_404(Image, id=id, slug=slug) comments = image.comments.all() if request.method == 'POST': comment_form = CommentForm(data=request.POST) #if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.image = image new_comment.user = request.user new_comment.save() else: comment_form = … -
Best practice for storing auth tokens in VueJS?
My backend is a REST API served up by Django-Rest-Framework. I am using VueJS for the front end and trying to figure out what is the best practice for doing authentication/login. This is probably terrible code, but it works (in a component called Login.vue): methods: { login () { axios.post('/api-token-auth/login/', { username: this.username, password: this.pwd1 }).then(response => { localStorage.setItem('token', response.data.token) }).catch(error => { console.log("Error login") console.log(error) }) this.dialog = false } } Does it make sense to use localStorage this way? Also, I'm wondering when the user wants to sign out, and I call /api-token-auth/logout, do I still need to remove the token from localStorage? It's not actually clear to me what goes on with the tokens either on Django's end or the browser/Vue. -
ModuleNotFoundError: No module named 'xyz'
Running Python3.6.2. My code in process_sqs_messages.py up to line 3: __author__ = 'Chris' import boto3 from xyz.settings import SQS_QUEUE_NAME Here is my stacktrace: Traceback (most recent call last): File "bin/process_sqs_messages.py", line 3, in <module> from xyz.settings import SQS_QUEUE_NAME ModuleNotFoundError: No module named 'xyz' Directory structure: Project | +-- bin | | | +-- process_sqs_messages.py | +-- xyz | | | +-- __init__.py | +-- settings.py My installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'xyz', ] Anyone know why i'm getting this error? -
How efficient is it to order by distance (entire table) in geodjango
Lets say I have the following data model Person(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) location = models.PointField(srid=4326) Now lets say I have an app that makes queries to this django backend, and the only purpose of this app is to return a list of registered users (in paginated form) from closest to farthest. Currently I have this query in mind # here we are obtaining all users in ordered form current_location = me.location people = Person.objects.distance(current_location).order_by('distance') # here we are obtaining the first X through pagination start_index = a end_index = b people = people[a:b] Although this works, it is not as fast as I would like. I have some concerns over the speed of this query. If the table were large (1 million+) then wouldn't the database (Postgres SQL w/ PostGIS) have to measure the distance between current_location and every location in the database before performing an order_by on that subsequently 1 million rows? Anyone have any ideas on how to properly return nearby users ordered by distance in an efficient manner? -
Django Related_name - still throws error
I'm making a website where the Auth.User is extended by a Userprofile where it has a foreign key to the User itself aswell as a key to user who invited the user. I am using related_name for both but it throws me an error: ERRORS: <class 'account.admin.UserProfileInline'>: (admin.E202) 'account.UserProfile' has more than one ForeignKey to 'auth.User'. Heres model: class UserProfile(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE, related_name="user") invited_by = models.OneToOneField(User, related_name="invited_by") bought = models.ManyToManyField(product, blank=True) def __str__(self): return str(self.user) Why does it still say that i have to many foreign keys? If i would change the name to a invalid related_name then it says that i need to add a correct one. I dont see my error... -
Trying to build a webpage in Django that displays a chessboard using chessboard.js
I'm trying to build a chess website in Django. Right now I'm just trying to get a page that displays a chessboard using the chessboard.js Javascript library, whose directory structure is: chessboard -css -js -img It seems that typically, in order to use chessboard.js to display a chessboard in HTML, you have to store the HTML file in the chessboard folder, then link the js and css files, like this: <head> <link rel="stylesheet" href="css/chessboard-0.3.0.css" /> <script src="js/jquery-1.10.2.min.js"> </script> <script src="js/chessboard-0.3.0.js"> </script> </head> <body> <div id="board1" style="width: 400px"></div> <script> var board1 = new ChessBoard('board1', 'start'); </script> </body> If you wanted to store your HTML file in a separate directory, you would have to alter the chessboard-0.3.0.js file, so that when it appends CSS stylesheet and image links to the HTML file the paths are correct relative to the HTML file's location. Typically in a Django app you store any HTML in a templates directory and any static files in a separate static directory. That's what I'm doing here, so instead of the above HTML I'm using this (test.html): {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>Chess</title> <link rel="stylesheet" href="{% static 'css/chessboard-0.3.0.css' %}"> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="{% static 'js/chessboard-0.3.0.js' %}"></script> </head> … -
Django cached page: generate cache key for graphene query (GAE)
I want to be able to generate cache keys for whatever is being queried via the graphQL gui by the client. It woudn't make sense to do something like cache.set() because I simply have too many fields that could be queried and I'm unable to predict which ones will be queried. How could I generate cache keys for all content that queried? On my view, I have the following: class EVGraphQLView(StaticApiKeyOrInternalMixin, GraphQLView): """GraphQL view for clients.""" def dispatch(self, request, *args, **kwargs): self.request = request self.kwargs = kwargs self.object = self.get_object() return GraphQLView.dispatch(self, request, *args, **kwargs) def get_object(self): if not hasattr(self, '_object'): self._object = super(EVGraphQLView, self).get_object() return self._object And on urls file: urlpatterns = [ url(r'^igraphql', cache_page(60 * 15)(GraphQLView.as_view(graphiql=True))), ] It might help to mention that I am using GAE, so these are my settings: CACHES = { 'default': { 'BACKEND': 'ev_utils.cache.GoogleAppEngineMemcachedCache', 'TIMEOUT': 3600 } } None of this has worked, I've been looking through documentation but nothing seems to help. -
You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field
Could not resolve URL for hyperlinked relationship using view name "listinsurant-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. How to properly configure the model with a foreign key? Thank you models.py from list_insurant.models import ListInsurant from list_insurers.models import ListInsurers from django.db import models class Product(models.Model): id = models.AutoField(primary_key=True) treaty_number = models.IntegerField() insurant = models.ForeignKey(ListInsurant) insurers = models.ForeignKey(ListInsurers) class Meta: db_table = 'test_table' serializers.py from products.models import Product from rest_framework import serializers class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ( 'treaty_number', 'insurant', 'insurers' ) views.py from rest_framework import viewsets from products.serializers import ProductSerializer from products.models import Product class ProductViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Product.objects.all() serializer_class = ProductSerializer urls.py from django.conf.urls import url, include from rest_framework import routers from products.views import ProductViewSet from list_insurant.views import ListInsurantViewSet from list_insurers.views import ListInsurersViewSet from django.contrib import admin router = routers.DefaultRouter() router.register(r'product', ProductViewSet, 'product') router.register(r'list_insurant', ListInsurantViewSet, 'list_insurant') router.register(r'list_insurers', ListInsurersViewSet, 'list_insurers') urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] -
Django - how to capture the selection user has made on frontend
I'm trying to build a dashboard and want to update the graphs based on selection user makes. For example if a user selects company A and click on button 'Update', the code captures that change, query data based on new selection and pass it on again to frontend. I have been able to write most of the code where I can query database based on the selection. But I'm not sure how to capture the user selection and pass on to views.py from the frontend. Models: class Airline(models.Model): name = models.CharField(max_length=10, blank=True, null=True) code = models.CharField(max_length=2, blank=True, null=True) class FinancialData(models.Model): # All units in millions airline = models.ForeignKey(Airline) financial_year = models.ForeignKey(Year) mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2) regional_revenue = models.DecimalField(max_digits=7, decimal_places=2) other_revenue = models.DecimalField(max_digits=7, decimal_places=2) Views.py: class ListAirlineYearFinancialData(generics.ListAPIView): serializer_class = FinancialDataSerializer airline_id = Airline.objects.filter(pk=1) # pk=1 is just a placeholder, but want to change based on selection queryset = FinancialData.objects.filter(airline_id=airline_id) queryset_filtered = queryset.filter(financial_year_id=1) def airline_dashboard(request): airline_list = Airline.objects.all() year_list = Year.objects.all() return render(request, 'dashboard/company_page.html', {'airline_list': airline_list, 'year_list': year_list}) def get_queryset(self, *args, **kwargs): return self.queryset_filtered Urls.py url(r'^$', views.ListAirlineYearFinancialData.airline_dashboard, name='airline_dashboard'), HTML <form action="" method="GET"> {% csrf_token %} <select> {% for airline in airline_list %} <option> Primary Key: {{ airline.pk }} </option> {% endfor %} … -
Django: is there a way to load templates in nested folders?
in this moment I have an app that has over 100 template files like this: -app/ --templates/ ---template1.html ---template2.html --- ... ---template100.html But I want to separete this files in some folders, like this: -app/ --templates/ ---masters/ ----master1.html ----master2.html ---components/ ----component1.html ----component2.html ---others/ ----other1.html ----other2.html Question: is there a way to load templates from folders inside the template folder or all templates must to be located in the template folder? -
How to use django-allauth with steam OpenID in Django?
I have been looking for information in the documentation, but obviously there is only for OpenID. Has anyone implemented it before with this library? -
How to store a large amounts of photos and videos using Django
I have a huge desire to create a website that hosts a bunch of educational videos and photos and I'd like to write it in Django, but I'm not sure how to go about it. I have 3months of Django, and year+ of HTML/CSS/JS/jQuery/Bootstrap/SQL under my belt. With Django I have created several mini projects, but nothing this serious. I assume that this is feasible, but don't know which tools I should consider. What will be the best place for storing uploaded images and videos using Django as backend? Should Include Celery, Redis and AWS S3 in my project? I plan to host my project on digitial ocean using their standard $10/month plan, does anyone think/know if this will be enough to cover 5k users and their uploaded data? Sorry guys I know this is a lot of questions ( and you dont have to answer all), but this is bugging me alot and before starting the actual coding I want to plan everything properly to limit any chances for failure. Any suggestions/pointers much appreciated. -
Django save and retrieve data to / from model
Trying to write a function that will keep a specific symbol on a game i am developing, when it shows up. The following piece of code runs on every "spin". The problem is that after every spin, i only get the new "symbols that i am interested in" and not the ones from the previous "spins"! Can anybody show me what i am doing wrong? I've also double-checked that i don't get any errors for the fields' existence or anything. My snippet is: holdWild = [] tmptmp = [] # For reel for reel in range(0, len(game_dict['return_reels'])): # For row for row in range(0, len(game_dict['return_reels'][reel])): # If my current position's symbol is 12 if int(game_dict['return_reels'][reel][row]) == 12: # Load model's field holdTemp (if any) in to tmptmp list tmptmp = json.loads(save.holdTemp) # Load model's field previous holdedPositions (if any) in to holdWild list holdWild = json.loads(save.holdedPositions) # If current number (combined) is not in tmptmp if (int(str(reel)+str(row)) not in tmptmp): # Append the reel and the row in holdWild for fill in range(0, 2): if fill == 0: holdWild.append(int(reel)) else: holdWild.append(int(row)) # Save holdWild in model's holdedPositions field save.holdedPositions = json.dumps(holdWild) # Append the combined coordinates to tmptmp list tmptmp.append(int(str(reel)+str(row))) … -
Django how to order queryset based on filtered many to many field?
Hi all i'm trying to figure out how to order a queryset based on a manyToMany field but I need to filter that field as well. Here is the exact problem. qs = Drink.objects.all() I want to order this queryset by a related field ingredientsuserneeds Models: class IngredientsUserNeeds(models.Model): user = models.ForeignKey(User, blank=True, null=True) drinks = models.ManyToManyField(Drink) count_need = models.IntegerField(default=0) class Drink(models.Model): name = models.CharField(max_length = 1000, null=True, blank=True) user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) In a DRF list view, I want to order the queryset by the drink's ingredientuserneeds_set but filtered by the user which will return a queryset that is of length one, finally ordering by that single object's count_need in the queryset. It would be sorta like qs = qs.order_by('ingredientsuserneeds_set__filter(user=user)__first()__count_need') But clearly, you cant do what i typed. Any ideas? -
How to unittest auth pages in Django 1.7
How do you unittest test auth pages Django 1.7? I had a unittest in Django 1.6 that confirmed some custom username validation rules for the auth.User model, by browsing to the /admin/auth/user/add page and attempting to enter an invalid username. However, this test fails in Django 1.7 because in the unittest, no /admin/auth/* URLs are available, causing a 404 error. Oddly, when I run the project in the normal devserver, all auth paths are present. My urls.py is a the standard: from django.conf.urls import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), ] And my unittest simply does: client = Client() response = client.get('/admin/auth/user/add/') print(response) Yet the error page returned shows: Page not found (404) Request Method: GET Request URL: http://testserver/admin/auth/user/add/ Using the URLconf defined in alphabuyer.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^admin/ ^login/$ [name='login'] ^admin/ ^logout/$ [name='logout'] ^admin/ ^password_change/$ [name='password_change'] ^admin/ ^password_change/done/$ [name='password_change_done'] ^admin/ ^jsi18n/$ [name='jsi18n'] ^admin/ ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ [name='view_on_site'] ^__debug__/ ^(?P<slug>[a-zA-Z0-9\-_]+)/$ The current URL, admin/auth/user/add/, didn't match any of these. If I also print out my INSTALLED_APPS, it shows django.contrib.auth is there. Why is my unittest unable to access any add-on admin URLs? -
Specify Authentication Backend for Multi-Tenant Environment
I understand Django supports multi-tenancy by looping through all of the backends in the settings.py DATABASES object and attempting to get a username and password match. Rather than loop through all the backends, I'd like to customize the authenticate method such that I can specify the backend of which to authenticate. So this method def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): would look something like this. def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backend('contoso'): Any tips or suggestions greatly appreciated. -
Using a model's ID as a default for another field
Or can you do this? This won't necessarily be the end result model (as it kinda illogical irl), but whilst creating this model what I'd like to do is have the default value of the two parents of a person be the person itself, and so use it's own ID as the parent reference. At this point the AutoField for the ID is fine. Unless I need to change it to facilitate what I'm looking to do. Understandably I'll get the 'self' error migrating the below, but it helps describe my example: class Person(models.Model): dtob = models.DateTimeField(blank=False, verbose_name="Date of birth", default=datetime.now) dtod = models.DateTimeField(blank=False, verbose_name="Date of death", default=datetime.now) creationdate = models.DateTimeField(blank=False, verbose_name="Creation date", default=datetime.now) BLOOD_TYPE_CHOICES=( ('O+', 'O Positive'), ('O-', 'O Negative'), ('A+', 'A Positive'), ('A-', 'A Negative'), ('B+', 'B Positive'), ('B-', 'B Negative'), ('AB+', 'AB Positive'), ('AB-', 'AB Negative'), ) bloodtype = models.CharField(blank=False, verbose_name="Blood type", max_length=3, choices=BLOOD_TYPE_CHOICES, default='O+') parentA = models.IntegerField(blank=False, verbose_name="Parent A", default=self.id) parentB = models.IntegerFiled(blank=False, verbose_name="Parent B", default=self.id) All help and comments appreciated. -
how to post an image to django with ajax
I have a django model class like this: class Location(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) create_date = models.DateTimeField('date added', auto_now_add=True) modify_date = models.DateTimeField('date modified', auto_now=True) name = models.CharField(max_length=200) image_file = models.ImageField( upload_to=get_image_filename, null=True, blank=True) And the rest framework installed. I can post and create new locations via ajax (from the webpage) like this: var config ={ url: LOCATIONS_URL, type: 'POST', data :{ name: 'new_name', }, headers: { "X-CSRFToken": getCookie("csrftoken") }, success: function (context){console.log('success', context);}, error: function (context){console.log('errror');}, } $.ajax(config); getCookie("csrftoken") is a function that gets the correct CSRF value. This works. Now I want to post an image via ajax to the Django database. I tried various things for example: var alt_logo = new Image(); var file; alt_logo.addEventListener('load', function() { file = new File([alt_logo], "filename.png", {type: "image/png", lastModified: new Date()}); var formData = new FormData(file); var config ={ url: LOCATIONS_URL, type: 'POST', data :{ name: 'testname', image_file: formData, }, contentType:false, cache: false, processData:false, headers: { "X-CSRFToken": getCookie("csrftoken") }, success: function (context){console.log('success', context);}, error: function (xhr,ajaxOptions, thrownError)console.log( "Error: " + thrownError );console.log( "Status: " + status );}, }) alt_logo.src = 'path/to/my/default_logo.png'; } $.ajax(config); But I always get the error "415 Unsupported Media Type". After googleing around I tried to send the data … -
Display a global message instead of a local message
I know how to display a 'bound' message on a form with def clean_ref1_fullname(self): value = self.form.cleaned_data.get('ref1_fullname', '').title() if value in (None, ''): raise ValidationError( _('"Reference 1 - Fullname" is required') ) return value def clean_ref1_fullname(self): value = self.form.cleaned_data.get('ref1_fullname', '').title() if value in (None, ''): raise ValidationError( _('"Reference 1 - Fullname" is required') ) return value It will display a message on a specific field. I would like to display a global message. How could I do that? Assume this form is simply ExampleForm. -
How to serve a PDF which is fetched from a third-party API in Python/Django?
I'm fetching a PDF from a third-party API and I'm getting the file contents as string back from the API. I'm trying to serve it in the browser but the file is blank for some reason. It shouldn't be. Below is my code: # This returns the pdf bytes as string document = get_document() response = HttpResponse(document, content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response What am I doing wrong? Thanks!