Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get files absolute path after being uploading in Django?
I want to upload a file to my database and after it is uploaded import it and eventually export the data into my database. I have the uploading working just fine but I'm not sure how to get the absolute path of the file after it is uploaded. I'm able to print out the name of the document, but if the same document name is uploaded it is appended but still shows the original file name if I call form.cleaned_data['document'].name. What can I do to get the absolute file path and then call a function to start processing this file? So this is what I'm looking to do: User uploads a .csv file File gets saved in db (with a description and file path. File path is getting stored properly in db) Get file location of file that was just uploaded Start to process this file to convert the .csv data and store in database models.py from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render, redirect from django.views import View # Create your views here. from .forms import DocumentForm from .models import Document … -
unable to set and retrieve session variables
Using Django 1.10 My middleware is set as follows: MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ] I made sure to include the SESSION ENGINE SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' I have my client secret and id set as follows: os.environ['CLIENT_SECRET'] = 'something' os.environ['CLIENT_ID'] = 'something' and my views are setup to do a callback, store session variables as follows: def potato_oauth_callback(request): POTATO_OAUTH2_TOKEN_ENDPOINT = "https://login.potato.com/potatoservices/potatooauth2/potatotoken" POTATO_SECRET = get from env variables POTATO_ID = get from env variables POTATO_TYPE = "authorization_code" POTATOCALLBACK_URL = "https://potatourl/potatoes/potatocallback" authorization_code = request.GET.get('code') payload = { 'potato_type': POTATO_TYPE, 'potato_id': POTATO_ID, 'potato_secret': POTATO_SECRET, 'potato_uri': POTATOCALLBACK_URL, 'code': potato_code } r = requests.post(POTATO_OAUTH2_TOKEN_ENDPOINT, data=potatoload) resp = r.json() potatoAccess = { 'id': resp['id'], 'timestamp': resp['issued_at'], 'instanceURL': resp['instance_url'], 'signature': resp['signature'], 'accessToken': resp['access_token'] } request.session['potatoAccess_id'] = potatoAccess['id'] request.session['potatoAccess_timestamp'] = potatoAccess['timestamp'] request.session['potatoAccess_instanceURL'] = potatoAccess['instanceURL'] request.session['potatoAccess_signature'] = potatoAccess['signature'] request.session['potatoAccess_accessToken'] = potatoAccess['accessToken'] return HttpResponse(t.render({}, request)) Subsequently, when I do a request to recheck my session variables, I keep getting Key Errors and am unable to retrieve them: def check_potatoes(request): c = {} c['potatoAccess_id'] = request.session['potatoAccess_id'] print request.session['potatoAccess_id'] return HttpResponse(json.dumps('potatoes'), content_type='application/json') OR def check_potatoes(request): try: c = {} c['potatoAccess_id'] = request.session['potatoAccess_id'] print request.session['potatoAccess_id'] return HttpResponse(json.dumps('potatoes'), content_type='application/json') except Exception as potatoes: potatoesdata = {'message': … -
Django 1.11 Annotating a Subquery Aggregate
This is a bleeding-edge feature that I'm currently skewered upon and quickly bleeding out. I want to annotate a subquery-aggregate onto an existing queryset. Doing this before 1.11 either meant custom SQL or hammering the database. Here's the documentation for this, and the example from it: from django.db.models import OuterRef, Subquery, Sum comments = Comment.objects.filter(post=OuterRef('pk')).values('post') total_comments = comments.annotate(total=Sum('length')).values('total') Post.objects.filter(length__gt=Subquery(total_comments)) They're annotating on the aggregate, which seems weird to me, but whatever. I'm struggling with this so I'm boiling it right back to the simplest real-world example I have data for. I have Carparks which contain many Spaces. Use Book→Author if that makes you happier but —for now— I just want to annotate on a count of the related model using Subquery*. spaces = Space.objects.filter(carpark=OuterRef('pk')).values('carpark') count_spaces = spaces.annotate(c=Count('*')).values('c') Carpark.objects.annotate(space_count=Subquery(count_spaces)) This gives me a lovely ProgrammingError: more than one row returned by a subquery used as an expression and in my head, this error makes perfect sense. The subquery is returning a list of spaces with the annotated-on total. The example suggested that some sort of magic would happen and I'd end up with a number I could use. But that's not happening here? How do I annotate on aggregate Subquery data? … -
Elasticsearch raises exception after initial configuration
First time using haystack/elasticsearch. I get the following error message: elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception') I tried following the initial tutorial on the Haystack website, with an even more basic model (just the title in my index). Elasticsearch seems to be properly installed and returns: { "name" : "KX_5nrn", "cluster_name" : "elasticsearch_snirp", "cluster_uuid" : "zAUqr9RWSz6k6WlXJzcXPA", "version" : { "number" : "5.2.2", "build_hash" : "f9d9b74", "build_date" : "2017-02-24T17:26:45.835Z", "build_snapshot" : false, "lucene_version" : "6.4.1" }, "tagline" : "You Know, for Search" } Much obliged! -
How to decrease number (575) of queries in a nested loop?
Part of a function is computing a number of the last valid offers which are lower, equal and higher than a_price. Can't figure out a better way so I use two loops for now. The problem is that this executes 575 queries which is too much. One product can have many buyers and buyer has many offers (with different datetimes). I tried to add prefetch_related('buyers') but It did not help at all. reset_queries() products = Product.objects.filter(user=user) my_active_products = products.filter(active=True).prefetch_related('buyers') for product in my_active_products: for buyer in product.buyers.filter(valid=True): last_valid_offer = buyer.get_last_valid_offer() a_price = product.our_eur_price if a_price: if a_price < last_valid_offer.eur_price: cheaper += 1 elif a_price > last_valid_offer.eur_price: more_expensive += 1 elif a_price == last_valid_offer.eur_price: equal += 1 else: unknown += 1 print len(connection.queries) Do you know what should I do to decrease the number of queries? -
Trigger Post_save signal on M2M field
This code should add items to an index every time a new object is created. It works, but does not realise the M2M field is being created. I believe the signal doesn't "see" tags (as it's an M2M field). In other words: adds the title field only to index when object is "CREATED" only adds the M2M relations to index when "SAVE" is clicked FWIW, this is indexing for elastic search. Models.py class Task(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) def get_grouped_tags(self): tag = self.tag.order_by('taglevel') grouped_tags = { tag_level: [ { 'name': tag_of_level.name, 'taglevel': tag_of_level.taglevel, } for tag_of_level in tags_of_level ] for tag_level, tags_of_level in groupby(tag, lambda tag: tag.taglevel) } return grouped_tags def to_search(self): d = { "tags": self.grouped_tags(), "title": self.title } return TaskIndex(meta={'id': self.id}, **d) def indexing(self): obj = TaskIndex( meta={'id': self.id}, title=self.title, typetask=self.get_typetask_display() ) obj.save() return obj.to_dict(include_meta=True) def update_search(instance, **kwargs): instance.to_search().save() def remove_from_search(instance, **kwargs): instance.to_search().delete() post_save.connect(update_search, sender=Task) post_save.connect(update_search, sender=Tag) pre_delete.connect(remove_from_search, sender=Task) pre_delete.connect(remove_from_search, sender=Tag) m2m_changed.connect(update_search, sender=Task) Search.py connections.create_connection() class TaskIndex(DocType): title = String() class Meta: index = 'task-index' def bulk_indexing(): TaskIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator())) def _search(title): s = Search().filter('term', title=title.text) response = s.execute() return response -
Django project settings for production and development
In Django I have updated my git with pull from repo. And when I run it throws "myproject" database does not exist. Really I do not have myproject database because in production I have only prod_project database. But, somehow django is trying to load myproject database from base.py rather than loading from prod.py # base.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'admin', 'PASSWORD': '*****', 'ATOMIC_REQUESTS': True, }, } # prod.py from .base import * DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'prod_myproject', 'USER': 'admin', 'PASSWORD': '', }, } try: from .local import * except ImportError: pass # local.py is empty file -
Setting up Django's test database
I have an old legacy application that got upgraded to Django 1.7. I am trying to create a test suite for it that uses a local test database. For some reason, this seems to be much harder than it should. The first thing I did is migrate from South to Django's built-in migration tool. The last step (running migrate) didn't seem to take any effect. I've made the test command use the following DATABASES Django setting, so anyone running the test doesn't have to actually run MySQL locally: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '' }, } Now whenever I run ./manage.py test, I keep getting this error: django.db.utils.OperationalError: no such table: mainapp_country How can I fix this? -
How do I show one page to logged-in user and another to a not-logged in user with Django?
I'm confident that this question has been asked before, but I can't find an answer here. The goal: show a user that isn't logged in a random assortment of posts but a user that is logged in all of their own posts. The two views from views.py: def movement_random(request): movements = Movement.objects.order_by('?')[:10] return render(request, 'blog/movement_random.html', {'movements': movements}) @login_required def movement_list(request): movements = Movement.objects.filter(author=request.user).order_by('-moved_on') return render(request, 'blog/movement_list.html', {'movements': movements}) From urls.py: from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.movement_random, name='index'), url(r'^$', views.movement_list, name='movement_list'), url(r'^movement/(?P<pk>\d+)/$', views.movement_detail, name='movement_detail'), url(r'^movement/new/$', views.movement_new, name='movement_new'), url(r'^movement/(?P<pk>\d+)/edit/$', views.movement_edit, name='movement_edit'), url(r'^accounts/', include('registration.backends.hmac.urls')), ] As it stand right now, the "homepage" for the app is, right now, always the first URL, even with a logged-in user. How do I show the views.movement_list to a logged-in user while the views.movement_random to a non-user? -
Why Django migration alter field (AlterField) that is not touched?
When i do migration python manage.py makemigrations wall i see in console that Django (1.8.12) tells me a long list of fields that are touched: Migrations for 'wall': 0079_auto_20170302_0024.py: - Add field periodic_task_interval to userproject - Alter field bank_problems on bankireference - Alter field bank_problems_category on bankireference - Alter field bank_products on bankireference - Alter field bank_products_category on bankireference - Alter field extr_category on bankireference - Alter field extr_words on bankireference - Alter field neg_features on bankireference - Alter field neutral_features on bankireference - Alter field pos_features on bankireference - Alter field tonality_category on bankireference - Alter field tonality_words on bankireference - Alter field bank_problems on fbpagepost - Alter field bank_problems_category on fbpagepost - Alter field bank_products on fbpagepost - Alter field bank_products_category on fbpagepost - Alter field extr_category on fbpagepost ...... ad so on, near all fileds that is ManyToManyField. I also checked other migrations, looks like random choose of fields, because i see also tagulous.models.fields.TagField and even models.TextField. BUT, i am sure a did not changed that fields, even touched them This is what in 0079_auto_20170302_0024.py for untouched fields: ...... migrations.AlterField( model_name='userproject', name='description', field=models.TextField(default='', verbose_name='Description', blank=True, null=True), ), ...... The only thing i have done is added - … -
404 Client Error: NOT FOUND for url and ValueError: No JSON object decoded
This is the project I'm working on Using DICT.get(key) but still getting KeyError in Django and I have solved the KeyError. But now new errors have occurred, which are '404 Client Error: NOT FOUND for url' and 'ValueError: No JSON object could be decoded'. This is the error message: http://imgur.com/a/kft3E And my updated views.py: http://pastebin.com/T7mnJiLs The traceback: 404 Client Error: NOT FOUND for url: http://localhost:8080/simcheck 404 <:::COPY THIS:::> Internal Server Error: /situational/attempt/246/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/VMadmin/Desktop/FYP/Deployment/edukts/src/edukts_web/views.py", line 791, in attempt_situational_question scores = json.loads(r.text) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I was reading from here that setting a User-Agent might help, and I have added to my views.py but its not helping at all. Perhaps the error was raised not because of the JSON problem, but because r could not be obtained in the first place. Maybe something to do with the connection … -
Django form(set) - this field is required
When i am editing my form/formset and remove one ContestForm, in most of times it simply doesnt change and and i see error "this field is required" e. g. there was "Form XYZ", i changed it to "----" (blank) and after submitting it shows "this field is required" as you can see in the screenshot Views.py: def contest_admin(request, contest_slug): contest = get_object_or_404(Contest, slug=contest_slug) ontestFormsFormSet = inlineformset_factory(Contest, ContestForms, fields=('form', 'main_entry', 'user_modifiable',), extra=2, ) contest_desc = ContestDescForm(request.POST or None, instance=contest) contest_forms = ContestFormsFormSet(request.POST or None, instance=contest) if request.method == 'POST': if contest_desc.is_valid() and contest_forms.is_valid(): contest_desc.save() contest_forms.save() context = { ... } template_name = "contests/admin/_admin.html" return render(request, template_name, context) Models.py: class Contest(models.Model): name = models.CharField('Contest Name', max_length=100) slug = models.SlugField(unique=True) capacity = models.IntegerField('Capacity') team_size = models.IntegerField('Team size', default=1) description = models.CharField('Description', max_length=1000) date_opened = models.DateField('Date opened') date_registration_closed = models.DateField('Date registration closed') date_closed = models.DateField('Date closed') forms = models.ManyToManyField(FormEntry, through='ContestForms') class ContestForms(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE) form = models.OneToOneField(FormEntry) main_entry = models.BooleanField('Main entry') user_modifiable = models.BooleanField('Modifiable') class Meta: verbose_name_plural = "ContestForms" Forms.py: class ContestDescForm(forms.ModelForm): widget_attrs = { 'class': "form-control", 'type': 'date', } description = CharField(widget=forms.Textarea) date_opened = DateField(widget=DateInput(attrs={'type': 'date'})) date_registration_closed = DateField(widget=DateInput(attrs={'type': 'date'})) date_closed = DateField(widget=DateInput(attrs={'type': 'date'})) class Meta: model = Contest exclude = … -
Change Multiple Form Sizes Django Bootstrap
I'm trying to style my Django forms using CSS. I want it so that I can have multiple fields on the one line and different widths, but also have some fields that stretch the whole width of the container. I'm finding it difficult to do. I've tried using Bootstrap's grid system but I can't specify which div to put around which form element. I've also tried using a few answers I've seen here with TextAreas, and specifying the number of rows and cols like so: widget=forms.Textarea(attrs={'cols': 8, 'rows': 1}) I was wondering is there a way I can add divs around particular inputs without having to use lots of if else statements in the template. I could specify a template with the divs already in it but I'm fairly sure I can only use one form template? -
Circular Referencing Packages - Python/Django
During the course of a GraphQL implementation I'm finding myself making a lot of circular references to keep the packages modular. Consider the following folder structure. project/ graphql/ __init__.py inputs/ __init__.py company.py contact.py company.py import graphene import graphql.inputs.contact class CompanyInput(graphene.InputObjectType): contacts = graphene.List(graphql.inputs.contacts.ContactInput) ... contact.py import graphene import graphql.inputs.company class ContactInput(graphene.InputObjectType): company = graphql.inputs.company.CompanyInput() I consistently get the Django error: ImportError at /api/v2/ Could not import 'gql.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: 'module' object has no attribute 'company'. Is this kind of circular referencing possible? Both contacts and companies need to be able to reference the input object class defined in the separate packages. This is so that graphql can take in inputs with with children and allow nested creation as well as allowing the input of an object with the creation of a parent. -
Get Form values in Python using Django framework
My question here is without using Model or forms.Form can we get form values on submit using Django request object. Here is small example to explain problem. HTML Code : <form action="/login/" method="post"> {% csrf_token %} <input type="text" id="USERNAME" class="text" value="USERNAME" > <input type="password" id="Password" value="Password" > <div class="submit"> <input type="submit" onclick="myFunction()" value="LOGIN"> </div> <p><a href="#">Forgot Password ?</a></p> </form> views.py Code : def dologin(request): print('i am in do login') print(request.method) print(request.POST) for key, value in request.POST.iteritems(): print(key , value) return render(request,'webapp/login.html') So here my key values are empty always. I have learned and capable enough to create html forms using Model and forms:Form. But to add more style changes I need to map this forms:Form object to html defined form. Thanks in advance. -
Django advanced join / query
I have this two models. class City(models.Model): city = models.CharField(max_length=200) country = models.CharField(max_length=200) class CityTranslation(models.Model): city = models.ForeignKey(City) name = models.CharField(max_length=200) lang = models.CharField(max_length=2) prio = models.IntegerField() Every city can have multiple translated names within one language. For exmaple: I need a query, which gives me all cities in a country (City.objects.filter(country="Poland")) If there exist a CityTranslation with lang='pl' it should be added/annotated (the name at least)! If there are multiple CityTranslation's with lang='pl' they should be ordered by 'prio' and get the first one. Anyone an idea how to accomplish this task? -
javascript compress django decompress
I need to send a very big string from browser to server, so I want to compress it using javascript on client side and then decompress on server using django/python. Could you give any ideas how is better to do that? -
More efficient way of writing this function? (Django, AJAX)
The way I have written the function works now, I'm just wondering if there is a better or more efficient way to write it. It is an ajax call that gets a list for further filtering a geography, for example if county is chosen then it will get a list of all the counties in that state. I'm still learning coding and want to get better at using good coding practices. $.ajax({ url : "filters", type : "POST", data : { search : selected_state, geog : selected_geog }, success: function(data) { $.each(data, function(i, v) { switch(selected_geog) { case 'County': case 'Dma': filters.push(v.fields.name); break; case 'Zip': var exists = $.inArray(v.fields.zcta, data_check); if (exists < 0) { data_check.push(v.fields.zcta); } data_check.sort(); var exists2 = $.inArray(v.fields.county, filters); if (exists2 < 0) { filters.push(v.fields.county); } filters.sort(); break; case 'CD': filters.push(v.fields.cd114fp); break; case 'Zones': var exists = $.inArray(v.fields.p_dma, filters); if (exists < 0) { filters.push(v.fields.p_dma); } filters.sort(); var exists2 = $.inArray(v.fields.owner, attrfilters); if (exists2 < 0) { attrfilters.push(v.fields.owner); } SHPconverter.attrfilters.sort(); var exists3 = $.inArray(v.fields.scode, data_check); if (exists3 < 0) { data_check.push(v.fields.scode); } data_check.sort(); break; } }) } }) and here is the django view def filters(request): searchVar = request.POST.getlist('search[]') geogVar = request.POST.get('geog') if geogVar == 'County': … -
Building image on a docker container for running own Django app
I'm trying to build an image for run in a Docker container with an own existing Django app doing the following command sudo docker build -t avilaholding/clubmercado ~/Documents/docker/cmimage but I get this error with psycopg2 instead Collecting pathspec==0.3.4 (from -r /srv/clubmercado/requirements.txt (line 23)) Downloading pathspec-0.3.4.tar.gz Collecting psycopg2==2.6.1 (from -r /srv/clubmercado/requirements.txt (line 24)) Downloading psycopg2-2.6.1.tar.gz (371kB) Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' warning: manifest_maker: standard file '-c' not found Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5wxAAo/psycopg2/ You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. The command '/bin/sh -c pip install -r $DOCKYARD_SRVPROJ/requirements.txt' returned a non-zero code: 1 I think it might be because it's running on python 2.7 but I want it to run on python 3.5. I have both versions installed on Ubuntu 16.04. … -
How do I do a login with Django?
i have an app to manage students mark and i want to make a login for students Image's link when students try to login : the app should check if username/password exists in database -
Django Page is not refreshing with new data sent from the server
I am new to Django so I will try to describe my scenario the best I can: The user enter some String to search The data is returned from the server and the data is populated in the table accordingly The user can then click on a button and data will appear in modal dialog In the dialog box the user can change the search value and hit the search button to re search for the new value a post request is sent to the server and the function is invoked in the views file In the browser network under dev mode (F12) I can see that the response hold the new data but the page itself shows the old data Does someone have an idea why this happens and how this can be resolved? -
Connections mirroring in Django tests
I have a multi-database configuration of Django 1.10 and json fixtures for connections. For example my configuration looks like DATABASES = { 'default': { 'NAME': 'default', ..., 'TEST': { 'NAME': 'test_default', } }, 'second': { 'NAME': 'second', ..., 'TEST': { 'NAME': 'test_second', 'MIRROR': 'default', } } } When Django bootstrap testing environment it loads TestCase.fixtures into not-mirrored connections (in my case only into test_default). When test case next tries to get model placed in second connection it fails with DoesNotExists. This happens because fixtures are loaded into first connection that is not committed because of using savepoints between running test cases. Consequently all tests that assume presence of data in mirroring connections like in master connection will fail! This looks like a problem with Django test bootstrap algorithm. Also possible that i do something completely wrong. Why Django not loads fixtures also into mirrored connections? -
Django Migration difference between dev and test postgres databases
I have a development database I was working on and I had issues with the migrations taking for adding a foreignkey field. I ended up having to blow away the database after clearing my migrations folder out and redoing it. So now I have one migration file... The problem is, I pulled code to my test server, and now that database is VERY out of sync (it's not, django thinks it is. It really just needs a table added and a field). Though running make migrations breaks as the migration folder I had pushed was clear of all but one migration and does not jive with the migration folder on the test server. Any ideas as to how I can reconcile this, it is my test data so blowing away the database here and starting new isn't an issue, but this will be a huge issue again when I push to production (and cannot blow away that database). Maybe dump the data/database using pg_dump, blow away the database, run migrations and load the data back via the dump file? -
Wagtail: Serializing page model
I am using wagtail as a REST backend for a website. The website is built using react and fetches data via wagtails API v2. The SPA website needs to be able to show previews of pages in wagtail. My thought was to override serve_preview on the page model and simply seralize the new page as JSON and write it to a cache which could be accessed by my frontend. But im having trouble serializing my page to json. All attempts made feel very "hackish" I've made several attempts using extentions of wagtails built in serializers but without success: Atempt 1: def serve_preview(self, request, mode_name): from wagtail.api.v2.endpoints import PagesAPIEndpoint endpoint = PagesAPIEndpoint() setattr(request, 'wagtailapi_router', WagtailAPIRouter('wagtailapi_v2')) endpoint.request = request endpoint.action = None endpoint.kwargs = {'slug': self.slug, 'pk': self.pk} endpoint.lookup_field = 'pk' serializer = endpoint.get_serializer(self) Feels very ugly to use router here and set a bunch of attrs Attempt 2: def serve_preview(self, request, mode_name): from wagtail.api.v2.endpoints import PagesAPIEndpoint fields = PagesAPIEndpoint.get_available_fields(self) if hasattr(self, 'api_fields'): fields.extend(self.api_fields) serializer_class = get_serializer_class( type(self), fields, meta_fields=[PagesAPIEndpoint.meta_fields], base=PageSerializer) serializer = serializer_class(self) Better but i get context issues: Traceback (most recent call last): ... File "/usr/local/lib/python3.5/site-packages/wagtail/api/v2/serializers.py", line 92, in to_representation self.context['view'].seen_types[name] = page.specific_class KeyError: 'view' Any toughts? -
Django - django-registration - Change Form registration.backends.hmac.views.RegistrationView
I am currently building a user registration verification process via email on my web app and am using the HMAC activation workflow from the django-registration application. I would like to change the default form that is used by the RegistrationView to my custom user registration form. I tried to pass the form_class argument within the url set-up as follows: from registration.backends.hmac.views import RegistrationView ... url(r'^create-account/register/$', RegistrationView, {'form_class' : UserRegistrationForm}), ... However, this generates a TypeError mentioning that only 1 arguments are allowed and that 3 were given. Would anyone know what is causing this issue? Thanks.