Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not receiving information when using GET method, only when I don't use it
In my project I'm displaying JSON conversations for a certain ID,the ID is passed as an argument in the URL. def conversationview(request, convo_identification): data = InputInfo.objects.all() conversation_identification = request.GET.get('convo_identification') #conversation_id = {'conversation_id': []} header = {'conversation_id': '', 'messages': []} entry = {} output = {} for i in data: if str(i.conversation_id) == conversation_identification: header['conversation_id'] = i.conversation_id entry = {} entry['sender'] = i.name entry['message_body'] = i.message_body entry['date_created'] = str(i.created) header.get('messages').append(entry) output = json.dumps(header) return HttpResponse(output) URLs.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^message/', sendMessage.as_view(), name='message'), url(r'^conversations/(?P<convo_identification>\d+)', views.conversationview, name='conversationview'), ] conversation_identification = request.GET.get('convo_identification') doesn't work (nothing displays on the screen), but when I change it to conversation_identification = convo_identification it will display the information for that ID fine. I don't have any HTML for this because I don't need it. But I'm wondering why I can't use request.GET or request.get.GET()? Does it matter? I know by looking at my terminal that there is a GET request being made. -
How do you write a script referencing indexed inputs?
I'm basically a complete javascript and jquery amateur, trying to get a simple feature working. The goal is to present a list of notifications (corresponding to a django model with a flag of "read") in a user profile page, each one with an "read" checkbox that begins in the unchecked state. When the user checks the "read" box, I'd like the script to update the flag in the backend. Once this occurs, the notification won't be displayed in future visits to the profile page, and the count of unread messages will go down. I've been learning from this tutorial at Tango with Django, which I think does what I want to do. <p> <strong id="like_count">{{ category.likes }}</strong> people like this category {% if user.is_authenticated %} <button id="likes" data-catid="{{category.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> {% endif %} </p> ... <script> $('#likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/rango/like_category/', {category_id: catid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); </script> The difference is that where they have the button id=likes, I have a checkbox with something like id=notif-64, because there is a checkbox for each notification entry. Can the script be rewritten to accept inputs like notif-X? Or else, how am I going … -
Django 404 localhost:8000/admin error
When I go to "localhost:8000/admin" I get an OBJECT NOT FOUND with a 404 error message. I followed Traversy Media's tutorial and have only edited code in the setting.py file to connect to MySQL. I had to change my port to 8000 and ssl port to 1443 in XAMPP, but apache and MySQL are running smoothly. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'M42.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'M42.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'm42', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '' } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Django error when trying to access database in network directory
Now this may be something very foolish to do, but please allow me to discuss my issue. I am attempting to have Django access a database on a remote device by accessing it's network directory like so (in the settings.py script): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/run/user/1004/gvfs/sftp\:host\=169.254.131.151\,user\=root/root/injection_log2.sqlite', }} I've successfully created a file, viewed a file, and edited a file through Vim and that exact directory. So doing this should work right? But I am getting the following bug: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection … -
Redirect to appropriate page while clicking on Button ReactJS/Django project
I'm new to the web development and chose django/Reactjs for my social network project. I made a few api methods like account/view_user/ that returns list of users and account/view_user/ that returns attributes for particular user. I also wrote a page in React that renders a list of users class PersonnelContentFeed extends React.Component { constructor() { super(); this.state = { 'items': [] } } componentDidMount() { this.getItems(); } getItems() { fetch('http://localhost:8000/api/account/view_user/') .then(results => results.json()) .then(results => this.setState({'items': results})); } render() { return ( <ul> {this.state.items.map(function(item, index) { return <PersonnelContentItem item={item} key={index} /> })} </ul> ); } } class PersonnelContentItem extends React.Component { render() { return ( <Row className="PersonnelContentItem"> <Col xs="3"></Col> <Col xs="6"> <Card> <CardImg top width="100%"></CardImg> <CardBody> <CardTitle> <strong>{this.props.item.first_name} {this.props.item.last_name}</strong> </CardTitle> <NavLink to='./PersonDetails'><Button> Details </Button> </NavLink> </CardBody> </Card> </Col> </Row> ) } } There is also a React component for person details(similar to PersonnelContentFeed) The question is: What should I do to redirect user to the appropriate details page (with right id, e.g /api/account/view_user/1) while clicking "Details" Button. Thank you all in advance. -
Django/Postgresql division by zero issue with Window function and Lag expression
How do I avoid division by zero errors where the field with zero values is neither (1) an existing model field or (2) an annotated field? Is that possible? This queryset works until there is a zero in prior_qtr_rev variable. prior_qtr_rev = Window( Lag('rev'), partition_by=F('company_id'), order_by=F('fiscal_end_date').asc() ) yoy = F('rev') / prior_qtr_rev - 1 companies = Financial.objects.filter( company__ticker='AAPL', ).annotate( rev_yoy=yoy, ) I looked at this and this for guidance. I tried wrapping the prior_qtr_rev with Case and When as suggested in the first link, but I was getting the following error. yoy = F('rev') / Case(When(prior_qtr_rev=0, then=0), default=prior_qtr_rev, output_field=FloatField() ) - 1 django.core.exceptions.FieldError: Cannot resolve keyword 'prior_qtr_rev' into field. Choices are: I am trying to avoid having to add prior_qtr_rev in my results. I only want the calculated yoy variable to be annotated. -
Django - Filter a list of objects using a field on a related model and show a value of the related model
(Sorry for my bad english) I have a problem, I need to filter a list of products to show only the availables on a branch office, and this attributes are in a related model of a products. I have a Product Model class Product(models.Model): # Relations supplier = models.ForeignKey( Supplier, verbose_name=_('supplier'), on_delete=CASCADE, ) manufacturer = models.ForeignKey( Manufacturer, verbose_name=_('manufacturer'), on_delete=CASCADE, ) family = models.ForeignKey( Family, verbose_name=_('family'), on_delete=CASCADE, ) category = ChainedForeignKey( Category, chained_field='family', chained_model_field='family', auto_choose=True, verbose_name=_('category'), ) subcategory = ChainedForeignKey( Subcategory, chained_field='category', chained_model_field='category', auto_choose=True, verbose_name=_('subcategory'), ) condition = models.ForeignKey( ProductCondition, default=1, verbose_name=_('condition'), on_delete=CASCADE, ) # Attributes - Mandatory name = models.CharField( max_length=63, unique=True, verbose_name=_('name'), ) slug = models.SlugField( max_length=63, unique=True, editable=False, verbose_name=_('slug'), ) ... ... and I have other Model with the branch office (each branch office use different prices and stock) this is the ProductPrice Model class ProductPrice(models.Model): # Relations product = models.ForeignKey( Product, verbose_name=_('product'), on_delete=CASCADE, ) branch_office = models.ForeignKey( BranchOffice, default=1, verbose_name=_('branch office'), on_delete=CASCADE, ) # Attributes - Mandatory # Costo de compra del producto neto net_purchase_price = models.DecimalField( default=0.00, max_digits=10, decimal_places=2, help_text=_('net purchase price (without taxs)'), verbose_name=_('net purchase price'), ) # IVA aplicable al producto tax_rule = models.SmallIntegerField( choices=TAX_RULES, default=1, verbose_name=_('tax rule'), ) # Precio de compra con … -
Saving Facebook picture in Django Model (REST Social Oath2)
This question is about saving Facebook Profile pictures in the Django model automatically, using https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 library. The above library allows me to create and authenticate users using bearer tokens. I have the created the profile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') photo = models.FileField(blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() Which automatically creates user profiles for each user. Now, I would like to add the following code to save the photo from Facebook. Facebook API requires user id to get this picture. photo = https://facebook/{user-id}/picture/ UserProfile.objects.create(user=instance, photo=photo) The above is not working because 1) I can't figure out where to get the user id from. 2) The image can't be stored like that, I need to convert it to bytes or some other method. -
Cannot reverse a url from name in Jinja2
I have a Django project with Jinja 2.10 templating. I have a standard Jinja environment that aliases url to Django's reverse. In urlpatterns I have the following entry: path('test', views.test, name='test') And I want to dynamically create a URL to this view from another simple template: {{ url('test') }} However, when I open the view that renders this template, I receive an error: Reverse for 'test' not found. 'test' is not a valid view function or pattern name. I see people successfully using this method (e.g. here), so why isn't it working here? -
Select a random ForeignKey in Django
Here is my problem : Imagine I have a model named "Monster" and a database named "Fight". Here is the Fight Model : class Fight(models.Model): fight_id = models.AutoField(primary_key=True) fight_user = models.OneToOneField(User, on_delete=models.CASCADE) fight_enemy = models.ForeignKey(Monster, on_delete=models.CASCADE) Now, if the user (fight_user) does not have already a "fight" model, I want to create one by selecting randomly an enemy in the "monster" model. How can I do that ? Thanks ! -
Designing an HTML form input that takes a range of numbers as well as text options
I have the following form: <table class="table"> <thead> <tr> <th><h4>Monday</h4></th> <th><h4>Tuesday</h4></th> <th><h4>Wednesday</h4></th> <th><h4>Thursday</h4></th> <th><h4>Friday</h4></th> <th><h4>Add</h4></th> </tr> </thead> <tbody> <tr> <form id="tracking_form"> <td><input type="number" name="monday" class="weekday_points" min="0" max="100" required id="id_monday" /></td> <td><input type="number" name="tuesday" class="weekday_points" min="0" max="100" required id="id_tuesday" /></td> <td><input type="number" name="wednesday" class="weekday_points" min="0" max="100" required id="id_wednesday" /></td> <td><input type="number" name="thursday" class="weekday_points" min="0" max="100" required id="id_thursday" /></td> <td><input type="number" name="friday" class="weekday_points" min="0" max="100" required id="id_friday" /></td> <td><input type="button" class="btn btn-default" onclick="submitIfUnique()" value="Add Points"></td> </form> </tr> </tbody> <tfoot> </tfoot> </table> Where a user enters a number from 0 to 100 as a score for a student. I also want to track whether the student was absent, whether the absence was explained, etc. If the student was absent, then the user shouldn't then be able to enter a score. What would be a good form design for a use case like this? I'm working in Django, so I could change the weekday number inputs to text inputs and provide choices like this: settings.py: SCORE = ['Present', 'Absent (Not Explained)', 'Absent (Explained)', 'Integrating'] + [x for x in range(0, 101)] models.py: monday = models.CharField(choices=settings.SCORE) tuesday = models.CharField(choices=settings.SCORE) wednesday = models.CharField(choices=settings.SCORE) thursday = models.CharField(choices=settings.SCORE) friday = models.CharField(choices=settings.SCORE) The problem is, the input would now … -
Django - how to delete model item from list
I'm currently building an app with Django for the purpose of creating user-story cards (a bit like a Trello board). On one page I have my cards displayed as a list: Screenshot of list The code for the list is: <h1>ScrumBuddy Board</h1> <ul> {% for card in cards.all %} <li class="card"><a href="{% url 'card' %}/{{ card.id }}">{{ card.title }}</a> </li> {% endfor %} </ul> And the view def for the board is: def board(request): cards = Card.objects context = {'cards': cards} return render(request, 'scrumbuddy/board.html', context) I'd like to add a delete link to each card that removes it from this list, preferable with a confirmation dialogue box. Any suggestions on how to do that would be fantastic. Many thanks. -
django redirects on posting form using ajax
I'm trying to understand what's actually going on. I have this CreateView based class which I'm using to add new Operation: class OperationCreate(CreateView): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def form_valid(self, form): (...) form.save() return JsonResponse({'result': 'success'}) def form_invalid(self, form): form.save() return JsonResponse({'result': 'error'}) After getting a form and posting it using ajax I can see following calls logged: [18/Feb/2018 22:52:54] "GET /expenses/new_operation/ HTTP/1.1" 200 1135 [18/Feb/2018 22:53:04] "POST /expenses/new_operation/ HTTP/1.1" 200 21 [18/Feb/2018 22:53:04] "GET /expenses/manage_operations/?csrfmiddlewaretoken=okXK8OwPJ9BJGQeMvSW3Y5koSeTEIXyQDBOAroI1OU8tD7GPxQxZQ37IdhdkhiKe&account=1&type=-1&category=1&date=2001-01-01&amount=2001 HTTP/1.1" 200 3842 I don't understand where did the last one came from. I know I have specified success_url which is a legacy code after previous implementation but it's not used anymore since I have redefined from_valid method. Also I don't get why this last request contains all parameters that I have posted before. Could you please explain it to me? Here is my ajax post method: function postForm(url, form_selector) { var form = $(form_selector); var csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value') form.submit(function () { $.ajax({ headers: { 'X-CSRFToken': csrf_token }, type: 'POST', url: url, data: form.serialize() }); }); }; -
How to disable Django showing decimal separator in templates?
I have a Django app, when i was writing the code on my pc, it was showing the numbers in the templates in this style: 1000 -> 1,000 (I use the use thousand separator) But when i deployed the app to my server, it shows: 1000 -> 1,000.00 but i don't what to use the numbers with the decimal separator. I tried formatting the numbers with the intcoma filter but doesn't work anyway. How i can get rid of this? -
how to retrieve specific card without using card id? stripe, django
I know we can use stripe customer id to retrieve list of cards attached to the customer id. Also, I know we can retrieve ONE specific card with the card's id....But what if I do not want to use the card id to retrieve the card. Instead I want to use exp month, year, last4. Is this possible? I thought of all_cards = stripe.Customer.retrieve(cus_id).sources.all(object=CARD) the_card = all_cards.all( exp_month=data.get(EXP_MONTH), exp_year=data.get(EXP_YEAR), last4=data.get(LAST_4) ) but it says no such parameters such as exp_month I thought of doing it in a way to loop through all the card and match the parameters which myself believes would be a bad idea if there is a better one. Does anyone have a better idea or suggestions? Thanks in advance for any advise -
How do I make a password from one `input` match another as I type?
I have this at the top of my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript"> var app= angular.module("app",[]); app.config(function($interpolateProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); }); app.controller("MainCtrl",function($scope){ $scope.name= "World"; }) </script> I have two input elements. <input id="id_password1" name="password1" ng-model="pw" placeholder="Password" type="password" required=""> and <input id="id_password2" name="password2" ng-model="pw" placeholder="Confirm password" type="password" required=""> As I type my password into the first input, I'd like to fill the second with what I'm typing in the first. How do I do this? Edit: These inputs are in a form made with Django. In my forms.py, I have this. class RegisterForm(UserCreationForm): ''' Form that makes user using just email as username ''' username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email", "id":"id_register_username"})) password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password", "ng-model":"pw"})) password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password", "ng-model":"pw"})) -
How to implement Premium payments in Django
I am on the way to finish my project. I want to use a payment access. Maybe someone know how to solve it. For example the user will can decide what a plan want. The 3 plans will be available:basic,premium and pro. If the user choose the basic plan then can create for example 10 records, if premium 20 records etc. I want to use a Polish provider of payment. -
django module' object has no attribute 'vote'
I'm currently doing the tutorial on the Django website, and I've been running into this problem. command line views.py urls.py -
Ansible-playbook says file exists, and than says it doesn't exist
I am trying to debug my ansible-playbook, and figure out why an RSA key I copy onto a Docker Image fails to be authenticated when cloning a git repository onto that Docker Image. The first thing I wanted to look at is if the RSA key file I moved even exists in the Docker Image my playbook is creating. I run a couple tasks, one to see if the file exists, and than another than displays the RSA key to me. The first task that sees whether the file exists saves that result to a variable, and in that variable I can see that the file does in fact exist. When I try to print the contents of that file though, I get an error message saying that file path doesn't exist. ANSIBLE - name: Upload Deploy Private Key /home/app-user/.ssh/id_rsa copy: src=keys/keys dest="/home/app-user/.ssh/id_rsa" mode=0400 - name: Check that /home/app-user/.ssh/id_rsa exists stat: path: /home/app-user/.ssh/id_rsa register: stat_result - debug: var: stat_result - debug: msg="the value of id_rsa is {{lookup('file', '/home/app-user/.ssh/id_rsa') }}" TERMINAL docker: TASK [base : Upload Deploy Private Key /home/app-user/.ssh/id_rsa] ******** docker: Sunday 18 February 2018 13:24:36 -0600 (0:00:00.508) 0:02:20.492 ******* docker: changed: [default] docker: docker: TASK [base : Check that … -
How to define hidden field widget and set up value into modelform and save it in DB?
I have such models.py class User_information(models.Model): name = models.CharField(max_length=50) url = models.URLField() def __str__(self): return self.name And my forms.py class PostForm(ModelForm): class Meta: model = User_information fields = ['name', 'url'] labels = { 'name': _('Имя'), 'url': _('link'), } widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 3}), # 'url' : ????????????? } I need to save a current url page from hidden field of form. How can I set up hidden field and get current url of form's page and save it? -
use django template with dash application
I have set-up a dash application that works well with my django website, but I would like to have the dash application on a page that has a template. The setup I have is the usual one, that is : views.py def dispatcher(request): ''' Main function @param request: Request object ''' params = { 'data': request.body, 'method': request.method, 'content_type': request.content_type } with server.test_request_context(request.path, **params): server.preprocess_request() try: response = server.full_dispatch_request() except Exception as e: response = server.make_response(server.handle_exception(e)) return response.get_data() @login_required def dash_index(request, **kwarg): return HttpResponse(dispatcher(request)) @csrf_exempt def dash_ajax(request): return HttpResponse(dispatcher(request), content_type='application/json') and urls.py urlpatterns = [ re_path('^_dash-', views.dash_ajax), re_path('^', views.dash_index), ] The above code works fine. Now I've tried the following for embedding the page (view dash_index) within a template (called dashboard template). The template is not for formatting the app itself, but for elements that will be "around" the app, such as navbar, footer, menu etc. Try n°1 @login_required def dash_index(request, **kwarg): template_name = "dashboard_template.html" return HttpResponse(dispatcher(request),template_name) doesn't yield error, but doesn't display template. try n°2 : @login_required def dash_index(request, **kwarg): template = loader.get_template("dashboard_template.html") return HttpResponse(template.render(dispatcher(request))) I get the following error from the urls.py file AttributeError: module 'app_name.views' has no attribute 'dash_index' Try n°3 : @login_required def dash_index(request, **kwarg): return … -
Converting function based view to class based view to return JSON Response
I have a function based view which works fine with Bootstrap Modal dialog and returns the JSON Response. I am trying to implement this with CreateView but couldn't make it to work. Function Based View which works fine :- def task_create(request): form = CreateTaskForm(initial={'owner' : request.user, 'assignee' : request.user}) context = {'form': form} html_form = render_to_string('tasks/task_create_ajax.html', context, request=request) return JsonResponse({'html_form': html_form}) Attempt for Class Based View :- class CreateTaskView(LoginRequiredMixin, CreateView): form_class = CreateTaskForm def get_template_names(self): if self.request.is_ajax(): return ['tasks/task_create_ajax.html'] else: return ['tasks/createtask.html'] def get_form_kwargs(self): kwargs = super(CreateTaskView, self).get_form_kwargs() kwargs.update({'initial': {'owner' : self.request.user, 'assignee' : self.request.user}}) return kwargs def form_invalid(self, form): response = super(CreateTaskView,self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(CreateTaskView, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response Problem :- In function based view, the html form is passed via variable html_form which I can view/debug in browser using console.dump command. When I use the class based view, my form didn't get populated. Can someone please suggest what should be the correct approach to make it work with class based view? How can I pass the JsonResponse for the form (get method) with … -
What's wrong in this python code?
def vector(sample_list): for item in sample_list: sums = 0 square = item**2 sums = square + sums magnitude = sums**0.5 return magnitude print(vector([2,3,-4])) Why this code doesn't give the correct magnitude? It gives the last value of the vector in function call. -
Transfer form together with other data using one AJAX post. Django
Very simple task. It is necessary to transfer data from the form together with other data using AJAX POST. The problem is how to extract this data later from the form, because they represent a whole line. $(function() { $('#myform').submit(function(event) { event.preventDefault(); var form=$('#myform').serialize(); var data={}; data['form']=form; data['csrfmiddlewaretoken']='{{ csrf_token }}'; data['other_data']='other_data'; $.ajax({ type: 'POST', url: '/myajaxformview', dataType: 'json', data: data, success: function (data, textStatus) { $('#output2').html(JSON.stringify(data)); }, error: function(xhr, status, e) { alert(status, e); } }); }); }); def myajaxformview(request): if request.method == 'POST': if request.is_ajax(): data = request.POST print(data) #<QueryDict: {'form': ['csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2'], 'csrfmiddlewaretoken': ['VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9'], 'other_data': ['other_data']}> form=data.get('form') #csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2 print(form) return HttpResponse(json.dumps(data)) return render(request, 'foo.html') -
Saving Django Media files on File System in Production
I am building a Django application where I have to serve some media files on server. Due to some limitations, I cannot use separate media file storage like S3 or Azure etc. What I actually do is that I need to generate an audio file on the basis of data provided by user and then play that file on browser. I delete that file after playing it. This is a research based project with no user based data and also data will be very small. Therefor I want to store media file on same server. When I run my application with DEBUG=True, data is uploaded on server and I can also access it in my web page. But when when I set DEBUG=False, I cannot access my media files stored in same server. I know the problem is that I need to deploy my media file to a separate server in production environment. But as I said, I cannot use a separate media file storage. I know that In production environment, I need to use server like Nginx and Apache when I will set path of my media file storage in nginx/apache settings and it will work. But the problem …