Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update FielField of an existing model
I have this model class TravelRequests(models.Model): mission_order = models.FileField(blank=True, null=True, upload_to='mission_order') where the mission order filefield is not required for the creation of the model but than it will be updated by an another user so he can upload the file. The problem is that when i upload the file when the model is created it doesn't save the file in the /media folder and in the filefield it self it save only the name of the file this is the ajax request : var data = new FormData($('.facilities_form').get(0)); var pk = $(this).val() $.ajax({ type: "POST", url: '/approve_facilities/' + pk + '/', data: data, cache: false, processData: false, contentType: false, success: function(response) { if (response == 'request_updated') { Swal.fire({ title: 'The request is approved!', type: 'success', allowOutsideClick: false, }).then((result) => { if (result.value) { window.location.href='/' } }); } } }); this is the view that handle the request @login_required def FacilitiesApproveRequest(request, pk): cordinator_comment = request.POST.get('cordinator_comment', '').strip() mission_order = request.FILES.get('mission_order') request_toApprove = TravelRequests.objects.filter(pk=pk) request_toApprove.update(mission_order=mission_order, facilities_approve_case=True, facilities_comment=cordinator_comment, facilities_comment_time=timezone.now(), request_updater=request.user, request_update=timezone.now(), request_status='facility_approve', facilities_aprove=request.user) return HttpResponse('request_updated') this is the html input : <form class="facilities_form" method="post" enctype="multipart/form-data"> <input type="file" name="mission_order" id="id_mission_order" accept=".pdf,.jpeg,.png,.msg"> </form> when i use the form to update the field i get this … -
Manually populate the ImageField remotely
Let me start off by explaining how my program works. I have model in Django like, class Attendance(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to=func_that_returns_path) Now, I have done this so that I can view the Attendance table rows from Django Admin, but I'm not going to be populating it from the Django Admin. See, I want to populate this table outside of Django. I'll have two programs. One, my Django app and another python script that connects to the server manually and does it's magic. My Django app will be hosted on a server and the script will be kept on my computer. The very first idea I had was to manually connect to the database using mysql-connector and just put the image in the database through it but then I realized that Django models don't actually hold the file itself but the file location. This complicated things. I don't really have any idea other than putting the file in the server through a TCP socket connect and putting the file in the media folder and adding the path to that file in the database. Please let me know if you have any other ideas or what else might work. -
How to paginate external API in Django Rest Framework
I'm learning to use Django Rest Framework, so as exercise I want to consume Github User REST API listing the users and save on a local database a specific user info, also I want that listing to be paginated. I have the following viewsets file: import requests from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from users.models import User from .serializers import UserSerializer class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @action(detail=False, methods=['GET']) def github(self, request): data = requests.get('https://api.github.com/users') return Response(data=data.json()) I'm able to list my users, and I know how to paginate the queryset but how do I paginate the github response ? another question, in this snippet my routes stay like: api/user api/user/github ​ Is there a way to create a separate view just for the github so I can something like: api/user api/github/user api/github/repository ​ and then be able to use filter field on api/user and api/github/user. -
Saving data inside and outside a form into a database
I'm learning to code with Django. So I have a form that displays quizzes and a JavaScript file that computes these quizzes. The quizzes are displayed in a , and I have other details like course still displayed on the form. To the best of my knowledge, POST only takes data withing the form. What if I have the score outside the form, how do I go about it? This is what I've done already: The JavaScript that computes the results: `` function submitAnswers(answers) { var total = answers.length; var score = 0; var choice = [] //new dynamic method 1 for (var i = 1; i <= total; i++) { choice[i] = document.forms["quizForm"]["q" + i].value; } for (i = 1; i <= total; i++) { if (choice[i] == null || choice[i] == '') { alert('You skipped question ' + i); return false; } } // new dynamic method for checking answer for (i = 1; i <= total; i++) { if (choice[i] == answers[i - 1]) { score++; } } //Display Result var results = document.getElementById('results'); results.innerHTML = "<h3>You scored <span>" + score + "</span> out of <span>" + total + "</span></h3>" alert("You scored " + score + " … -
Call Django on HTML button click Part 2
My question is basically this question: Call Django on HTML button click To summarize: in Django, how do you call a function after clicking a button? I followed the answer in the above link, however, whenever I click on the button it takes me to the URL of /actionUrl, which I do not want. I simply want the function I have to be called when the button is clicked. Any help would be appreciated because I do not have enough rep to comment on that post. -
django init value change after form submit
I am trying to change user LoginView, for some reason i want to use mobile number as username, and after user input phonenumber i will send a code to mobile via SMS. before sending SMS i want to be sure spam but don't attack to my form. I know, I can use google captcha and other plugin. but for my training I wan't to use my own way. there for I create a model name question, there are many question and answer inside table. every time page refresh a random question shows to visitor. this works fine without any problem. but my problem is when i want to validate form self.question chose another random question each time. this is very confusing. I tried to validate inside view and form, no difference question always return another question. model.py class Question (models.Model): question = models.CharField(max_length=100, null=False) answer = models.CharField(max_length=100, null=False) secend_answer = models.CharField(max_length=100,blank=True, null=True) KIND_CHOISE = ( ('I', 'idoms'), ('M', 'mathematic'), ('K', 'knowledge'), ) question_kind = models.CharField(max_length=1, choices=KIND_CHOISE) def __str__(self): return "quest => {}, answer is ==> {}".format(self.question, self.answer) views.py class LoginnView( FormView): form_class = UserLoginForm template_name = 'accounts/login.html' success_url = 'accounts/login.html' def bquestion(self): ques = None max_id = Question.objects.all().aggregate(max_id=Max("id"))['max_id'] while ques … -
Nested serialization for JSON
I'm trying to return a JSON like this after a successful post request. { "ip": "127.0.0.1", "ports": [ {port: "", service: ""} ], "first_scan": "date", "last_updated": "date" } I'm trying to make my serializer so that whenever my nmap function which returns data in this way on the console: Host : 127.0.0.1 (localhost) State : up port : 631 service : CUPS port : 902 service : VMware Authentication Daemon port : 6463 service : port : 8000 service : WSGIServer/0.2 CPython/3.7.3 It would parse it like the JSON mentioned. I have tried making a model like this in my models.py class nmapScan(models.Model): ip = models.CharField(max_length=13, blank=True) ports = models.CharField(max_length=5) service = models.TextField() first_scan = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['first_scan'] But I'm still confused by this nested serialization concept. How would I go on making the data get parsed from my function, return it like that certain JSON and have it stored in the database (assuming my model is right) properly? -
Multiple forms with one FormView
Is it possible to use a FormView for 2 forms ? I know the class accepts one form_class by default but is there a workaround ? class MyForm(FormView): template_name = 'index.html' form_class = ThisIsMyForm success_url = '/list' context_object_name = 'user_id' def save(self, *args, **kwargs): if not self.timeout: self.timeout = 10 super(MyModel, self).save(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_id'] = self.request.user.id return context def form_valid(self, form): form.save() return HttpResponseRedirect(self.success_url) I don't suppose I could pass it through in the context variable ? -
attaching information to a form in its GET request
I am using this code inside my template to attach info to a GET request "{% url 'foo_create'%}?fooHolder_pk={{fooHolder.pk}}" and I have a form. now I want to use fooHolder.pk to attach it as a Foreign key to foo in the form GET request. But when I do that. The POST request still shows that the foreign key is null. Note: I am using function Based Views -
How to query a model made up of multiple Foreign Keys
I'm doing the CS50 Web programming course, learning to use Django. The learning exercise basically has you recreating this pizza restaurant menu with django. I've created some models for the data, and now I'm trying to use Django templating to create a menu page for the pizzas. Here are my models: from django.db import models class intToppings(models.Model): name = models.CharField(max_length=16) intToppings = models.IntegerField() # 0 Cheese, 1/2/3, 5 Special def __str__(self): return f"{self.name}" class Size(models.Model): size = models.CharField(max_length=16) def __str__(self): return f"{self.size}" class PizzaBase(models.Model): base = models.CharField(max_length=16) def __str__(self): return f"{self.base}" class Toppings(models.Model): topping = models.CharField(max_length=32) def __str__(self): return f"{self.topping}" class Pizza(models.Model): size = models.ForeignKey(Size, on_delete=models.CASCADE) # CASCADE will delete all Regular Pizzas if their size is deleted (as opposed to .SET_NULL) base = models.ForeignKey(PizzaBase, on_delete=models.CASCADE) intToppings = models.ForeignKey(intToppings, on_delete=models.CASCADE) price = models.IntegerField() # price in cents def __str__(self): return f"{self.size} {self.base} {self.intToppings} Pizza" There's an entry "small" and "large" in the Size db, and for intToppings there is one entry with name "cheese" and an int of 0, another for "1 topping" with an int of 1, etc. And for the Pizza model, I made an entry for every combo on the menu, ie: <QuerySet [<Pizza: small Regular Cheese … -
webcam Live Stream from HTML webpage to Django server for processing the stream with OpenCV python
I have just started showing my interest in computer since couple of months ago . I'm working on project called face detection , which will basically use OpenCV Harrcascades for frontal face detection . Though there are lot of tutorials available for face detection using javascript on client side , but I want to implement the same thing using Python . I'm using Django server in backend , since it will be easier to implement the opencv python code . So far I have only created a simple HTML webpage that access the user WebCam (The script s included below). I want to stream this video from HTML webpage to Django server so that I can further process the video for face detection . Any kind of help and suggestions will be appreciated . Thank you in Advance. navigator.mediaDevices =(navigator.mediaDevices.getUserMedia||navigator.mediaDevices.webkitGetUserMedia||navigator.mediaDevices.mozGetUserMedia||navigator.mediaDevices.msGetUserMedia|navigator.mediaDevices.oGetUserMedia); var video; var webcamstream; function startWebcam() { var canvas = document.getElementById('output'); var context = canvas.getContext('2d'); video = document.getElementById('input'); if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; webcamstream = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); } video.addEventListener('play',function(){ draw(this, context, 300, 150); }, false); function draw(video, context, width, height) { context.drawImage(video, 0, 0, width, … -
Recieving an Attribute error when trying to add a new view
Im learning django, and following a tutorial online, im trying to create a new view for "home" but i keep recieving an attribute error. AttributeError: module 'pages.views' has no attribute 'home' Ive checked that I'm not doing anything wrong, and so I thought maybe the tutorial is outdated etc, but in the urls.py file, it says to do the exact same thing. Ive searched around google and tried removing spaces before the comas, changing the import name to a ".", Ive tried changing the name of the function and in the urls. views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(*args, **kwargs): return HttpResponse("<h1>Hello World!</h1>") urls.py: """trydjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from pages … -
Django rest framework: omit dict where field is empty
At the moment I get this response from a request: { "count": 1000, "results": [ { "name": "name 1", "description": "long text", "youtube": "" }, { "name": "name 2", "description": "long text", "youtube": "youtube.link" } ... ] } And I would like that I only get dicts back, where the youtube field is not empty. For example like this: { "count": 20, "results": [ { "name": "name 2", "description": "long text", "youtube": "youtube.link" } ... ] } Is there a way to realize this? I only found solution with where it was possible to skip only the fields, but I need a solution where the hole object will skip. -
flask or django for OOAD and DB project?
I would like some recommendations on what to use when creating a semester project for Object Oriented Analysis and Design(OOAD) and Database(Db). I know that Django comes with many modules and does alot of work behind the scene where as Flask is a lightweight framework. I think Django is not such a good choice because it provides many abstractions, making it difficult for newbies to understand what is going on under the hood. As a CS undergrad student, I should know about each and every component of my application. Therefore, I am more inclined to use Flask. If you think otherwise, kindly share your opinion. -
Using transactions in Django
I'm using django 1.11 on python 3.7 In a method I want to execute some database queries, mainly updating links between objects and I want to use this method to perform a check on what needs to be updated in a sync-operation. The following is an implementation: results = {} with transaction.atomic(): sid = transaction.savepoint() for speaker_user in speaker_users: # here my code checks all sorts of things, updates the database with # new connections between objects and stores them all in the # results-dict, using a lot of code in other classes which # I really dont want to change for this operation if sync_test_only: transaction.savepoint_rollback(sid) else: transaction.savepoint_commit(sid) return results This snippet is used in a method with the sync_test_only parameter that should only fill the results-dict without doing the database changes that go along with it. So this method can be used to do the actual work, when sync_test_only is False, and also only report back the work to-be-done, when sync_test_only is True Is this what the transaction.atomic() is designed for? Does this actually work in my use-case? If not, what would be a better way to achieve this behaviour? -
How do I create a table with inlineformset?
I made out the modelform in the table. How do I change the look of the table so that there would be two columns in the left - the field responsibility (textfield) and in the right under each other date input fields? Or do it without using the table on the bootstrap . form looks like templates.html <table class="table table-responsive"> {{ project_form.management_form }} {% for form in project_form.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> -
Multiple HTML option selection not working
I am developing a task management system using the django framework where supervisors can log in and assign tasks to multiple users using Django many to many field. When I log in to the admin portal, I can select multiple users at the same time which saves to the database well. But when I use the front end template, I am able to select multiple users but the selected options never get saved in the database and instead the field will be blank when viewing from the database table. Here is my Model: from django.contrib.auth.models import User class Task(models.Model): task_title = models.CharField(max_length=30, blank=True, null=True) unit = models.ForeignKey(Unit, blank=True, null=True) audit_phase_choice = ( ('Pre Engagement', 'Pre Engagement'), ('Understanding Entity', 'Understanding Entity'), ('Risk Assessment', 'Risk Assessment'), ('Performing Audit', 'Performing Audit'), ('Report', 'Report'), ) audit_phase = models.CharField(max_length=30, blank=True, null=True, choices=audit_phase_choice) assigned_by = models.CharField(max_length=30, blank=True, null=True) assigned_to = models.ManyToManyField(User, blank=True) date_assigned = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) status = models.CharField(max_length=30, blank=True, null=True) completed = models.BooleanField('Task Completed', default=False) date_completed = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) start_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) due_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) comment = models.TextField('comments', max_length=3000, default='', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __unicode__(self): return self.task_title def get_absolute_url(self): return reverse("taskmis:user_task_edit", … -
Python / DRF - error when trying to serialize a dictionary
I have the following dictionary: <type 'dict'>: {u'user2': {'username': u'user2', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': None, 'videos_overall': None, 'problems_overall': None, 'problems_attempts_overall': None, 'correct_problems_overall': None, 'forum_posts_last_week': 2, 'forum_posts_overall': 13, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': None}, u'user3': {'username': u'user3', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': 6, 'videos_overall': None, 'problems_overall': 18, 'problems_attempts_overall': 3, 'correct_problems_overall': 15, 'forum_posts_last_week': None, 'forum_posts_overall': None, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 6}, u'user1': {'username': u'user1', 'problems_attempts_last_week': 4, 'videos_last_week': 1, 'correct_problems_last_week': None, 'videos_overall': 3, 'problems_overall': 8, 'problems_attempts_overall': 4, 'correct_problems_overall': 4, 'forum_posts_last_week': 2, 'forum_posts_overall': 2, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 4}} And the following Serializer for it: class UserEngagementSerializer(serializers.Serializer): """ Serializes row data """ username = serializers.CharField() videos_overall = serializers.IntegerField() videos_last_week = serializers.IntegerField() problems_overall = serializers.IntegerField() problems_last_week = serializers.IntegerField() correct_problems_overall = serializers.IntegerField() correct_problems_last_week = serializers.IntegerField() problems_attempts_overall = serializers.IntegerField() problems_attempts_last_week = serializers.IntegerField() forum_posts_overall = serializers.IntegerField() forum_posts_last_week = serializers.IntegerField() date_last_active = serializers.DateTimeField(format=settings.DATE_FORMAT) When I try to return the results from my REST service, the following error is displayed: AttributeError: Got AttributeError when attempting to get a value for field username on serializer UserEngagementSerializer. The serializer field might be named incorrectly and not match any attribute or key on the unicode instance. Original exception text was: 'unicode' … -
I can't upload images with django
I am creating an image upload function with django. However, it is not uploaded. I don't know the code mistake, so I want to tell you. I tried variously, but if I specify default for imagefiled, default will be applied. #form class RecordCreateForm(BaseModelForm): class Meta: model = URC fields = ('image',) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(RecordCreateForm,self).__init__(*args, **kwargs) self.fields['URN'].queryset = UPRM.objects.filter(user=user) #view class RecordCreate(CreateView): model = URC form_class = RecordCreateForm template_name = 'records/urcform.html' success_url = reverse_lazy('person:home') def get_form_kwargs(self): kwargs = super(RecordCreate, self).get_form_kwargs() # get users, note: you can access request using: self.request kwargs['user'] = self.request.user return kwargs def form_valid(self, form): user = self.request.user form.instance.user = user form.instance.group = belong.objects.get(user=user).group return super().form_valid(form) #model def get_upload_path(instance, filename): n = datetime.now() prefix = "records/" ymd='/'.join([n.strftime('%Y'), n.strftime('%m'), n.strftime('%d'), ""]) + "/" directory=str(instance.user.id) + "/" name=str(uuid.uuid4()).replace("-", "") extension=os.path.splitext(filename)[-1] return ''.join([prefix, directory, ymd, name, extension]) class URC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(group, on_delete=models.CASCADE, null=True) URN = models.ForeignKey(UPRM, on_delete=models.CASCADE) UPRC = models.CharField(max_length=300) image = models.ImageField(upload_to=get_upload_path) def __str__(self): return self.UPRC #urls if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I will post any other necessary code. Sorry for the poor English. -
Webpack in react: Bundid for production
I am learning webpack and i am using it for react, my backend is django In my webpack, development server is working fine, only problem with building bundle for development. this is my webpack.common.js file: const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './client/index.js' }, plugins: [ // new CleanWebpackPlugin(['dist/*']) for < v2 versions of CleanWebpackPlugin new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: "./client/index.html", }) ], output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; and this is my webpack.prod.js file: const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'production', }); and this my webpack.dev.js fiel const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', devtool: 'inline-source-map', devServer: { contentBase: './dist' } }); And this is my package.js file { "name": "development", "version": "1.0.0", "description": "", "main": "client/index.js", "scripts": { "start": "webpack-dev-server --open --config webpack.dev.js", "build": "webpack --config webpack.prod.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.5.5", "@babel/plugin-proposal-class-properties": "^7.5.5", "@babel/preset-env": "^7.5.5", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.6", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "clean-webpack-plugin": "^0.1.17", "css-loader": … -
How to make the DRF ( Django-REST-Framework) Token persist so that it does not get lost after each page refresh?
NOTE- I am not using Python, Django, Templates for the front end. Just Pure HTML+jQuery+AJAX I have successfully implemented getting a User Based Token from the API Backend, Set it in Header File for the subsequen requests and work on the data provided by the API. But the problem is that whenever I refresh the page, the Authentication token is not there in the Header and I have to provide credentials again to access the API. Every time I refresh the page, the token is removed. How can I stop this? This is my code for setting the Header using jQuery+AJAX. $('#login').click(function () { //Send a POST Request to the URL for Token specified for User $.ajax({ type: 'POST', data: { username: $('#username').val(), password: $('#password').val() }, url: 'http://127.0.0.1:8000/rest-api/api-token-auth/', success: function (res) { console.log(res.token) //Initialize the Ajax for the first time $.ajaxSetup({ //Set the headers so that these will be in every HTTP Request headers: { "Authorization": 'Token ' + res.token } }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error: " + errorThrown); } }); }); -
Why truncatechars won't works properly?
{{ noticia.imagem_chamada }} returns "abc.jpg" {{ noticia.image_chamada|trucantechars:4 }} returns nothing! Why? -
Why doesn't unittest.mock.ANY work correctly with Django objects?
I have written a test in Django, and I'm using unittest.mock.ANY to ignore certain values in a dictionary. Here is the test: from django.test import TestCase from django.contrib.auth import get_user_model import unittest.mock as mock class Example(TestCase): def test_example(self): user = get_user_model().objects.create_user(username='example') result = {'user': user, 'number': 42} self.assertEqual( result, {'user': mock.ANY, 'number': 42} ) If I run this test, I expect it to pass. Instead, I get this failure: ====================================================================== FAIL: test_example (example.tests.Example) ---------------------------------------------------------------------- Traceback (most recent call last): File "example/tests.py", line 18, in test_example 'number': 42, AssertionError: {'user': <User: example>, 'number': 42} != {'user': <ANY>, 'number': 42} - {'number': 42, 'user': <User: example>} ? ^^^^^^^^^^^^^ + {'number': 42, 'user': <ANY>} ? ^^^ Why doesn't ANY work in this case? It seems to work with strings and numbers. -
How to add custom JS to the Froala Django framework
I am using the Django implementation of Froala (https://github.com/froala/django-froala-editor/tree/master/froala_editor). This means Froala is implemented via the Django framework using views.py, models.py and forms.py rather than initialisation as an inline Javascript. In this implementation I am able to pass options to Froala via forms.py. E.g: class PageForm(forms.ModelForm): content = forms.CharField(widget=FroalaEditor(options={ 'dragInline': False, 'toolbarButtons': [['bold', 'italic', 'subscript', 'superscript'], ['indent', 'outdent', 'formatOL', 'formatUL']], })) However, if I want to implement custom events to the editor, such as this https://www.froala.com/wysiwyg-editor/examples/drop-content example of drop content, how can I do this via Django?. Usually I would add the following code, but the editor is already initialised via Django templates so it's not clear how I would proceed. <script> var dragCallback = function (e) { e.dataTransfer.setData('Text', this.id); }; // For Firefox to work. document.querySelector('#drag-smile').addEventListener('dragstart', dragCallback); document.querySelector('#drag-text').addEventListener('dragstart', dragCallback); new FroalaEditor('div#froala-editor', { events: { initialized: function () { var editor = this; editor.events.on('drop', function (dropEvent) { // Focus at the current posisiton. editor.markers.insertAtPoint(dropEvent.originalEvent); var $marker = editor.$el.find('.fr-marker'); $marker.replaceWith(FroalaEditor.MARKERS); editor.selection.restore(); // Save into undo stack the current position. if (!editor.undo.canDo()) editor.undo.saveStep(); // Insert HTML. if (dropEvent.originalEvent.dataTransfer.getData('Text') == 'drag-smile') { editor.html.insert('<span class="fr-emoticon fr-emoticon-img" style="background: url(https://cdnjs.cloudflare.com/ajax/libs/emojione/2.0.1/assets/svg/1f600.svg)">&nbsp;</span>'); } else { editor.html.insert('Hello!'); } // Save into undo stack the changes. editor.undo.saveStep(); // Stop event … -
Django database: no such table
Before we start, I read almost every post on Stackoverflow with problem like in the title, but no solution has helped me ... I have models like this: CATEGORY_CHOICES = ( ('Django', 'Django'), ('Python', 'Python'), ('C++', 'C++'), ('Graphics', 'Graphics'), ('Text Editor', 'TextEditor'), ('Spreadsheet', 'Spreadsheet'), ('DataBase', 'DataBase'), ('Web Design', 'WebDesign'), ) class PostImage(models.Model): name = models.CharField(max_length=100, choices=CATEGORY_CHOICES) image = models.ImageField(default='default_post.jpg', upload_to='post_pics') def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) numbers_of_entries = models.IntegerField(default=0) image = models.ForeignKey(PostImage, on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('comment-detail', kwargs={'pk': self.pk}) def __str__(self): return self.text The problem is that when I try to create a database I get an error: django.db.utils.OperationalError: no such table: blog_postimage Can someone explain to me what could be going on and how to solve this problem? Before you ask, I used the following commands: python manage.py makemigrations python manage.py migrate I work on Django 2.2.4