Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11.5 on Apache with mod_wsgi giving ImportError: No module named site
[Fri Sep 29 14:46:35.808072 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' has died, deregister and restart it. [Fri Sep 29 14:46:35.808113 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' terminated by signal 1 [Fri Sep 29 14:46:35.808116 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' has been deregistered and will no longer be monitored. [Fri Sep 29 14:46:35.808944 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Starting process 'swpdoc' with uid=48, gid=48 and threads=15. [Fri Sep 29 14:46:35.809868 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Python home /var/www/swpdoc/venswpdoc. [Fri Sep 29 14:46:35.809895 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Initializing Python. ImportError: No module named site If i use a project with django 1.9.5. it is working find and updating the django to newer version giving this error. Anyone help ? -
How can I use xgboost in heroku
I'm creating my first Django machine learning app on Heroku, but there is an error even that code passed in development env. Here are a code and an error message. from sklearn.externals import joblib clf = joblib.load('clf.pkl') clf.predict_proba(x) File "/app/.heroku/python/lib/python3.6/site-packages/xgboost/sklearn.py", line 475, in predict_proba class_probs = self.booster().predict(test_dmatrix, TypeError: 'str' object is not callabl ※ I already confirmed "x" has no string. I can use this code in development env. How can I use xgboost in heroku? -
Not properly render image from Django model
I am making a simple app(Django version 1.11+python3.5+). I want to show images on my homepage(web app) from Django models. I can upload successfully from Django admin panel. But image cant renders properly. The image does not show in the homepage. This is my HTML file. {% extends "shop/base.html" %} {% block content_area %} {% for name in products %} <div class="col-lg-3 col-md-3"> <div class="main_content_sidebar"> <div class="content_title"> <h2>{{name.product_name}}</h2> </div> <div class="image_space"> <img src="{{name.product_image.url}}" class="img-thumbnail" alt=""> </div> <div class="content_p"> <p>Retail Price:{{name.product_retail_price}}</p> <p>Quantity: {{name.product_quantity}}</p> <p>Date: {{name.product_sell_date}}</p> </div> </div> </div> {% endfor %} {% endblock %} This is my models.py file. class ProductsName(models.Model): product_name=models.CharField('name', max_length=50) product_retail_price=models.IntegerField('retail price TAKA') product_quantity = models.IntegerField('quantity') product_sell_date=models.DateTimeField('buy date', auto_now_add=True) product_image = models.ImageField(upload_to='upload/', blank=True, null=True) def __str__(self): return self.product_name When I visit my homepage, I can't see any image. But I see image link If I open my browser dev tools. chrome dev tool if I click that image link from chrome dev tool. I got andjango doesn/t found that image url error. -
How to use Django template context processor and form together?
I am a newbie to Django. In a project I have to take inputs for multiple models in Django using forms. For every model I have written functions (in views.py) and its corresponding Django template (in template folder). Such as,my Add Teacher function is, def add_teacher(request): form = TeacherForm() if request.method=="POST": form = TeacherForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print(form.errors) return render(request,"billing/add_teacher.html",{"form":form}) And billing/add_teacher.html template is, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Add Teacher</title> </head> <body> <h1>Add a Discipline</h1> <div> <form id="teacher_form" method="post" action="/billing/add_teacher/"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" name="submit" value="Add Teacher"/> </form> </div> </body> </html> Now, I want to use a template for all of my functions.Such as, I want to use this template for all functions with the help of Django template context processor. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>{{ h1 }}</h1> <div> <form id={{ form_id }} method="post" action="{{ action }}"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field … -
Django URL complicated patterns and paths
I'm trying to generated nested url paths. So far I could only generate 1 level urls. When I try second level urls it doesn't get called anymore, it still only shows the first level url although the address bar on the browser does direct to the second level url. Is this possible or do I need to create a new app? urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView, TemplateView from dashboard.models import IPARate,PCPRate from dashboard import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^medicare/', ListView.as_view(queryset=IPARate.objects.all().order_by("id"), template_name='dashboard/medicare.html')), url(r'^medicare/medicarepcp/$', ListView.as_view(queryset=PCPRate.objects.all().order_by("id"), template_name='dashboard/medicarepcp.html')), url(r'^medicare/', views.medicaid, name='medicare'), url(r'^medicare/medicarepcp/$', views.medicarepcp, name='medicarepcp'), ] -
jQuery keyup event is activated multiple times, doubling every time its triggered
I added an auto-completing search bar to my website. It queries the database for elements that start with the entered string every time the user types a new character. It works fine, however every time the user adds another character or does any keyboard event like backspace it doubles the event activation. 1,2,4,8,16, etc.. times. How could I make it so that it doesn't accumulate event triggers and only triggers .keyup() one time per keyboard event? Here's the HTML code: <form> <div class="nav-item"> <input class="search-query form-control" placeholder="Items" type="text" name="items" value="" id="id1" /> </div> </form> <hr> <div id="id2"> </div> And here's the jQuery code: $(document).ready(function() { $('#id1').keyup(function(){ var query = $(this).val(); $.get('/url/', {items: query}, function(data){ $('#id2').html(data); }); }); -
django create gif and store in DB
I'm receiving files from an input via a POST request. I'd like to take to those create a GIF from them and store it directly in a sqlite database. I have found various ways in python to create GIFs out of images and save them to the file system like the one here VALID_EXTENSIONS = ('png', 'jpg') def createGIF(data, duration=0.2): images = [] for d in data: images.append(imageio.imread(d)) output_file = 'Gif-%s.gif' % datetime.datetime.now().strftime('%Y-%M-%d-%H-%M-%S') imageio.mimsave(output_file, images, duration=duration) but I was not able to find a way of creating the GIF and either store it into variable or save it into the DB directly. Is there any way of creating a GIF and not have to save it to disk first before putting it in a DB? -
django dropdown item hyperlink not working when clicking
I am building a Django app and everything is working except the link in a dropdown menu. I have followed everything that was necessary, but somehow the link does not make Django to render the page. Under More the link About should work, but it does not. I include the code and also I have deployed it temporarily for a production inspection: http://azeribocorp.pythonanywhere.com/index html: {% load static %} {% load staticfiles %} {% block stylesheets %} <link rel="stylesheet" type="text/css" href="{% static 'css/_topnavbar.css' %}"> {% endblock %} <!--Top Navigation--> <nav role="navigation" class="nav" id="topnav"> <ul class="nav-items"> <li class="{% if request.resolver_match.url_name == 'index' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'index' %} class='nav-link'><span>Home</span></a> </li> <!--<li class="nav-item"> <a href={% url 'index' %} class="nav-link" ><span>Home</span></a> </li>--> <li class="{% if request.resolver_match.url_name == 'track_containers' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'track_containers' %} class='nav-link'><span>Track Containers</span></a> </li> <nav class="submenu"> <ul class="submenu-items"> <li class="submenu-item"><a href="#" class="submenu-link">Product #1</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #2</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #3</a></li> </ul> </nav> </li> <li class="{% if request.resolver_match.url_name == 'search' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'search' %} class='nav-link'><span>Search</span></a> </li> <li class="{% if request.resolver_match.url_name … -
Python web application installer packages?
Has anyone ever made an installer package for a Flask or Django (or other WSGI framework) application that lays down the code, virtualenv, configures the WSGI server (Gunicorn or uWSGI for example)? I've tried Googling the topic but I only find documentation about installing the frameworks themselves or deploying the applications to cloud services like AWS and Heroku. I know that all of the above could be scripted, but I'm interested in building actual installer packages for different platforms that get the WSGI app up and running and leaves the other needed components (such as database, cache, proxy, etc.) up to the administrator. Are there existing examples of this someone could point me to? Does anyone have suggestions on where to start for learning how to create these packages? -
Django DRY - how to simplify similar views using same template?
Please note: Just to make clear '[app_name]' is a placeholder for the actual app name. Not Django substitution code. Just imagine it says 'Stuff' instead of [app_name], if it's confusing. My question: How do I make this more DRY? There is a lot of code repetition, and there must be a way of unifying some of it. If you do answer, I would be really grateful if you write out explicitly what and why. As a lot of answers assume quite a bit of knowledge and I am trying into good habits in Django coding style and practice. Thank you for your time. [app_name]/urls.py from django.conf.urls import url from . import views app_name = 'things' urlpatterns = [ url(r'^cars/$', views.CarThingIndexView.as_view(), name='Car_index'), url(r'^trees/$', views.TreeThingIndexView.as_view(), name='Tree_index'), .... ] [app_name]/model.py from django.db import models class Tree(models.Model): """ Tree """ name_text = models.CharField(max_length=200) def __str__(self): return self.name_text class Car(models.Model): """ Car """ name_text = models.CharField(max_length=200) def __str__(self): return self.name_text [app_name]/view.py from django.views import generic from inventory.models import Car, Tree class CarThingIndexView(generic.ListView): template_name = '[app_name]/index.html' context_object_name = 'thing_list' def get_queryset(self): return Car.objects.values() class TreeThingIndexView(generic.ListView): template_name = '[app_name]/index.html' context_object_name = 'thing_list' def get_queryset(self): return Tree.objects.values() [app_name]/template/[app_name]/index.html {% extends '[app_name]/base.html' %} {% block content %} {% if … -
Gmail open tracking, set cookie with Django
I'm working on a simple app to embed a transparent pixel into emails being sent out manually with Gmail and then cookie the user. I'm inserting this <img> into the email: <img height="1" src="https://example.net/pixel.png?guid=1234" style="visibility:" width="1"> The intent is that when the email is opened it should request the image from example.net/pixel.png The Django app with an endpoint of pixel.png has this view: def set_cookie(request): PIXEL_GIF_DATA = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data = base64.b64decode(PIXEL_GIF_DATA) response = HttpResponse(data, content_type='image/gif') response.set_cookie('some_cookie_name', 'some_cookie_value') return response If I visit `example.net/pixel.png?guid=1234' it's setting the cookie appropriately, so we're good there. The only issue I'm running into is that when the email is opened the request is not being made out to my server. As the recipient if I go into the developer tools and watch the network requests I'm not seeing the request being made to mysite.net However, if I view the original email, down in the footer I can see that my <img> tag is included. If I try using an external image like static.example.net/images/sometest123.png the image does come through and is visible. -
Can I Use One view In a Django Project?
I´m new to web dev, and I was wondering if it´s possible to make a website,that just need to present informations of a company (HMTL), in just one View. Like rendering the Entire bootstrap in one view. -
Unable to install mysqlclient on centos
I am building a django app and for which i need to configure mysql.I am trying to install mysqlclient module for sql connection and this is what i am trying pip install mysqlclient --no-cache-dir It is throwing me following error.It is throwing error while linking to gcc library. Collecting mysqlclient Downloading mysqlclient-1.3.12.tar.gz (89kB) 100% |################################| 92kB 4.0MB/s Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /home/admin/awx.varadev.com/awxenv/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-6m2TNP/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-WFoARo-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/admin/awx.varadev.com/awxenv/include/site/python2.7/mysqlclient: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic … -
Django model django.db.utils.InternalError Can't DROP COLUMN
I have two models: I wanted to implement many-to-one relationship When I uncommented the school field in Weather. While migrating to the database. The error occured: django.db.utils.InternalError: (1091, "Can't DROP COLUMN school_id; check that it exists") Is there any posible reason to cause the error? class Weather(models.Model): time = models.DateTimeField() temperature = models.DecimalField(max_digits=3,decimal_places=1,default=None,null=True) humidity = models.DecimalField(max_digits=3,decimal_places=1,default=None,null=True) uv = models.IntegerField(default=None,null=True) light = models.IntegerField(default=None,null=True) rainfall = models.IntegerField(default=-1,null=True) #school = models.ForeignKey(School,related_name="weather",default=None,on_delete=models.CASCADE) def __str__(self): weather = '{0.time} {0.temperature} {0.humidity} {0.uv} {0.light} {0.rainfall}' return weather.format(self) class School(models.Model): name = models.CharField(max_length=10,null=False) eng_name = models.CharField(max_length=50,null=False) school_abbreviation= models.CharField(max_length=8,null=False) def __str__(self): school = '{0.name} {0.eng_name} {0.school_id}' return school.format(self) -
Angular couldn't find service
I'm building Angular 1.6.6 app with Django Rest Framework following tutorial by TrackMaven. My app couldn't find any services: ReferenceError: Can't find variable: retail Here is my service file: retail .factory('Chain', function ($resource) { return $resource( 'http://localhost:8000/chains/:id/', {}, { 'query': { method: 'GET', isArray: true, headers: { 'Content-Type': 'application/json' } } }, { stripTrailingSlashes: false } ) }); And my app.js: 'use strict'; var retail = angular.module("retail", []); angular .module('SampleApplication', [ 'appRoutes', 'retail', 'ngResource', ]); I think it's all about scopes but I can't figure out what's wrong. -
Can't rebuild indexes in django-haystack
I've installed Apache Solr 4.10.4, django-haystack 2.4.0, pysolr 3.3.2 and Django 1.8.6. I'm finishing make a simple blog application in Django framework. I typed following command in terminal: (my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py rebuild_index but it return me an error: WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 3 posts ERROR:root:Error updating blog using default Traceback (most recent call last): File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 1080, in _escape_attrib if "&" in text: TypeError: argument of type 'int' is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 188, in handle_label self.update_backend(label, using) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 233, in update_backend do_update(backend, index, qs, start, end, total, verbosity=self.verbosity, commit=self.commit) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 96, in do_update backend.update(index, current_qs, commit=commit) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/backends/solr_backend.py", line 75, in update self.conn.add(docs, commit=commit, boost=index.get_field_weights()) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/pysolr.py", line 807, in add m = ET.tostring(message, encoding='utf-8') File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 1125, in tostring short_empty_elements=short_empty_elements) File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 777, in write short_empty_elements=short_empty_elements) … -
Django jquery file upload: linking to another model
Setting up django-jquery-fileupload https://github.com/sigurdga/django-jquery-file-upload and it works, here's the model # encoding: utf-8 from django.db import models class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) and the view # encoding: utf-8 import json from django.http import HttpResponse from django.views.generic import CreateView, DeleteView, ListView from .models import Picture from .response import JSONResponse, response_mimetype from .serialize import serialize class PictureCreateView(CreateView): model = Picture fields = "__all__" def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') for now ignoring how behind the scenes it uploads the images, what I do however need to figure out is … -
Django - How to reorder model objects
Let's say I want to reorder fruits. Somewhere in the code I call fruit.reorder(3) where fruit is the fruit I want to move and 3 is the ID after which I want to insert the fruit. Before calling reorder, fruits where in the following order : 4,3,6,1. And now, given that the calling fruit is 1, the order would be : 4,3,1,6. How should I implement def reorder: in Fruit.py model to achieve this ? -
Django raises NoReverseMatch: 'en-us' is not a registered namespace
Django raises django.urls.exceptions.NoReverseMatch: 'en-us' is not a registered namespace How i can fix it? -
Schedule task in Django using schedule package
I am trying to learn how to scheduled a task in Django using schedule package. Here is the code I have added to my view. I should mention that I only have one view so I need to run scheduler in my index view.. I know there is a problem in code logic and it only render scheduler and would trap in the loop.. Can you tell me how can I use it? def job(): print "this is scheduled job", str(datetime.now()) def index(request): schedule.every(10).second.do(job()) while True: schedule.run_pending() time.sleep(1) objs= objsdb.objects.all() template = loader.get_template('objtest/index.html') context= { 'objs': objs} return HttpResponse(template.render(context, request)) -
How can I get the IP address of RabbitMQ running from another container (Docker Compose)?
I am following this tutorial. In there, I need to set RabbitMQ IP address to my Celery settings. I have three containers in my docker-compose.yml: NGINX, Django + Celery, and RabbitMQ. These are all run with docker-compose up. However, I need to have the RabbitMQ IP address for celery.py in different container. Looking through Google, docker-machine ip <container> should be the solution. However, docker-machine only works for running container, AFAIK. So, how can I pass container IP address to another container in same docker-compose.yml file? In this case I want to have my RabbitMQ IP address. -
customize django admin object detail page url(object change url)
I am trying to override the default django admin change url. I my table i have composite primary key. class ABC(models.Model): code = models.ForeignKey('PQR', models.DO_NOTHING, db_column='code', primary_key=True) language = models.ForeignKey(Languages, models.DO_NOTHING, db_column='language') me_name = models.TextField() common_name = models.TextField(blank=True, null=True) abbreviation = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'abc' unique_together = (('code', 'language'), ('language', 'me_name'),) Now my admin url in django admin for each object is /admin/home/abc/{{code}}/change/. But i have repeated codes in objects because primary key is composite of ('code', 'language'). So for objects which have repeated code are throwing Error MultipleObjectsReturned at /admin/home/abc/X00124/change/ get() returned more than one ProcedureTranslations -- it returned 2! here X00124 this code associated with more than one object. What i want here that override the modeladmins get_urls() method and construct the url /admin/home/abc/{{code}}/{{language}}/change/. I tried but no success. Help will be appreciated. -
Django+Jinja2+i18n: jinja2.exceptions.UndefinedError: 'gettext' is undefined
I'm trying since many hours to get things work, but still without success. I use Jinja2 with Django (https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2) and now I try to enable translations. Jinja2 docs suggest (http://jinja.pocoo.org/docs/2.9/extensions/#i18n-extension) existing extension (jinja2.ext.i18n). So my configuration looks like this: settings.py TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": False, 'OPTIONS' : { 'environment': 'config.jinja2.environment' } }] jinja2.py: def environment(**options): env = Environment(**options, extensions=['jinja2.ext.i18n']) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, 'dj': defaultfilters }) return env within template: {{ gettext('...') }} result: jinja2.exceptions.UndefinedError: 'gettext' is undefined Does anyone know what the problem is and what I miss? thanks for help in advance! -
Can't edit richtext field in Wagtail
We have a magazine and use Django project and Wagtail. We came upon a very bizarre bug: One of our remote editors is unable to edit one specific field, that is the main content body of the page. He is able to see the text, but when tries to click nothing happens. It does not enter edit mode, like it is disabled, but ONLY for him: He is not trying locally, he is trying live, so there is not a difference between Wagtail versions He cannot edit using his credentials, or any other credentials He tried different browsers and different computers I tried with his credentials and I am able to edit Any idea of what could be causing this? Could the location have something to do? -
DRF - How to handle exception on serializer create()?
I'm using the friendship Django module with Django Rest Framework. When creating an API the Serializer's create() may raise some exceptions - AlreadyFriendsError, DoesNotExist or AssertionError. Now when an exception occurs, the return object is not valid (None) and I get a Traceback with the AssertionError: create() did not return an object instance. From my API views.py class FriendManageAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = FriendManageSerializer def post(self, request, *args, **kwargs): if request.data['action'] == 'add_friend': return self.create(request, *args, **kwargs) From my API serializers.py class FriendManageSerializer(serializers.ModelSerializer): to_user = serializers.CharField(max_length=150) def create(self, validated_data): friendship_ret = None try: request = self.context.get("request") if request and hasattr(request, "user"): user = request.user user_model = get_user_model() to_user = user_model.objects.get(username=request.data['to_user']) friendship_ret = Friend.objects.create( from_user=user, # The sender to_user=to_user, # The recipient ) friendship_ret.save() except (AlreadyFriendsError, user_model.DoesNotExist, AssertionError): print("EXCEPTION FriendManageSerializer.create()") return friendship_ret How should I really handle this case? What should I be returning when the object is not valid?