Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot Import Name X
Currently trying to create a Models.py file for my Django project to be able to store questions in a database. But every time i reference the model in my forms.py for the Meta Class I receive an import error. forms.py from django import forms from django.contrib.auth.models import User from .models import Q1 Question1_CHOICES = ( ('1', 'I Like Smoking'), ('2', 'I Dislike Smoking'), ('3', 'I Do not Smoke'), ('4', 'I Do not mind Smokers '), ) class QuestionForm(forms.Form): Q1 = forms.MultipleChoiceField( required=False, widget=forms.RadioSelect, choices=Question1_CHOICES ) class Meta: model = Q1 fields = ['question'] widgets = { 'question': forms.RadioSelect() } Models.py from django.db import models from .forms import Question1_CHOICES class Q1(models.Model): question = models.CharField(max_length=50, choices=Question1_CHOICES) My Error is as follows File "forms.py", line 3, in from .models import Q1 Any help would be really appreciated as I'm stumped what it could be -
How can I implement shadow editing (or revisions) across a model with relationships (django)?
While this is django+postgresql, the answer could be generic sql or from a "Databases for Dummies" book. We have a database with several interrelated models (one to one, one to many, and many to many fields). We'd like to allow a user to shadow-edit the database, and only publish once he's happy with the changes. For a single model, I could use something like django-reversions, and I could handle the relationships by hand in a hacky sort of way. But, this would have several side effects: The models not in control of django could change, which would update the data immediately (no shadow copy) Since external relationships are being stored, things will get strange if there are a lot of edits to them. Huge amount of work 'catching' CRUD operations and routing them to published or draft entries (if particular user is editing) Need to fix all pks on relations when publishing (more hack-titude) What I'd really like is something that would do this: Allow editing of many related tables at once, over many REST CRUD calls, and only updating after 'publishing' Allow rolling back to previous version (versioning) Any ideas? -
Django paginated master-detail CBV
I have the following models: class Book(models.Model): name = models.CharField() authors = models.ManyToManyField('Author', blank=True, verbose_name=_('authors')) class Author(models.Model): name = models.CharField() def my_books(self) -> List[Book]: return Book.objects.filter(authors__exact=self.id).all() I am displaying author and related books via DetailView: class AuthorDetailView(generic.DetailView): model = Author In the template, I am accessing books of a given author via author.my_books() method - but this returns ALL ROWS from database. I want to enable pagination on the book rows. How do I do that in CBV? -
Django: Filter foreignkey objects by default on model
I have 3 models what create a data hierarchy: Brand, Family, Car. In displaying the DetailView for the Brand, I have a table with a Brand's families (foreignkey) and in that table, I then have a property for num_cars to display the number of cars with a foreignkey back to that family. Example: Brand:Ford Families: Taurus 150 F150 100 F250 0 This is displayed in my template as: {% for family in brand.families.all %} {{ family }} {{ family.num_cars }} {% endfor %} Is there a way to filter the families by the number of cars so I don't see results where there are 0 cars? I can do this in the template with: {% for family in brand.families.all %} {% if family.num_cars > 0 %} {{ family }} {{ family.num_cars }} {% endif %} {% endfor %} However that doesn't seem like the ideal solution. I'd like to have this in my models (if possible). Any ideas? -
How to get the user input in an incomplete Django form field?
I have a "survey" form which has fields - name, id and age. I would like to capture the user entry in the "id" field before the user submits the form for scanning the entered "id" in my database table. How can I capture this entered data and use it in my view function for scanning the database? Can I use javascript to pass the user input to my view function? How would that look like? I am a newbie in Django development so any suggestions would help me big time! Here is the view function I am trying to design that scans the "id" from my survey table and if there is a match in the past 30 days, then it returns an alert pop up to the user to take the survey or not. def search(request): if request.method == 'POST': # If the form has been submitted... form = TopicForm(request.GET) # A form bound to the POST data if form.is_valid(): x = form.cleaned_data['id'] else: x = form.cleaned_data['id'] x = request.POST.get('url') posts = survey.objects.filter('id'=x) posts1 = survey.objects.filter(date=posts) delta= date.today - posts1 if delta.days <=30: return HttpResponse('Survey NOT required') else: return HttpResponse('Survey required') SURVEY TEMPLATE FORM.HTML <form action="{% url 'FCR1' … -
Am getting a ProgrammingError when I try to access my messages from my heroku app. Am I missing something?
Environment: Request Method: GET Request URL: https://my-trial-project.herokuapp.com/messages/ Django Version: 1.10.1 Python Version: 2.7.13 Installed Applications: [ u'django.contrib.admin', u'django.contrib.auth', u'django.contrib.contenttypes', u'django.contrib.sessions', u'django.contrib.messages', u'django.contrib.staticfiles', u'Trial_app', u'authentication', u'feeds', u'user_profile', u'user_messages', u'debug_toolbar' ] Installed Middleware: [ u'django.middleware.security.SecurityMiddleware', u'django.contrib.sessions.middleware.SessionMiddleware', u'django.middleware.common.CommonMiddleware', u'django.middleware.csrf.CsrfViewMiddleware', u'django.contrib.auth.middleware.AuthenticationMiddleware', u'django.contrib.messages.middleware.MessageMiddleware', u'django.middleware.clickjacking.XFrameOptionsMiddleware', u'debug_toolbar.middleware.DebugToolbarMiddleware' ] Traceback: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/app/user_messages/views.py" in user_messages 58. msg_to_user = UserMessages.get_sent_messages(current_user) File "/app/user_messages/models.py" in get_sent_messages 34. msgs = UserMessages.objects.read_message(message_data) File "/app/user_messages/models.py" in read_message 10. for _id in message_id: File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in iter 256. self._fetch_all() File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all 1087. self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in iter 155. for row in compiler.results_iter(): File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in results_iter 789. results = self.execute_sql(MULTI) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 835. cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py" in exit 94. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) Exception Type: ProgrammingError at /messages/ Exception Value: column user_messages_usermessages.user_to_id does not exist LINE 1: ...sages_id" FROM "user_messages_usermessages" WHERE … -
Django path to uploaded image
Learning Django, I wanted to build a site where people can upload pictures. The whole account application ( create account, change passward etc. ) is completed, now I have to create a aplication that allows the user to upload images. I am now finding myself writing the final template, but I don't know how to specify the path the the saved picture. I have created an Image model that saves the image file offered by the user to the /media/images directory like so : image = models.ImageField(upload_to='images') . The form that the user has to complete is : class ImagePost(forms.ModelForm): class Meta: model = Image fields = ('image','description','title') So, he has to provide the image, a description and the title (description and title are 2 other attributes of the class Image model. Here is the view that handles the logic part : @login_required def image_create(request): if request.method == 'POST': # form is sent form = ImagePost(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = cd.save(commit=False) # assign current user to the item new_item.user = request.user new_item.save() # redirect to new created item detail view return redirect(new_item.get_absolute_url()) else: # build form with data provided by the bookmarklet … -
Django DetailView - How to change the get_object to check a field
So I want to make a DetailView that shows a photo by itself and its associated information. However, I want to have it make sure the user has permission to access the photo as well. This is the urls.py for the view url(r'^photo/(?P<slug>[\-\d\w]+)/$', views.PhotoDetail.as_view(), name='photo'), This the is views.py class PhotoDetail(DetailView): template_name = 'otologue/photo_detail.html' def get_object(self, queryset=None): slug = self.get_slug_field() print(slug) object_instance = Photo.objects.filter(slug=slug) print(object_instance) object_user = object_instance.photoextended.user user = get_object_or_404(User, username=self.request.user) # Get the user in the view if object_user != user: # See if the object_user is the same as the user return HttpResponseForbidden('Permission Error') else: return object_instance As you can see I try to get_slug_field() but when I print it it only says 'slug' when the slug should say the objects slug which is in the url. From this the object_instance doesn't have any object and then why I try to get the user from it, it can't find any data. Please Help! -
HTML Table Data To Django Back End via AJAX
Im trying to get from an html table on the front end of my webpage to the django backend where I can load it into a dataframe or something more organized. Right now my set up is as follows: index.html <script type="text/javascript"> // get table data function getJson(){ var table = document.getElementById('example'); var tr = table.getElementsByTagName('tr'); var jObject = {} for (var i = 0; i < tr.length; i++){ var td = tr[i].getElementsByTagName('td'); for (var j = 0; j < td.length; j++){ jObject[+ i + '_td_' + j] = td[j].innerHTML; } } return jObject; } // send ajax $(document).on('click', '#add', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "/ajax/", data: { name: getJson(), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function() { alert("Reg successfully.") } }); }); </script> My view doesnt do much right now because I'm getting the data in the form of: (u'name[57_td_14]', u'101') (u'name[18_td_14]', u'99') (u'name[21_td_2]', u'3000') (u'name[1_td_15]', u'105') (u'name[66_td_2]', u'4600') (u'name[31_td_8]', u'19.7') Does anyone have a better approach to grab table data and present it in a way thats easier to manipulate on the django side? views.py def ajax(request): if request.method == 'POST': for key, value in request.POST.items(): print(key, value) return HttpResponse(' ') else: return HttpResponse('No') -
TemplateDoesNotExist (about jfu)
django-jfu is django jquery file uploader (https://github.com/Alem/django-jfu) jfutags.py: from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', upload_handler_name = 'jfu_upload', *args, **kwargs ): """ Displays a form for uploading files using jQuery File Upload. A user may use both a custom template or a custom upload-handling URL name by supplying values for template_name and upload_handler_name respectively. Any additionally supplied positional and keyword arguments are directly forwarded to the named custom upload-handling URL. """ context.update( { 'JQ_OPEN' : '{%', 'JQ_CLOSE' : '%}', 'upload_handler_url': reverse( upload_handler_name, args = args, kwargs = kwargs ), } ) # Use the request context variable, injected # by django.core.context_processors.request, # to generate the CSRF token. context.update( csrf( context.get('request') ) ) t = loader.get_template( template_name ) return t.render( Context( context ) ) In my topic.html , I used its tags in this way and I want topic.id to be passed as an argument to the name='topic_pic_upload' URL. {% load jfutags %} {% jfu 'upload_form.html' 'topic_pic_upload' topic.id} HOWEVER,it turns out TemplateDoesNotExist at /topic/122/ forum/topic.html when it shows Using loader django.template.loaders.app_directories.Loader: C:\FairyBBS\account\templates\forum\topic.html (File does not exist) C:\FairyBBS\forum\templates\forum\topic.html **(File exists)** -
How to save to a database on click
In my Pervious question, i recently asked how to make forms.py in Django 1.9 show in HTML. now that this is done im trying to make a button which when the selection has been made (in this case it's radiobuttons) it will post to the database and move on with the questionaire. Currently im attempting to make it post in my Views.py but im having no luck in making it send the data. def question1(request): question_form = QuestionForm() if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): return render(request, 'music.questions2,html') return render(request, 'music/question1.html', locals()) Would really appreciate the help in making this happen. -
Filling model fields using both data from form and other sources
I got a model that represents user's financial account: class Account(models.Model): currencies_list = [currency.alpha_3 for currency in pycountry.countries] currencies_tuples = ((currency, currency) for currency in currencies_list) user = models.ForeignKey(User) name = models.CharField(max_length=50) currency = models.CharField(max_length=3, choices=currencies_tuples) initial_balance = models.DecimalField(max_digits=10, decimal_places=2) current_balance = models.DecimalField(max_digits=10, decimal_places=2) I want to allow user to create a new account using following view: def new_account(request): if request.method == "POST": form = AccountForm(request.POST) if form.is_valid(): account = form.save(commit=False) account.save() return redirect('index') else: form = AccountForm() return render(request, 'expenses/new_account.html', {'form': form}) and form: class AccountForm(ModelForm): class Meta: model = Account fields = ['name', 'currency', 'initial_balance'] I'm only letting user to fill three fields: name, currency and initial_balance. I want fields user and current_balance to be filled automatically: user by copying currently logged user ID and current_balance by copying value provided by user for initial_balance field. May I kindly ask you to point me in the right direction? -
Django Rest Framework many to many with extra fields serialization
class Item(models.Model): name = models.CharField(max_length=20) class Meals(models.Model): name = models.CharField(max_length=50) ingredients = models.ManyToManyField(Item, through='MealRecipe') class Menu(models.Model): name = models.CharField(max_length=50) meals = models.ManyToManyField(Meals,through='CompMenu') class CompMenu(models.Model): TYPE_COMP = ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) menu = models.ForeignKey(Menu) meal = models.ForeignKey(Meals) type = models.CharField(max_length=1, choices=TYPE_COMP) class MealRecipe(models.Model): meal = models.ForeignKey(Meal) item = models.ForeignKey(Item) qty = models.IntegerField() If i need to serialze queryset how can i do it, there is no documentation about it, i need a JSON with item_id, MealRecipe_qty. Do i have to serialze all models ? I need this to manipualte the recipe quantities on the front end based on the selected menu. -
Django raw query - how to pass postgres array value as parameter?
I'm working with raw SQL queries in a Django+PostgreSQL app, and I've come across the problem of having to pass as parameter a PostgreSQL Array value (of type tags = ArrayField(m.CharField(max_length=80) in app / tags character varying(80)[] in db). I'm using code like this: Product.objects.raw('SELECT * FROM myapp_code_products WHERE tags @> %s', [ ['red'] # also tried with simply string '{"red"}' but that didn't work either, also tried with tuple ]) ...in the hope of getting SQL like this generated: SELECT * FROM myapp_code_products WHERE (tags @> '{"red"}') but I either get simply nothing substituted like (tags @>) or list or tuple substitution like (tags @> ['red']) or (tags @> ('red')) and obviously none of this result in a valid contains query. And, if anyone is wondering, the substituted parameter is user-supplied, so just completely bypassing parameter substitution here is not an option security-wise. Note: also, using raw queries is to be considered a requirement here, using querysets and model queries is not an option here. (Detail: I'm using Django 1.10.5 with Python 3.6.0 and PostgreSQL 9.3 on Windows 10 64bit) -
Check if day is valid for selected month Django forms
I have a form where the user types a day (number between 1 and 31) and then selects a month from a list and then types a year. The problem is that when a date such as (31 February) will throw the following error: day is out of range for month Is there a way I can check if the day is valid for that month (and year if it is a leap year) in the form? -
How do I add uptional parameters to cloudinary_fileupload() in jquery?
I have read to documentation on how to add optional parameters to cloudinary's jquery function that is used to directly upload to the cloud. It the photo is uploaded to the cloud correctly, however I want to pass to the cloudinary_fileupload function either an upload preset, or a transformation in the function itself. I have tried alot of things to no avail. Here is my code $(function () { $('#direct_upload input[type="file"]').cloudinary_fileupload( { dropZone: '#direct_upload'}, {"transformation": "c_limit,h_400,w_400", "tags":"123"} I have also tried $(function () { $('#direct_upload input[type="file"]').cloudinary_fileupload( { dropZone: '#direct_upload', "transformation": "c_limit,h_400,w_400", "tags":"123"}, and other variations but nothing has worked! Thanks in advance -
Django: how to send email when the publish date is reached for a blog item
I have craeted a blog using Django My blog model contains: Title Description Image Publish_date Date_created Now whenever i reach the pub_date, i want to send email or send some notification to an android app. How to do that. -
Django Server Trying To Receive Table Data via Ajax
I want to grab all table data from my page and send it to the server, I believe the below code does this correctly, but my django server sends a 500 error back. <script type="text/javascript"> // Function Gets All Table Info function getJson(){ var table = document.getElementById('example'); var tr = table.getElementsByTagName('tr'); var jObject = {} for (var i = 0; i < tr.length; i++){ var td = tr[i].getElementsByTagName('td'); for (var j = 0; j < td.length; j++){ jObject['table_tr' + i + '_td_' + j] = td[j].innerHTML; } } return jObject; } // Ajax Call To Server $(document).on('click', '#add', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "/ajax/", data: { name: getJson(), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function() { alert("Reg successfully.") } }); }); </script> Below is my django function, I wasnt really trying to do much other than test out if its working, im not sure if there is an error in my js or in my view. def ajax(request): if request.method == 'POST': name = request.POST['name'] return HttpResponse(name) else: return HttpResponse('No') -
Integrating other python apps in Django
I have multiple python apps that are gathering and doing manipulation with data. At this moment I use pewee as a database, but I am considering integrating them with Django, mostly because of the Django admin (more easy to manually check/modify data for me and non-devs) instead of building an interface myself. The external apps run independently one of another and do a lot of database operations. They are gathering data from online and offline(excel, csv) sources, and do not run on a server(can be considered desktop apps). It is possible to start an app from Django admin, by adding a button ? What is the best way to add them from a project organization point of view ? -
Collect subtotals and add them for specific user
I have the following query: per_person = report.values('order__user', 'order__date').annotate(per_order=Sum(F('quantity') * (F('product__product__price')), output_field=DecimalField()))\ .annotate(user_cost=Sum( Case( When(take_away=True, then=((F('quantity')*1))), When(take_away=False, then=(Value(0))), output_field=DecimalField() )) +Case( When(per_order__gt=12, then=(Sum(F('quantity') * (F('product__product__price')))) - 6), When(per_order__lte=12, then=(((Sum(F('quantity') * (F('product__product__price'))) * 0.5)))), output_field=DecimalField(decimal_places=2)) )\ .annotate(company_cost=Case( When(per_order__gt=12, then=((Value(6)))), When(per_order__lte=12, then=(((Sum(F('quantity')*(F('product__product__price')))*0.5)))), output_field=DecimalField(decimal_places=2) )) which give a result like: {'order__user': 1, 'per_order': Decimal('5.00'), 'user_cost': Decimal('2.500'), 'company_cost': Decimal('2.500'), 'order__date': datetime.date(2017, 3, 7)} {'order__user': 47, 'per_order': Decimal('7.00'), 'user_cost': Decimal('3.500'), 'company_cost': Decimal('3.500'), 'order__date': datetime.date(2017, 3, 6)} {'order__user': 1, 'per_order': Decimal('18.00'), 'user_cost': Decimal('12.00'), 'company_cost': Decimal('6'), 'order__date': datetime.date(2017, 3, 6)} How can I collect and add each of the subtotals like 'per_order', 'user_cost', and 'company_cost' for a specific user (e.g. 'order__user': 1)? -
Allow only the author of the post to edit in class based views- Django?
views.py class EditEducation(UserPassesTestMixin, LoginRequiredMixin, UpdateView): model = Education form_class = EducationForm template_name="education/add_education.html" def test_func(self): x = self.request.user.pk print (x) y = Posts.objects.get(user='user') print (y) if x == y: return True else: if self.request.user.is_authenticated(): raise Http404("You are not allowed to edit this Post") models.py class Posts(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) post = models.CharField(max_length=1200, blank=False) How do i match the loggedin user and the user object of the Post i could not find any solution since i am using class based views. -
Celery: how to test task that schedules itself to run again
I have a celery task that, if a certain condition is not yet reached, schedules itself to run again after a while. When I test it I use: @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_ALWAYS_EAGER=True, BROKER_BACKEND='memory') So the task repeatedly schedules itself to run again immediately instead of the date I intended, and it generates an infinite loop and I get the error: RuntimeError: maximum recursion depth exceeded in cmp How can I test this task without triggering this error? Thanks I don't know if the code from the test is relevant, but here it is: def create_new_deadline(gig): if gig.next_deadline is not None: cancel_overdue_gig.apply_async((gig.id,), eta = gig.next_deadline) # cancel gig whose deadline was not met @task def cancel_overdue_gig(gig_id): gig = Gig.objects.get(id=gig_id) if gig.next_deadline and gig.next_deadline <= timezone.now(): gig.status = 12 gig.next_deadline = None gig.cancelation_reason = _( 'Deadline not met by ') + gig.venue.display_name gig.save() else: create_new_deadline(gig) Basically I check if there's a deadline and if the deadline has passed. If it hasn't, that means the deadline has been postponed, and I set another check for the next deadline. If it has, I change the status to cancelled and delete the deadline. -
NoReverseMatch Error Django - UpdateView
I have a view which the user can create/update their posts. However, when the user has finished their editing, I want them to return back to the post (summary). However, there's an error somewhere which I can't find. Any ideas on what the issue may be? Error: 1) Reverse for 'aircraftdetail' with arguments '()' and keyword arguments '{'id': 2}' not found. 0 pattern(s) tried: [] 2) return HttpResponseRedirect(instance.get_absolute_url()) 3) return reverse('aircraftdetail', kwargs={"id": self.id}) views.py def AircraftUpdate(request, id=None): instance = get_object_or_404(Aircraft, id=id) form = AircraftForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context={"aircraft":instance, "form":form} return render(request,'aircraft_form.html',context) Models.py class Aircraft(models.Model): title = models.CharField(max_length=50, default="") image = models.ImageField(upload_to = 'static/image_upload', blank=True) cost = models.DecimalField(max_digits=8, decimal_places=3) def get_absolute_url(self): return reverse('aircraftdetail', kwargs={"id": self.id}) Urls.py - Aircraft urlpatterns = [ url(r'^detail/(?P<id>\d+)/$', views.AircraftDetail, name='AircraftDetail'), url(r'^detail/(?P<id>\d+)/edit/$', views.AircraftUpdate, name='AircraftEdit'), url(r'^$', views.AircrafList, name='aircraft'),] Urls.py AviationSite (Main) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'aircraft/', include('aircraft.urls')), url(r'^login/', login_view, name="login"), url(r'^logout/', logout_view, name="logout"), url(r'^register/', register_view, name="register"), url(r'^aircraft/create/$', AircraftCreate),] -
Testing Wagtail page views
I want to test my views functionality for a Wagtail Page that uses the RoutablePageMixin. I've found that Wagtail includes some testing functionality, but I'm trying to check the content on different urls. Although the Wagtail test functions work, testing using self.client.get doesn't work -- I get an 404 response. I'm trying the following test: def test_subpage(self): response = self.client.get( self.page.full_url + self.page.reverse_subpage('subpage') ) self.assertEqual(response.status_code, 200, 'Request the open positions page') I assume the error lies in the way in which the page is created. I have used several ways, but cannot find one for which this works. The most intuitive way I found to create the page is the following: def setUp(self): self.login() parent = Page.get_root_nodes()[0] # Home self.assertCanCreate(parent, MyPage, { 'title': 'Title!', 'title_sv': 'Title2!', 'slug': 'test', 'published': datetime.datetime.now(), }) self.page = MyPage.objects.get(slug='apply') The subpages have been manually tested and do seem to work. -
django backend with mxgraphh
I want to use mxgraph to build my interactive web diagram application. My default backend is in python. But mxgraph only give java and .NET backend. is it possible to make a mxgraph backend in python? If yes, how? thank you in advance.