Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Cannot upload images and get it to update the DB
So I'm trying to make it possible for users to update their Avatar/Profile image by allowing them to upload their image + I want to implement an image cropper so they can crop the image to a ratio of 1 to 1. All tho I think the first thing is making it possible to upload. I've searched around trying to make it possible but I think I've almost been everywhere. The thing is the image field I'm using is like an extension to the User table I basically called it extendeduser that has all the extra information included in it. View.py @login_required def useravatar(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() user.extendeduser.avatar = form.cleaned_data('avatar') user.save() messages.success(request, 'Your avatar was successfully Uploaded!') return redirect('useravatar', user_pk=request.user.pk) logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_user = get_object_or_404(User, pk=user_pk) driverslicence = DriversLicenceCategories.objects.all() feedback = FeedbackSupportForm() password = PasswordChangeForm(request.user) avatar = UpdateProfileForm(instance=request.user) context = { 'avatar' : avatar, 'logged_in_user': logged_in_user, 'requested_user': requested_user, 'feedback' : feedback, 'password' : password, } return render(request, 'user/avatar.html', context) Models.py class ExtendedUser(models.Model): avatar = models.ImageField(upload_to='users/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='users/backgrounds', default='static/img/userpreload.png') Forms.py class UpdateProfileForm(forms.ModelForm): postal_code = forms.CharField(max_length=10, required=True) phone_number = forms.CharField(max_length=16, required=True) phone_number_show = forms.BooleanField(required=False) avatar … -
matching query does not exists - error in Django search
I have been struggling with this for a while now.I tried to implement Django search with pagination. Pagination works, but when I try to search something, I get this error: Course matching query does not exist. Here is the traceback: https://pastebin.com/jJp2hLUs And code: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def pagination(request, data, num=10): paginator = Paginator(data, num) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) index = courses.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] return courses, page_range def search(request, slug): query = request.GET.get('q') if query: results = Course.objects.filter(Q(name__icontains=query), slug=slug) else: results = Course.objects.get() pages = pagination(request, results, num=1) context = { 'courses': pages[0], 'page_range': pages[1], 'query': query, } return render(request, 'courses/index.html', context) def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) -
How to raise a custom form invalid error in wizardview from django formtools
I am using django-formtools to split the registration form. I have added Google ReCaptcha for captcha verification. I would wish to produce error in the form like the one in django UpdateView. Is there any method in django form wizard like messages.error(self.request, 'Invalid reCAPTCHA. Please try again.') return super(UpdateUserProfileView, self).form_invalid(form) -
how to use twilio video api python?
i would like to implement twilio video api in my django project but i didn't really understand the docs i managed to create a room i flowed this example from twilio.rest import Client api_key_sid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" api_key_secret = "your_api_key_secret" client = Client(api_key_sid, api_key_secret) room = client.video.rooms.create(unique_name='DailyStandup') print(room.sid) after that what should i do ? how to access the room and start the chat -
Django : "stream" vs request.FILES["file"]
So I wanted to write a custom file upload parser as specified in docs. According to doc I implemented the parse method as class MailParser(BaseParser): """ parses email serialized data """ media_type = "multipart/form-data" def parse(self, stream, media_type = None, parser_context = None): """ Here I was trying to read stream """ but when I tried to read stream it additionally had following content ----------------------------488071469102781097692083 Content-Disposition: form-data; name="file"; filename="email_test.msg" Content-Type: application/vnd.ms-outlook < actual content here > ----------------------------488071469102781097692083-- But when I directly read the file from request using request.FILES['file'] .read() The same content wasn't there. I wanted to understand this behaviour. Thanks in advance. -
NoReverseMatch at /login/
NoReverseMatch at /login/ is the error I'm getting from the console, I have a feeling this is something to do with the linking that is going on between urls.py but I can't figure out which part of it is wrong. Any help would be greatly appreciated on this. The full error from the console is beneath Reverse for 'django.contrib.auth.views.login' not found. 'django.contrib.auth.views.login' is not a valid view function or pattern name. urls.py from django.contrib import admin from polls import views as polls_views from django.conf.urls import url, include from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^calendar/', include('calendarium.urls')), url(r'^polls/', include('polls.urls')), url(r'^$', polls_views.home, name='home'), url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'login'}, name='logout'), url(r'^signup/$', polls_views.signup, name='signup'), ] base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{% block title %}OnNote{% endblock %}</title> </head> <body> <header> <h1>My Site</h1> {% if user.is_authenticated %} <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> login.html {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <div id="content-container" class="container p-none"> <div class="lgn-container col-lg-8"> <form … -
Multiple Reverse-Relations in Django-REST-FrameWork
Models: class Client(Model): title = CharField('Название клиента', max_length=100) class Phone(Model): client = ForeignKey(Client, on_delete=CASCADE) number = CharField(max_length=50) Serializers: class PhoneSerializer(ModelSerializer): number = CharField(required=True) class Meta: model = Phone fields = ('number') class ClientSerializer(ModelSerializer, GlobalObjectMixin): id = IntegerField(read_only=True) title = CharField(required=True) phone = PhoneSerializer(required=False) def create(self, validated_data): if 'phone' in validated_data: phones = validated_data.pop('phone') client = Client.objects.create(**validated_data) phone = Phone.objects.create( client_id=client.id, **phones ) return client class Meta: model = Client fields = ('id', 'title', 'phone', 'phone_set') Problem: I can't add multiple phones while creating the Client, if I provide only one Phone for Client, I can create and retrieve that Client with no problem, but if I add multiple Phones while creating the Client, I got an empty list instead of a list of dicts with Phones. PS: I'm making requests via postman, I provide Phone while creating Client like: phone.number : 1234567 -
Django annotate with conditional expression, how to apply distinct()
I have a little bit complex query and I use annotate with a conditional expression, the code is below: from django.db.models import Q, F, When, CharField, Value, Case from django.contrib.auth.models import User ATT_PREFIX = 'f' def get_it(mymodel, fields): q = Q(modelone__modeltwo__mymodel=mymodel) query_set = { 'aid': F('modelone__id'), 'name': F('modelfour__name'), } for f in fields: query_set[ATT_PREFIX + str(f.id)] = Case( When(Q(modelfive__modelsix=f) & Q(modelfive__user__email=F('email')), then='modelfive__entry'), default=Value(''), output_field=CharField(), ) return User.objects.filter(q).annotate(**query_set) Attributes aid and name collected with F() have expected values. Second part which use conditional expression have a problem: If feilds list contain 2 objects, then I have 2 User objects created by Case() when condition is meet. So instead of one object with atributes (aid, name, f17, f18) I got two objects: obj1 attributes (aid, name, f17) obj2 attributes (aid, name, f18) -
executing code only once when status change
I am a beginner django developer, and I have a question concerning executing code only once when a if statement is met. In my app I have a team where each member need to answer a survey. and I would like that, if each member has answer his survey a mail is sent to the Team manager that the team is ready. I know how to do it in myview.py.. the thing is now each time I load my app a new mail is sent ... I would like to have it send only once, when the status change from open to close. Any idea ? -
Gunicorn for Django project without virtual enviroment
I was trying to deploy my Django project with Gunicorn but the tutorial is very messy and even though the example worked, the real project is not working. Do I need to configure a gunicorn file or make some changes in project wsgi file? here is my wsgi file- import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ChemicalSimilarities.settings") application = get_wsgi_application() I am using this command to try to run gunicorn for debugging too - gunicorn ChemicalSimilarities.wsgi:application--debug --log-level debug The error that I am getting is this - proxy_protocol: False worker_connections: 1000 statsd_host: None max_requests_jitter: 0 post_fork: <function post_fork at 0x7fb86d5fd7d0> errorlog: - enable_stdio_inheritance: False worker_class: sync ssl_version: 2 suppress_ragged_eofs: True syslog: False syslog_facility: user when_ready: <function when_ready at 0x7fb86d5fd500> pre_fork: <function pre_fork at 0x7fb86d5fd668> cert_reqs: 0 preload_app: False keepalive: 2 accesslog: None group: 1000 graceful_timeout: 30 do_handshake_on_connect: False spew: False workers: 1 proc_name: None sendfile: None pidfile: None umask: 0 on_reload: <function on_reload at 0x7fb86d5fd398> pre_exec: <function pre_exec at 0x7fb86d5fdd70> worker_tmp_dir: None limit_request_fields: 100 pythonpath: None on_exit: <function on_exit at 0x7fb86d6055f0> config: None logconfig: None check_config: False statsd_prefix: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} reload_engine: auto proxy_allow_ips: ['127.0.0.1'] pre_request: <function pre_request at 0x7fb86d5fded8> post_request: <function post_request at 0x7fb86d605050> forwarded_allow_ips: … -
django rest api error
in view.py def locker_data_response(request, locker_id): if request.method == 'GET': locker_information = get_object_or_404(Locker, locker_id = locker_id) print(locker_information) locker_information_serialize = LockerSerializer(locker_information, many=True) print(locker_information_serialize) return Response(locker_information_serialize.data) in serialize.py class LockerSerializer(serializers.ModelSerializer): class Meta: model = Locker fields = '__all__' .accepted_renderer not set on Response error -
Django - User uploaded S3 files in the view
I have a page where users can upload PDF / image files to their profile. The model for these files is relativly straightforward: class ResumeItemFile(models.Model): item = models.ForeignKey(ResumeItem, related_name='attachment_files') file = models.FileField( max_length=255, upload_to=RandomizedFilePath('resume_attachments'), verbose_name=_('Attachment')) name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) I am creating a view where all files linked to a profile (item) are gathered in a .zip file. I've got this working locally, but in production I run in the following error NotImplementedError: This backend doesn't support absolute paths. The main difference is that on production the mediafiles are served through S3 MEDIA_URL = 'https://******.s3.amazonaws.com/' STATIC_URL = MEDIA_URL In my view I created a list of the ResumeItemFile in the attachments variable, which is a list of dicts that look like this: {'filename', ResumeItemFileObject} for file in attachments: storage = DefaultStorage() filename = file[1] file_extension = str(file[0].file).split('.')[-1] file_object = storage.open(file[0].file.path, mode='rb') filename, file_object.read()) file_object.close() Though this works fine locally, on staging it crashes on the file_object = storage.open(file[0].file.path, mode='rb') line. If the backend does not support absolute paths, how I am to select the correct file? Does anyone have an idea of what I am doing wrong? -
Django : render not passing context variable to template
I have this views function to fetch userid and accountnumber from AWS Dynamodb : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = dict(AccountNum=accnum,userID=uid) rows = list(f.items()) return render('useradd.html',{'rows': rows}) I have tried almost everything but the rows value is just not getting passed to my template. I even tried passing a simple string value and even that is not getting passed. This is my template table where I wish to display the userid and accountnum. <div class="mytable"> <table> <thead> <tr> <th>Account #</th> <th>User Id</th> </tr> </thead> <tbody> {% for row in rows %} <tr> <td>{{ row.AccountNum }}</td> <td>{{ row.UserId }}</td> </tr> {% endfor %} </table> </div> When I hit the template , nothing shows up. No values are getting displayed except the table headings. Why is render not passing the context variable (list value)from my views to template ? I have been stuck with for about 6 hours ! Can someone resolve this issue ? -
Django, CSS3, and font-face: how to load local font files?
So I have a Django app <my-app> and I would like to load some local font files into the base template <my-app>/templates/<my-app>/base.html. For example, under <my-app>/static/<my-app>/fonts/Lato/ I have several .ttf files: Lato-Black.ttf Lato-BlackItalic.ttf Lato-Bold.ttf etc and in <my-app>/static/<my-app>/css/fonts.css I have: @font-face { font-family: Lato; font-style: normal; font-weight: 300; src: local('Lato-Black') url('../fonts/Lato/Lato-Black.ttf') format('truetype'), local('Lato-BlackItalic') url('../fonts/Lato/Lato-BlackItalic.ttf') format('truetype'), local('Lato-Bold') url('../fonts/Lato/Lato-Bold.ttf') format('truetype'), local('Lato-BoldItalic') url('../fonts/Lato/Lato-BoldItalic.ttf') format('truetype'), local('Lato-Hairline') url('../fonts/Lato/Lato-Hairline.ttf') format('truetype'), local('Lato-HairlineItalic') url('../fonts/Lato/Lato-HairlineItalic.ttf') format('truetype'), local('Lato-Italic') url('../fonts/Lato/Lato-Italic.ttf') format('truetype'), local('Lato-Light') url('../fonts/Lato/Lato-Light.ttf') format('truetype'), local('Lato-LightItalic') url('../fonts/Lato/Lato-LightItalic.ttf') format('truetype'), local('Lato-Regular') url('../fonts/Lato/Lato-Regular.ttf') format('truetype') ; } Accordingly in base.html: <link rel="stylesheet" type="text/css" href="{% static '<my-app>/css/fonts.css' %}" /> This does not load the fonts so that I can use them as if I used Google's api: <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet"> So how do I fix my CSS? -
pass class variable name to class method
I have a Model defined as below: class ProblemVerificationModel(CreateUpdateDateModel): problem = models.ForeignKey(Problem, related_name="problem_survey") verifier = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="verified_problem") is_problem_properly_formated = ... # BooleanField is_this_done = ... # BooleanField is_that_done = ... # BooleanField # other BooleanFields The above model serves like a voting system in my application. I need to calculate percentage of votes for each property such as is_problem_properly_formated, is_this_done, is_that_done etc. I am using classmethod for the same as defined below: @classmethod def percentage_problem_properly_formated(cls, problem): votes = cls.objects.filter(problem=problem) total_votes = votes.count() yes_votes = votes.filter(is_problem_properly_formated=True).count() percentage_yes = (yes_votes / total_votes) * 100 return percentage_yes @classmethod def percentage_is_this_done(cls, problem): votes = cls.objects.filter(problem=problem) total_votes = votes.count() yes_votes = votes.filter(is_this_done=True).count() percentage_yes = (yes_votes / total_votes) * 100 return percentage_yes Now for each property I am using similar method with difference being parameter passed to filter method. This certainly is not a DRY way of doing things. I just want a single method where I can pass the parameter to pass to filter method. Can you help or provide hints to achieve the same results the DRY way? -
fatal error: portaudio.h: No such file or directory
Running setup.py install for pyaudio ... error Complete output from command /home/mertyildiran/Downloads/VirtualEnvironment/vir1/Cerebrum/ENV/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-GCltlv/pyaudio/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-icMIUV-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/mertyildiran/Downloads/VirtualEnvironment/vir1/Cerebrum/ENV/include/site/python2.7/pyaudio: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying src/pyaudio.py -> build/lib.linux-x86_64-2.7 running build_ext building '_portaudio' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c src/_portaudiomodule.c -o build/temp.linux-x86_64-2.7/src/_portaudiomodule.o src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory #include "portaudio.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 -
Excluding fields while using Values()
I have a model XYZ(name,age,sex), I am fetching all the fields using XYZ.objects.filter(name='ddd').values() this is returning all the fields in dict how to exclude the field age I have tried XYZ.objects.filter(name='').exclude('sex').values() but it not working -
django 2 crud operations without database with external api
I have an external third-party API for retrieving and storing song names and I need to interface it with Django 2 and permit the user through Django forms to insert and update songs. I'm struggling as most documentation on Django assumes a database backend and even examples on consuming an external REST API assume I want to store fetched data from the API to the database. I looked into creating a Django 2 custom model manager but it seems this is used as something above an existing database and not an external API. Django 2 serializers permit to serialize and deserialize data in between an API and a database. What I'm missing is the way to create a custom model abstracting the API and permitting me to use it as if it were a database so that I can go on and follow any Django forms tutorial after having abstracted the model layer. Currently I hacked something like below: urls.py : urlpatterns = [ url(r'^$', viewSong, name='home'), url(r'^create/$', SongView.as_view(), name='create'), url(r'^update/(?P<song_id>[0-9\.a-z]+)/$', SongUpdate.as_view(), name='update'), ] templates/form.html : <form role="form" action="/create/" method="post"> {% csrf_token %} <div class="form-group"> <label for="song-id">Song Id</label> <input type="text" id="song-id" name="song-id"> </div> <div class="form-group"> <label for="son-name">Song Name</label> <input type="text" … -
How to display 3 lists together using Python 3 + django2?
I have a list as follow: item1, [subitems] item2, [subitems] ... itemN, [subitems] For instance, item1 .. itemN might be a list of classes, and [subitems] contains a list of students that attend each class. A student might attend more than 1 class. Each class and student has a description (in a string variable). I want to create a (static) table that contains two columns. The first column is the list of classes. When I click to one element in the first column, the second column will display the list of students attend this class. Also, the description of the class will be displayed. If I click to a student, the cell will expand and display the description of the student. Sorry if the description is not so clear. The idea is as the image following: The list and description are stored in TXT files, not database. -
Heroku not pushing Django App due to buildpack error
I am trying to upload my Django project to Heroku with Python. My app was built on Python 3.6.1 and when I go to push the app to heroku I am receiving the following error message in the terminal: remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to random-appio. remote: I have included a runtime.txt file containing the following: python-3.6.1 I also have a Procfile containing: web: sh -c "cd directory && gunicorn directory.wsgi" As well as a requirements.txt file containing: Django==2.0.2 gunicorn==19.7.1 pytz==2018.3 whitenoise==3.3.1 My requirements.txt, Procfile and runtime.txt are all in the project directory. I can't see where I am going wrong here - any ideas? Thanks everyone. -
Trying to display same model with different pagination
So I have this page with 2 columns. First column represents the way I display my courses in the second column. On the second column all my courses are listed and from the first column I can choose how to list specific courses (by faculty) that replaces the all courses on the second column when pressed on faculty name. I added pagination to all courses of the second column which works as intended. Then when I tried to add pagination by faculty, only first faculty will appear and if I press on second page of the faculty courses, it will redirect me to all courses pagination for some reason.. <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> {% for faculty in faculties %} <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% … -
Front end development with a coupled Django back-end
There has been a lot of talk about having Django have a front-end set of tools. When will this come to fruition? What about a 'Django.js'? -
Django installation error, when install by pip3 command
After that command: aset@aset-linux ~ $ pip3 install django Traceback (most recent call last): File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 666, in _build_master ws.require(requires) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 984, in require needed = self.resolve(parse_requirements(requirements)) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 875, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.VersionConflict: (pip 8.1.1 (/usr/lib/python3/dist-packages), Requirement.parse('pip==9.0.1')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/pip3", line 6, in from pkg_resources import load_entry_point File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3147, in @_call_aside File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3131, in _call_aside f(*args, **kwargs) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3160, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 668, in _build_master return cls._build_from_requirements(requires) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 681, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 870, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application What should I do? I want to create site on Python by Django. Perhaps someone has a similar experience and would agree to help me. Thanks! -
django rest-framework serializer reverse relation
I am programming django based web site using django rest-framework. I want to use rest-framework to get model's data. this is my model.py class TimeTable(models.Model): subject_name = models.CharField(max_length=50) subject_code = models.CharField(max_length=10, unique=True) classification = models.CharField(max_length=50) professor = models.CharField(max_length=50) department = models.CharField(max_length=50) credit = models.CharField(max_length=1) year = models.CharField(max_length=4, default='2018') semester = models.CharField(max_length=1, default='1') def __str__(self): return self.subject_code + '-' + self.subject_name class Class(models.Model): owner = models.ForeignKey(Profile, null=True) timetable = models.ForeignKey(TimeTable, null=True) grade = models.FloatField() this is serializer.py class TimeTableSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TimeTable fields = ('url', 'subject_name', 'subject_code', 'classification', 'professor', 'department', 'credit', 'year', 'semester') class ClassSerializer(serializers.HyperlinkedModelSerializer): timetables = TimeTableSerializer(read_only=True) class Meta: model = Class fields = ('url','owner', 'timetable', 'grade', 'timetables') I want to get JSON response Like this (http://localhost:8000/api/classes/) [ { "url": "http://localhost:8000/api/classes/8/", "owner": "http://localhost:8000/api/profiles/19/", "timetable": "http://localhost:8000/api/timetables/3/", "grade": 4.5 "timetables": { "url": "http://localhost:8000/api/timetables/3/", "subject_name": "Artificial Inteligence", "subject_code": "3413513413", "classification": "major", "professor": "John Lee", "department": "software", "credit": "3", "year": "2018", "semester": "1" } } ] but i got this [ { "url": "http://localhost:8000/api/classes/8/", "owner": "http://localhost:8000/api/profiles/19/", "timetable": "http://localhost:8000/api/timetables/3/", "grade": 4.5 } ] How Can I get TimeTable's JSON data in Class JSON?? -
Offline context with Wagtail Page data (Django-Compressor)
I've got Wagtail set up with Django-Compressor (COMPRESS OFFLINE = True) which all works except for one template. This template uses the Disqus plugin which requires: An absolute page url A unique page identifier In my template I have included the following: {% compress js inline %} // My JS Code this.page.url = "{{ page.full_url }}"; this.page.identifier = {{ page.id }}; {% endcompress % So when accessing the page I get the error You have offline compression enabled but key "ARANDOMKEYGOESHERE" is missing from offline manifest. As per the Django-Compressor docs: If you use any variables inside the {% compress %} blocks, make sure to list all values you require in COMPRESS_OFFLINE_CONTEXT How would I go about adding the Page instance to the context in my settings? I thought of something like (pseudo-code): COMPRESS_OFFLINE_CONTEXT = { 'page': request.get('page') }