Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django- Validate form and send email using FormMixin
I am creating a django website and trying to validate a form. The same page also uses Listview to display a list of my recent blog post. My forms.py is : from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) message = forms.CharField(required=True) My views.py is : You can ignore the part containing ListView (including the Post include, queryset, template_name) because that part works fine. from django.shortcuts import render from .forms import ContactForm from django.views.generic.edit import FormMixin from blog.models import Post from django.views.generic import ListView class PostListAndFormView(FormMixin,ListView): queryset = Post.objects.all().order_by("-date")[:2] template_name = 'personal/index.html' form_class = ContactForm success_url = 'success.html' def form_valid(form): user = User.objects.create_user( name=form.cleaned_data['name'], email=form.cleaned_data['email'], message=form.cleaned_data['message']) return super(PostListAndFormView, self).form_valid(form) My HTML is : <form method="post"> {% csrf_token %} {{ form }} <input id="submit" type="submit" value="SEND MESSAGE" /> </form> The problem here is that after submitting the valid form it doesnt direct to the success url. Am I missing some inports here or am I missing some codes ? Should I make changes to some codes ?? Please help me...I also want to send email with the information from the valid form -
Django: Use post() in UpdateView to populate form's fields with instance's existing field values
I have trouble getting the current instance's fields on my UpdateView. How do I get the specific instance based on its id? views.py class ShowUpdate(UpdateView): model = Show fields = ['description', 'season', 'episode'] def post(self, request, **kwargs): request.POST = request.POST.copy() request.POST['description'] = "how to get instance description?" # problem here request.POST['season'] = 2 return super(ShowUpdate, self).post(request, **kwargs) models.py class Show(models.Model): owner = models.ForeignKey(User, null=True, default=True, related_name='o') title = models.CharField(max_length=100) description = models.TextField(default='N/A', blank=True, max_length=250) season = models.IntegerField(default=0) episode = models.IntegerField(default=0) def get_absolute_url(self): return reverse('show:index') def __str__(self): return self.title -
Django: Trouble with named URLs instead of ids
So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like localhost:8000/subjects/Biology/unit-one/ Here is my code views.py class IndexView(generic.ListView): template_name = 'card/index.html' context_object_name = 'subjects' def get_queryset(self): return Subject.objects.all() class SubjectView(DetailView): model = Subject slug_field = "subject" template_name = 'card/subject.html' class DeckView(DetailView): model = Deck template_name = 'card/deck.html' def get_object(self, subjects, deck): subject_obj = Subject.objects.filter(subject_name=subjects).first() obj = Deck.objects.filter(subject=subject_obj, deck_name=deck).first() return obj def get(self, request, subjects, deck): self.object = self.get_object(subjects, deck) context = self.get_context_data(object=self.object) return self.render_to_response(context) models.py class Subject(models.Model): subject_name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.subject_name def get_absolute_url(self): return reverse('card:index') class Deck(models.Model): deck_name = models.CharField(max_length=100) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) def __str__(self): return self.deck_name class Card(models.Model): term = models.CharField(max_length=100) definition = models.TextField() deck = models.ForeignKey(Deck, on_delete=models.CASCADE) def __str__(self): return self.term urls.py url(r'^subjects/(?P<subject>[\w ]+)/$', views.SubjectView.as_view(), name='subject'), url(r'^subjects/(?P<subject>[\w ]+)/(?P<deck>[\w ]+)/$', views.DeckView.as_view(), name='deck'), index.html <li><a href="{% url 'card:subject' subject.subject_name %}"> subject.html <ul> {% for deck in subject.deck_set.all %} <li><a href="{% url 'card:deck' deck.deck_name %}">{{deck.deck_name}}</a></li> {% endfor %} </ul> … -
Django: How to already fill a form's fields when editing existing instances of a model?
I asked this same question a few days ago, but I still have no solution. I'm making an app where you can track your episodes, and when the user is updating the episode of an existing show, I want the form to already have the fields on it. I don't have a forms.py for this form, I'm just using class-based views. views.py class ShowUpdate(UpdateView): model = Show slug_field = 'title' slug_url_kwarg = 'show' fields = ['description', 'season', 'episode'] urls.py # index url(r'^$', views.IndexView.as_view(), name='index'), url(r'^about/$', views.AboutView.as_view(), name='about'), # form to add show url(r'^add/$', views.ShowCreate.as_view(), name='show-add'), # edit show url(r'^(?P<show>[\w ]+)/edit/$', views.ShowUpdate.as_view(), name='show-update'), # delete show url(r'^(?P<show>[\w ]+)/delete/$', views.ShowDelete.as_view(), name='show-delete'), # signup url(r'^register/$', views.UserFormView.as_view(), name='register'), # login url(r'^login/$', views.LoginView.as_view(), name='login'), # logout url(r'^logout/$', views.LogoutView.as_view(), name='logout'), url(r'^error/$', views.ErrorView.as_view(), name='error'), url(r'^(?P<show>[\w ]+)/$', views.ShowDetail.as_view(), name='show-detail'), models.py class Show(models.Model): owner = models.ForeignKey(User, null=True, default=True, related_name='o') title = models.CharField(max_length=100) description = models.TextField(default='N/A', blank=True, max_length=250) season = models.IntegerField(default=0) episode = models.IntegerField(default=0) -
how to add staticfiles processing to css pages in django
In my CSS, I have examples like this: #defaultCountdown span.countdown_section { color:#fff; padding:7px 15px!important; margin-bottom:2px; font-weight:300; background:url(../img/bg-white.png); text-align:center } If you see the background tag, there's a url. How do I serve this via staticfiles? Thanks. -
Missing initial values when another field has required=True
One can set default values using the initial parameter. However, for some reason, this initial value is not given when another field has the required=True parameter. How do I set initial values in this case? I want to set the boxes to have the default value of true instead of false. Code example: class SearchForm(forms.Form): #search what? titles = forms.BooleanField(required=False, initial=True) abstracts = forms.BooleanField(required=False, initial=True) keywords = forms.BooleanField(required=False, initial=True) names = forms.BooleanField(required=False, initial=True) affiliations = forms.BooleanField(required=False, initial=False) #input search = forms.CharField(max_length=500, required=True, label="") -
Override settings from another Django app
How can I in my project settings.py override a setting from an apps settings.py? I tried importing it like this: import app.settings EXTENSIONS = { 'Folder': [''], 'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff', '.svg'], } But I get an error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How can I override settings from another app? -
How to edit many objects at the same time in django?
Well, usually, when I like edit one object I using instance and get_object_or_404, something like this: question = get_object_or_404(Question, id = id) form = FormQuestion(request.POST, instance=question) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/Something/') else: form = FormQuestion(instance = question) return render(request, {'form':form}, 'Ask/question.html') Using this code I can edit one object, the problem is: I need to list all questions and the fields will be editable, but I can't find a way to do this. Someone has a method or a code who resolve my problem? -
password authentication failed in postgresql with django
This is my first post here so I apologize if I did anything incorrectly I'm trying to learn web development with Django and I was following this guide to do so. Everything works fine until I get to python manage.py makemigrations I get this: password authentication failed for user "myprojectuser" I have checked and rechecked many times and the password is correct in the settings.py file. Here is how I did the file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } I am using postgreSQL 9.5, python 2.7, and Django 1.10 -
How can i retrieve foreign key objects in Django
Suppose I have this table strcuture class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, unique=False) def __unicode__(self): return "Artist:"+self.artist + " Title:"+self.title class Song(models.Model): album = models.ForeignKey(Album) #Link to primary key in Album title = models.CharField(max_length=128) def __unicode__(self): return self.title How can I retrieve All the Songs objects that belong to a certain instance of Album? -
How do I upload files to a specific folder in Django?
After the user uploads 2 .ini files, I would like it to save both files inside the following folder. MEDIA/uploadedconfigs/Printer/Plastic/ However, it's currently saving to the address below. MEDIA/uploadedconfigs/None/ Below is the code that uploads the files. models.py def UploadedConfigPath(instance, filename): return os.path.join('uploadedconfigs', str(instance.id), filename) class ConfigFiles(models.Model): Printer = models.CharField(_('Printer Model'), max_length=100, blank=True, null=True, unique=False) Plastic = models.CharField(_('Plastic'), max_length=40, blank=True, null=True, unique=False) creator = models.CharField(_('Creator'), max_length=40, blank=True, null=True, unique=False) HDConfig = models.FileField(_('High Detail'), upload_to=UploadedConfigPath) LDConfig = models.FileField(_('Low Detail'), upload_to=UploadedConfigPath) pub_date = models.DateTimeField(_('date_joined'), default=timezone.now) I'm not what "instance" is doing, but I was told it's what is spitting out the "None" folder name. I was also told I may need to place the files in a temporary folder but I'm not sure what that would entail. Any help would be appreciated! -
Django custom command subprocess logging puzzle
The core functionality is called as a custom command. update_data.py: class Command(BaseCommand): def handle(self, *args, **options): if options["nolog"]: I need to A) somehow pass a command line parameter to enable/disable logging. The problem is that B) logging should start (or not start in the second case) with an application start, so that it logs unrelated request handlers etc. E.g. putting logging to AppConfig.ready() satisfies B, but it is too early for having custom command line argument. The root cause is that django application calls its core part in a subprocess as a custom management command. So we have one copy of Django environment run from inside of its second copy. In other case command is to be run by scheduler. subprocess.Popen(["python", "manage.py", "update_data"], ...) -
Django-money: decimal_places doesn't work
I'm using django-money for representing price info in my project. I don't want to show any decimal point so I set decimal_places as zero, but it always shows two decimal point(as .00) Here is the code. models.py class Product(TimeStampedModel): name = models.CharField(max_length=120) slug = models.SlugField(null=True, blank=True) description = models.CharField(max_length=400, blank=True) is_active = models.BooleanField(default=True) objects = ProductManager() class Meta: ordering = ('-created',) def __str__(self): return self.name def get_absolute_url(self): return reverse( "products:product_detail", kwargs={ "slug": self.slug, } ) class Variation(TimeStampedModel): COLOR_CHOICES = ( ('black', '흑백'), ('single', '단색'), ('multi', '컬러'), ) price = MoneyField(max_digits=15, decimal_places=0, default_currency='USD') product = models.ForeignKey(Product) color = models.CharField( max_length=10, choices=COLOR_CHOICES, default='흑백', unique=True, ) is_active = models.BooleanField(default=True) def __str__(self): return self.get_color_display() signals.py @receiver(post_save, sender=Variation) def post_save_variation(sender, instance, created, **kwargs): if created: if instance.color == 'black': instance.price = Money(40000, USD) elif instance.color == 'single': instance.price = Money(50000, USD) elif instance.color == 'multi': instance.price = Money(60000, USD) instance.save() product_detail.html {% extends "base.html" %} {% load djmoney %} {% block content %} <h2> Product Detail 페이지입니다!</h2> <p> {{ product.name }}</p> <p> {{ product.description }}</p> 컬러: <select class="form-contorl"> {% for variation in product.variation_set.all %} <option value="{{ variation.color }}"> {{ variation }} </option> {% endfor %} </select> {% money_localize product.variation_set.last.price %} {% endblock %} How can … -
Inserting data into a Table row using Django ORM
I am currently learning about django orm and playing with this structure class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, unique=False) def __unicode__(self): return "Artist:"+self.artist + " Title:"+self.title class Song(models.Model): album = models.ForeignKey(Album) #Link to primary key in Album title = models.CharField(max_length=128) def __unicode__(self): return self.title I made an entry into Album using this >> a = Album(artist="Madonna",title="SomeTitle",genre="pop") >> a.save() and that saved it. Now how can i insert into the Song table? One way I think I could do is this >> s = Song(a,title="SongA") >> s.save() #Error TypeError: int() argument must be a string or a number, not 'Album' How can I save a song -
Aldryn_newsblog and djangocms RC1 3.4 mismatch between content and latest_article list
I never succeed to install correctly on a local server Aldryn_newsblog. I have had similar behaviour with djangocms_blog.I create a apphook page blog with summary and the other one with content, so after that I have the following sequence 1 - startrc1-34.net/fr/cms/ => Title and summary of unique article is listed 2 If i click 'Edit' on the cms toolbar=> I will see the main content for edition and the URL is startrc1-34.net/fr/cms/slugname 3 After modification If i publish the modification, I will see the list of articles again, not the content Other point, now when I create a blog page in the administration, and I want to see it in frontend the following error URL is created http://http//startrc1-34.net/fr/cms/newslugname Here my settings import os gettext = lambda s: s _ = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) """ Django settings for prjrc1st project. Generated by 'django-admin startproject' using Django 1.8.14. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep … -
My celery redis task isn't working in my django app on heroku server
I have a task that was working fine on my local server but when I pushed it to Heroku, nothing happens. there are no error messages. I am a newbie when it comes to this and locally I would start the worker by doing celery worker -A blog -l info. So I'm guessing that's the issue may have to do with that. because I don't know to do this. I doubt I'm supposed to do this in my app. heres my code celery.py import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'gettingstarted.settings' ) app = Celery('blog') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my tasks.py import requests import random import os from bs4 import BeautifulSoup from .celery import app from .models import Post from django.contrib.auth.models import User @app.task def the_star(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' … -
Django : Passing a list as arguments to generic create view from html page
I am making a portal for the procedure of Interview rounds. My basic code is as follows: models.py class Round(models.Model): pending_students = models.ManyToMany(User, related_name='pending_student', blank=True) done_students = models.ManyToMany(User, related_name='done_students', blank=True) round_number = models.PositiveIntegerField(default=0) #other fields First, for the current round, I am displaying pending_students and done_students separately. Current user will bring some pending to done(and done to pending if he wants) and then he will submit. I want that, On submitting, next round should be created. Now I want that if new round is created, then all done_students of previous round should come to pending_students for this newly created round. I am using generic create view (but if needed, I am fine with writing manually). Now problem is that in create view, how can I know which student should go to next round (means who are in the list of done_students on client side) ? I want to know, how can I pass the id's of all done_students from HTML page to newly called create view to create next round ? -
Receiving intermittent error when querying BigQuery database from Django App hosted on Apache2 Server
Not sure if I'm allowed, but for the sake of those who wants to see my issue first hand, I am adding url of my development environment (www.blesque.tv). Issue is easily reproducible by reloading that page multiple times. I switched the home page of my site to query data from my BigQuery database. When I am reloading the page, 2 times out of 3 approximately, I receive error as on the attached image below. Not sure what is happening. When content loads, it loads very quickly (the main reason I am switching to BQ), but then next time reloading the page, error is thrown. I tried to look through Google's API reference thinking maybe DB connection needs to be closed explicitly after each time I query it, but could not find anything about it. Need help from StackOverflow community. Thank you. This is the Google's API I am using: https://cloud.google.com/bigquery/docs/reference/v2/ Error message: Error at / [('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')] Request Method: GET Request URL: http://www.blesque.tv/ Django Version: 1.9.8 Exception Type: Error Exception Value: [('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')] Exception Location: /home/businessai/lib/python2.7/OpenSSL/_util.py in exception_from_error_queue, line 48 Python Executable: /usr/local/bin/python Python … -
Django querying against external database with different timezone
I have a Django API application running on postgres with TIME_ZONE='America/New_York' and USE_TZ = True. For a daily report, I need to query another database, MySQL, and compare records from the postgres DB to check for some updates. They should contain the same number of results. The MySQL DB's timezone is UTC however. How can I perform SELECT queries against the MySQL DB to have it match the same date range on my postgres DB? Example: These two queries should return the same number of results # Django/Postgres with TIME_ZONE='America/New_York'` MyObject.objects.filter(created_on__date=date(2016, 9, 17)) # External MySQL Databse in UTC sql.execute('SELECT * from MY_TABLE where created_on BETWEEN "2016-09-17" AND "2016-09-18"') -
Django order_by - force past dates to sort after present and future dates
I want to know if there is any way in Django to sort a queryset, so that the entries with date in the past are sorted after the entries with dates in the present or future. -
Django: View didn't return an HttpResponse object. It returned None instead
Basically I would like a user to input a number in a field and the fibonacci result to be printed but once the input is inserted into the input field I recieve that it returned None instead of an object I have this code over here for my html form: {% block content %} <form method="POST" action=".">{% csrf_token %} <input type="text" name="fcal" value="{{F}}" /> <p> <input type="submit" name="fibo" value="Fibonacci" /> </p> </form> {% if cal %} Your Fibonacci answer is {{cal}} {% endif %} {% endblock %} The content of my views.py is this one: from django.shortcuts import render_to_response, get_object_or_404, render from django.forms import ModelForm from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotFound import fibonacci def fibocal(request): if request.method == 'POST': fb = request.POST['fcal'] cal = fibonacci.fibo(fb) return render(request, 'fibb/fibb.html', {'cal': cal}) else: return render(request, 'fibb/fibb.html', {}) And my fibonacci function is this one: def fibo(n): if n == 0: return 0 elif n == 1: return 1 else: result = fibo(n - 1) + fibo(n - 2) return result I would like to know where the error is caused as I've looked again and again and I can see that I am returning a render not None -
How to test APIView in Django, Django Rest Framework
I am making an API with Django + Django Rest Framework. I am trying to test the GET methods of a view: View: class StuffView(APIView): queryset = Stuff.objects.none() def get(self, request, format=None): data = Stuff.objects.all().order_by('-primaryKey') StuffSerializer(data, many=True) return Response(serializer.data, 200) In my test I create test data for the Stuff and then run this utilizing DRF's APIClient: def test_stuff_view_get_all(self): response = self.client.get('/api/stuff/') content = json.loads(response.content.decode('utf-8')) # create dictionary self.assertEqual(response.status_code, 200) self.assertEqual(len(content), len(Stuff.objects.all().order_by('-primaryKey') )) This works, but I am not sure length is the best way to compare these things, or if decoding the response is the best way to do it either. The other thing I would like to test is to make sure that it is properly ordered by primary key. Is there a best practice to doing this? Is it even the correct way? Are there some things I am missing out on that I should be testing? -
Haystack SearchForm Update Choices based on SQS
I have a SearchForm that lets the user filter their search results when they select certain choices for available fields. see screenshot of filter form here As you can see by the code below, instead of getting the CHOICES via the SearchQuerySet, I'm using Django's QuerySet instead. Further down the code, I'm using haystack SearchQuerySet to return the results. What I'm having trouble with is modifying this to use the SearchQuerySet for CHOICES, so that each selection will narrow the available choices based on the SQS. Any help is much appreciated. class CustomSearchForm(SearchForm): def no_query_found(self): return self.searchqueryset.all() retailers = sorted(tuple(set([(choice, choice) for choice in Retailer.objects.order_by('retailer_name').values_list('retailer_name', flat=True)]))) brands = sorted(tuple(set([(choice, choice) for choice in Brand.objects.exclude(brand_name__isnull=True).order_by('brand_name').values_list('brand_name', flat=True)]))) categories = sorted(tuple(set([(choice, choice) for choice in Category.objects.order_by('category_name').values_list('category_name', flat=True)]))) colors = sorted(tuple(set([(choice, choice) for choice in Color.objects.values_list('color_true', flat=True)]))) sizes = sorted(tuple(set([(choice, choice) for choice in Size.objects.values_list('size_true', flat=True)]))) sorting = (('1','Random'),('2','Last Updated (most recent)'),('3','Regular Price'),('4','Sale Price'),) sort = forms.ChoiceField(choices = sorting, label="Sort By",label_suffix='',initial='1', widget=forms.Select(attrs = {'onchange' : "this.form.submit();", }), required=False) onsale = forms.BooleanField(required=False,widget=forms.CheckboxInput(attrs = {'onclick' : "this.form.submit();", }), label='On Sale', label_suffix='') retailer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs = {'onclick' : "this.form.submit();", }), choices=retailers, label_suffix='',required = False) brand = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs = {'onclick' : "this.form.submit();", }), choices=brands, label_suffix='',required = False) category … -
Django Queryset & Aggregate Functions
I am creating a little soccer / football game. Each week players will select two teams. All this, thanks to the kind people on here, is working nicely. I now want to create the scoring system and for this to work I need to calculate how many times their team selections WON their respective games. I.e. After 3 weeks each player would have picked 6 teams and I need to calculate how many of those selections WON their game. The following models are what I believe I need to try to calculate this: class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturestatus = models.CharField(max_length=24,null=True) fixturematchday = models.IntegerField(null=True) spectators = models.IntegerField(null=True) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) homegoaldetails = models.TextField(null=True) awaygoaldetails = models.TextField(null=True) hometeamyellowcarddetails = models.TextField(null=True) awayteamyellowcarddetails = models.TextField(null=True) hometeamredcarddetails = models.TextField(null=True) awayteamredcarddetails = models.TextField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season') def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixturematchday = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_seasonUserSelection') class Meta: managed = True db_table = 'straightred_userselection' There are a … -
Django pass parameters(blob) in AJAX call and access in views
In my Django app, I am making an ajax request: var data = { blob : JSON.stringify(blob), csrfmiddlewaretoken : token }; $.ajax({ url: '../upload/', type: 'POST', data: data, processData: false, contentType: false, success: function(data){ console.log("this is : " + data); } }); Now in views.py, I want to use this blob object. How do I see it? I have tried these: print (request.body) print (request.POST['blob']) the first one returns: b' [Object object] and second raises MultiValueDictKeyError(repr(key)). How is this done?