Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering the Users only if conversation occurred
Here's my Model class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() How can I filter out the Users only if, either Current User have sent them a message or they have sent Current User a message, as we see on Social Networks? I tried something like this users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) But it's not working. It's filtering the user equal number of times as conversation occured. When i used Message.objects.filter(Q(sender=user) | Q(receiver=user)).distinct('sender') It's raising an error that "DISTINCT ON fields is not supported by this database backend" (sqlite3) Please help me with this code. Thanks in advance! -
How to add a non-Django python package to a Django project?
This is probably one of those annoying newbie questions. I'm trying to use a python package called jieba in my Django project. I've tried pip install and dragging the package folder into my apps directory, but have not succeeded in importing the package (ModuleNotFoundError). Please tell me how this could be done. Thanks! -
Django Error - unsupported operand type(s) for +: 'int' and 'strTypeError at
I received this error an i don't know why it happend. TypeError at /admin/ofac_sdn/ofac_sdn/ unsupported operand type(s) for +: 'int' and 'strTypeError. I have uploaded a csv directly to my models. This is how my admin looks like: from django.contrib import admin from ofac_sdn.models import Ofac_Sdn from ofac_sdn.models import Ofac_Add from ofac_sdn.models import Ofac_Alt # Register your models here. admin.site.register(Ofac_Sdn) admin.site.register(Ofac_Add) admin.site.register(Ofac_Alt) These are my models: class Ofac_Sdn(models.Model): number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=200, null=True) b_i = models.CharField(max_length=250, null=True) programe= models.CharField(max_length=250, null=True) last_name= models.CharField(max_length=250, null=True) more_info = models.CharField(max_length=250, null=True) vessel_call_sign = models.CharField(max_length=250, null=True) vessel_type= models.CharField(max_length=250, null=True) vessel_dwt = models.IntegerField(blank=True, null=True) tonnage = models.IntegerField(blank=True, null=True) vessel_flag = models.CharField(max_length=250, null=True) vessel_owner= models.CharField(max_length=250, null=True) dob_aka= models.CharField(max_length=250, null=True) These are my urls: urlpatterns = [ url(r'^ofac/', include('ofac_sdn.urls')), url(r'^admin/', admin.site.urls), And this is what i have in my views. There is no view created, but i should see the inputs that I have in this ofac_sdn table/model. from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1> Hi Cohen</h1>") The thing is that i can see the records in my DB from an app, but they are not displayed in the admin. Thank you in advance! -
How to use previously defined methods (funcs) in "export" function in Python/Django?
Been updating a Python/Django project, and I know pretty much nothing about it, whatsoever. Currently I have been trying to export a current view (change list) to CSV. The columns are printed fine, all the methods (functions) are displaying all info as they should/expected. When hitting "Export" link the hardcore starts, and it's been up for weeks now. Finally something started to show in my .csv file, yet still I cannot print out methods like how_many or postal_code inside the loop for elem in csv_elements: Below is a partially printed class that takes care of displaying columns on the screen and then export them to the .csv file. I didn't include all of it, just parts I personally think are important to show (I may be very wrong about this of course). Basically everything down to export_this_list works just fine. What syntax should I use to be able to re-use already defined functions (methods) inside the last function (method)? class EnrolmentAdmin(TrainingAdminMixin, admin.ModelAdmin): """EnrolmentAdmin is used for registering Enrolment model.""" form = EnrolmentForm . . list_display = ('date', 'training', 'postal_code', 'how_many') . . def postal_code(self, obj): return obj.invoice_data['postal_code'] def how_many(self, obj): return obj.total_participants how_many.short_description = "How Many Persons" . . def … -
How to stop Djago/PSQL from auto-incrementing table ID on creation failure
Currently, I have a Django project with an ItemReport table that only allows for 1 entry per day per item. Everything is fine and all except that whenever it fails with an IntegrityError (i.e. my project tried to create an ItemReport on a day when an ItemReport already exists, the object ID increments anyway. For example: September 1: Report for September 1 (ID 1) September 2: Report for September 1 (ID 1) Report for September 2 (ID 5) Models as follows: class ItemReport(BaseModel): fk_item: Item = models.ForeignKey(Item, null=False) date = models.DateField(default=now, null=False) class Meta: unique_together=(('fk_item', 'date'),) class Item(BaseModel): item_class = models.CharField(max_length=40, null=False) name = models.CharField(max_length=80, unique=True, null=False) Bit of code that gets run everytime a user logs in: for i in Item.objects.all(): try: latest_ir = ItemReport.objects.create(fk_item=i) print('Created Item Report!') except IntegrityError as e: print('ItemReport for {} for today already exists!'.format(i.name)) print('Created ItemReports!\n') -
flask restful api inside django app error :The view mysite.core.views.getallitems didn't return an HttpResponse object. It returned None instead
i am trying to add an api to my django app using flask, the purpose of the api is to return some json data if the email and password are correct via post request: url.py urlpatterns = [ url(r'^getallitems', core_views.getallitems, name='getallitems'), ] views.py @csrf_exempt def getallitems(request): def post(self): try: # user = authenticate(username='gabyawadim', password='g') # if user is not None: # else: # parser = reqparse.RequestParser() # parser.add_argument('email', type=str) # parser.add_argument('password',type=str) # args = parser.parse_args() # # _email = args['email'] # _password=args['password'] # conn = mysql.connect() # cursor = conn.cursor() # cursor.callproc('sp_getusername',(_email, _password)) # data = cursor.fetchall() # # items_list=[]; # for item in data: # i = { # 'username':item[0], # } # items_list.append(i) data = { 'name': 'Vitor', 'location': 'Finland', 'is_active': True, 'count': 28 } return JsonResponse(data, status=201) except Exception as e: return HttpResponse(status=201) Error Request Method: POST Request URL: http://127.0.0.1:8000/getallitems Django Version: 1.11.3 Exception Type: ValueError Exception Value: The view mysite.core.views.getallitems didn't return an HttpResponse object. It returned None instead. Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response, line 198 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/gaby/django projects/simple-signup-master/profile-model', '/usr/local/lib/python2.7/dist-packages/virtualenv-15.1.0-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/gaby/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Tue, 5 Sep 2017 07:25:25 +0000 … -
Retry Django-rq failed job
i'm using the Django-rq app on my django project, i'm using a custom handler, as specified in the link: DJANGO-RQ, but i'm not able to requeue a job that it was on the failure queue. Any suggestions? Thanks -
ValueError: invalid literal for int() with base 10: 'Karen'
I wanna parse excel and put data in the model(User). I got an error, ValueError: invalid literal for int() with base 10: 'Karen' . views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): rows = sheet.row(row_index) print(rows[1]) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row in rows: is_man = rows[4] != "" emp = build_employee(row[5]) user = User(user_id=row[1], name_id=row[2], name=row[3], age=rows[4],man=is_man,employee=emp) user.save() models.py is class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) name = models.CharField(max_length=200) age = models.CharField(max_length=200) man = models.BooleanField() TYPE_CHOICES = ( ('m', 'manager'), ('l', 'leader'), ('o', 'others'), ) employee =models.CharField(max_length=1, choices=TYPE_CHOICES) Excel is I cannot understand where is wrong.I tried this written way def build_employee(employee): if employee == 'leader': return User.l if employee == 'manager': return User.m if employee == 'others': return User.o but same error happens.How can I fix this? -
Django Rest Framework inner function is not getting called in custom decorator
I have added my decorator(is_same_domain_authorized_user) in urls.py. When I call the /login-user/ url. It is not calling my decorator (is_same_domain_authorized_user). Can anyone spot my mistake???? Note: I should call the decorator from urls.py itself.(this is my scenario) decorators.py def is_same_domain_authorized_user(view_func): def wrapper(request, *args, **kwargs): import pdb;pdb.set_trace() return is_same_domain_authorized_user return wrapper urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login-user/', is_same_domain_authorized_user(views.TokenView.as_view())) ] Thanks -
How to test a custom field in Django 1.11.1
I've create a custom field in Django class MyField(models.CharField): description = "My awesome field" # ... I want to create a unit-test in which I make a temporary/ephemeral model that uses the field. My goal is to test that the functions like to_python, from_db_value, and validate, are implemented correctly from the view of an actual Model. I also don't want to have the Model included in the production database. I've looked up a few different means of doing this and they do not work: https://www.kurup.org/blog/2014/07/21/django-test-models https://stackoverflow.com/a/503435/2097917 https://blog.bixly.com/bixly-how-to-dynamically-adding-models-for-testing-in-django http://www.akshayshah.org/post/testing-django-fields/ These all seem to be outdated. I would like to be able to define the model within an tests.py file (i.e. projectroot/myapp/tests.py) and somehow have the setUp add the model to the database: class MyModelTest(models.Model): myField = MyField() class MyFieldTestCase(TestCase): def setUp(): # ... do something funky to create the table def test_foo(self): myModel = MyModel.objects.create(myField="something") self.assertEqual(myModel.myField, "something") -
Django ORM: exclude does not return expected result
Django 1.11.4 I'd like to select only frames with lost items. If an item is lost, lost_day is not empty. The problem: I can't understand what is going on in case of "Wrong result". I would say, it should return the same result as the "Correct result". Could you help me realize what is wrong with it? Wrong result >>> Frame.objects.all().exclude(item__lost_day__isnull=True) <QuerySet [<Frame: 3>]> Correct result: >>> Frame.objects.all().filter(item__lost_day__isnull=False) <QuerySet [<Frame: 1>, <Frame: 3>]> Self-checking >>> a = Item.objects.get(pk=3) >>> a.lost_day is None True >>> b = Item.objects.get(pk=1) >>> b.lost_day is None False models.py class Frame(models.Model): pass class Item(models.Model): frame = models.ForeignKey(Frame, blank=False, on_delete=models.PROTECT, verbose_name=_("frame")) lost_day = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, verbose_name=_("lost")) -
post_detail() view missing required positional arguments:
This is the debug page view of the error . I'm beginner to django . I am facing this problem that I can't get the post detail view with year , month and post . Error is post_detail() missing 4 required positional arguments: 'year', 'month', 'day', and 'post'. this is models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class Post(models.Model): STAUTS_CHOICE = ( ('draft','Draft'),('published','Published'),) title =models.CharField(max_length =250) slug = models.SlugField(max_length =250) author = models.ForeignKey(User,related_name='blog_post') body = models.TextField() publish =models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) udated = models.DateTimeField(auto_now=True) status = models.CharField(max_length =250 , choices = STAUTS_CHOICE , default = 'draft') class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('blog:post_detail', args = [self.slug]) def __str__(self): return self.title ______________________________________________________________ this is views.py from django.shortcuts import render , get_object_or_404 from .models import Post def post_list(request): post = Post.objects.all()[Error :][1] return render(request,'blog/post/list.html',{'post':post}) def post_detail(request,slug,year, month,day,post): post = get_object_or_404(Post, slug = slug , status = 'published' ,publish_year = year, publish_month = month , publish_day = day) return render(request,'blog/post/detail.html',{'post':post}) this is urls.py from django.conf.urls import url from .import views urlpatterns = [ url(r'^post_list',views.post_list,name ='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'r'(?P<slug>[-\w]+)/$',views.post_detail,name='post_detail'), url(r'^(?P<slug>[-\w]+)/$',views.post_detail,name= 'post_detail'), -
Can't Add JWT_AUTH in setting
I want to set the expiration period for JWT token, so I added this on settings.py JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30), } Once I add it on settings, I'm getting this error django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. What's wrong with 'JWT_AUTH'? These are related parts of settings.py INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'profiles', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] # localhost:8000/ SITE_ID = 9 -
Django Pagination won't sort second page
I'm using Django pagination, and everything is working fine except only one page is sorted. What I have tried: if request.method == 'POST': if request.POST.get('sort_by') == 'price': products_list = Product.objects.filter(category = category).order_by('price') selected_sort_price = "selected" elif request.POST.get('sort_by') == 'name': products_list = Product.objects.filter(category = category).order_by('name') selected_sort_name = "selected" elif request.POST.get('sort_by') == 'date': products_list = Product.objects.filter(category = category).order_by('-id') selected_sort_date = "selected" show=request.POST.get('show', 5) else: products_list=Product.objects.filter(category = category).order_by('-id') ... page = request.GET.get('page', 1) paginator = Paginator(products_list, show) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) The above only works if there is post call, if no post call, then it is sorted by date of creation. So if a user wants to sort by price, he will select price from a dropdown menu, and onchange, form will be submitted and objects sorted accordingly. The problem is, when the user goes to second page, then everything goes back to default, because no post calls are made, and the previous post data isn't retained. What can I do to make the sorting apply to all pages? Looking for some direction, -
Django: Convert form data into 'clean url'
Let's say I have the following form: <form id="search-form" class="form-horizontal" method="GET" action="/results/" role="form"> <input type="text" class="form-control" id="query" name="query"> <button type="submit" form="search-form" class="btn btn-primary"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </button> </form> Currently, when the form is submitted, the url contains the query as a parameter, like so: www.<my-domain>.com/results?query=<some-query>. However, for SEO purposes, I want to convert this to a 'clean url', which would look more like this: www.<my-domain>.com/results/<some-query>. I've made the following modifications to my urls.py: urlpatterns = [ ... url(r'^results/(?P<query>[a-zA-Z ]+)$', views.ResultsView.as_view(), name="results"), ... ] So I should be able to grab the query value in my ResultsView like this: class ResultsView(TemplateView): def dispatch(self, request, *args, **kwargs): query = kwargs.get('query') How can I submit the form so it'll match with the corresponding url pattern? I've tried fiddling with the form action passing the input id to it, like this: action="/results/query/", but obviously, it thinks query is a literal string, and doesn't replace it with the value of the input. -
TypeError: 'Cell' object does not support indexing
I wanna parse excel and put data in the model(User). I got an error, Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/xxx/testapp/app/views.py", line 17, in <module> is_man = row[4] != "" TypeError: 'Cell' object does not support indexing views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): rows = sheet.row(row_index) print(rows) for row in rows: is_man = row[4] != "" user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man) user.save() I think rows is not cell but list,so I really cannot understand why it is called 'Cell' and how should I fix this. I tried to fix this,so change rows cell into list like for row_index in range(sheet.nrows): rows = sheet.row(row_index) rows = list(rows) print(rows) however,same error happens.What should I do to fix this? -
Integrate R with Django
I have an R file which contains the following code: x<- 4 print(x) I want to return this value of x in my localhost using Django. How can I achieve this? -
Create multiple records in database from a single form submission in Django
How can I create several records from a single form? In my application, an administrator manages several routes. models.py class Route(models.Model): milage = models.PositiveSmallIntegerField(... fuel = models.PositiveSmallIntegerField(... start_time = models.DateTimeField(... route_time = models.DateTimeField(... date = models.DateTimeField(... class Driver(models.Model): driver = models.CharField(max_length... usual_route = models.ForeignKey(Route) class Daily(models.Model): date = models.DateTimeField(... route = models.ForeignKey(Route) driver = models.ForeignKey(Driver) stage = models.PositiveSmallIntegerField(... Assume that an administrator manages 10 routes. What I want is for an administrator to start each day by creating a daily schedule by submitting a form with a date. On submission, I'm want to create 10 records in the database, one for each route. All 10 records will have the same date as submitted on the form, but each will have a different driver and route. I know how to add static information to a single record but I don't know how to: Create 10 records from a single post Dynamically change a field (i.e. driver, route) for each record. Currently the view looks like this. All records have stage = 1: class DailySchedule(CreateView): model = Daily form class = ... def form_valid(self, form): instance = form.save(commit = False) instance.stage = 1 Any ideas? Thanks. -
Java Script code not responding
I am trying to implement the read more and read less feature on click on link for my articles app in Django. But my java script code is not responding when I click on the read more link. Here are my files. <script type="text/javascript"> $(document).ready(function (){ var $el, $p, $up, $ps; $('.button').on("click", function(){ $el =$(this); $p= $el.parent(); $up= $p.parent(); $ph= $up.find(".para"); $ps= $up.find(".rest-content") ; if ($ps.is(':hidden')) { $p.load(function () { $ps.show(), $el.html("(read-less)"), $ph.hide(), console.log("It worked") ; }); } else { $ps.hide(); $el.html("(read-more)"); $ph.show(); } return false; }); }); </script> {% if article.post|length > 300 %} <p class="para">{{ article.post|truncatechars:300}}</p> <p class="rest-content">{{ article.post}}</p> <p class="read-more"><a href="#" class="button" >(read more)</a></p><br> {% else %} <p class="para">{{ article.post }}</p> <br> {% endif %} -
How to get the XMLHttpResponse send data in my views.py?
In the template I send data use XMLHttpResponse. My code is below: ... <input type="button" value="ajax1" onclick="ajax1()"> <script> function ajax1(){ var xhr = new XMLHttpRequest(); xhr.open('GET', '/ajax1/', true); xhr.send("name=root;pwd=123"); // send data } </script> But how can I in the views.py to receive the data? In my views.py: def ajax1(request): print request.GET.get('name'), request.GET.get('pwd') # all is None. return HttpResponse('ajax1') You see, I use request.GET.get(param_key) to get the data failed. How to get the XMLHttpResponse send data in my views.py? -
How can I put excel data to choices field?
I wanna put data in model by parsing excel. models.py is class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) age = models.CharField(max_length=200) man = models.BooleanField() TYPE_CHOICES = ( ('m', 'manager'), ('l', 'leader'), ('o', 'others'), ) employee =models.CharField(max_length=1, choices=TYPE_CHOICES) views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): rows = sheet.row(row_index) print(rows) for row in rows: is_man = row[4] != "" user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man,employee=row[4]) user.save() Now I cannot understand how I should put data to employee variable. Excel is like I wanna put m or l or o to employee model, but I cannot understand how to be able to done so by using choices field.Or am I wrong to use choices field to achieve my goal? -
Enter text immediately into box for autocomplete
I have a formset with django-autocomplete-light on the full_name field. I want to be able to TAB into the box and type. Currently, however, if I tab into the box, I can't type, it's like a ChoiceField, but if I click on it (or spacebar) it opens up the dropdown menu and I can type into the area below the menu I clicked on, as though I was typing in the first choice option. from functools import partial, wraps from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from django import forms from extra_views import ModelFormSetView, InlineFormSetView, InlineFormSet, CreateWithInlinesView from dal import autocomplete, forward from .models import Record, Ledger, Person from pdb import set_trace as st # Create your views here. class NameAutocomplete(autocomplete.Select2ListView): def get_list(self): return self.forwarded.get('full_name_choices', []) def create_form_class(persons): full_name_choices = [p.full_name for p in persons] class RecordForm(forms.ModelForm): full_name = autocomplete.Select2ListChoiceField( widget=autocomplete.ListSelect2( url='name_autocomplete', forward=[ forward.Const( full_name_choices, 'full_name_choices' ) ] ) ) class Meta: model = Record fields = ['score', 'full_name', ] return RecordForm def create_records(request, pk): ledger_id = pk ledger = Ledger.objects.get(pk=ledger_id) persons = Person.objects.filter(ledger_id=ledger_id) RecordInlineFormSet = forms.inlineformset_factory( Ledger, Record, can_delete=False, form=create_form_class(persons), extra=len(persons), ) if request.method == 'POST': formset = RecordInlineFormSet( request.POST, instance=ledger, ) if formset.is_valid(): … -
how to package python+django+excel project to windows exe file
I have written a project using python + django. and the data it needs is stored in excel not in the database. How can I package this project to .exe file so that it can run in the windows without all the python or django environment. I would really appreciate it if anyone can help. It is really important to me. Any documentations or forums would be a great help. Thank you all. -
Django How to pass object id via form action?
I'm still having problems passing an object's id in the url of a form. adjust.html <form action="{% url 'classroom:deleteblock' classroom.id %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="submit" /> </form> models.py class Classroom(models.Model): COURSE_NAME = ( ('MA8', 'Math 8'), ('SC10', 'Science 10'), ('PH11', 'Physics 11'), ('PH12', 'Physics 12'), ) BLOCK_NUMBER = ( ('11', 'Block 1-1'), ('12', 'Block 1-2'), ('13', 'Block 1-3'), ('14', 'Block 1-4'), ('21', 'Block 2-1'), ('22', 'Block 2-2'), ('23', 'Block 2-3'), ('24', 'Block 2-4'), ) class_list = models.TextField() course_name = models.CharField(max_length=20, choices=COURSE_NAME) course_block = models.CharField(max_length=10, choices=BLOCK_NUMBER) group_size = models.IntegerField(default=3) def __str__(self): return self.get_course_block_display() def save(self, *args, **kwargs): super(Classroom, self).save(*args, **kwargs) # overrides the default save function to parse the class list studentList = [] studentList = self.class_list.split('\n') print (studentList) for line in studentList: line = line.strip('\r') s = Student.objects.create(nickname = line, classroom = self) class DeleteForm(ModelForm): class Meta: model = Classroom fields = ['course_block'] views.py class BlockDeleteView(DeleteView): model = Classroom delete_block_view = BlockDeleteView.as_view() def adjust(request): if request.method == 'POST': form = DeleteForm(request.POST) if form.is_valid(): return render(request, 'classroom/classroom_form.html') else: form = DeleteForm() return render(request, 'classroom/adjust.html', {'form': form}) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^submitted', views.submitted, name='submitted'), url(r'^classup/$', create_classroom_view, name='classroom'), url(r'^block/$', views.block, name='block'), url(r'^(?P<pk>[09-]+)/deleteblock/$', delete_block_view, name='deleteblock'), … -
What program to use to add drag and drop functionality within a webpage
I'm looking for guidance on where to begin looking for a way to add drag-and-drop functionality within a web page. I know very little about web page development, so any insight is appreciated. What I am wanting to build is a web page that will have objects (e.g. image thumbnails) in a side pane that you can drag and drop into the main window to lay out how you want. In my case it will be in a structure like a binary tree where each image can be dropped in as a parent or child of the existing nodes. Where should I begin looking for a program that will allow this type of functionality? I have experience with Python, so I was hoping something like Django might do the trick, but since I know so little about web design, I really don't know if that is the right place to begin.