Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I inspect a ValidationError exception while testing with django TestCase?
I'm working with Django testing using a django.test.TestCase and I would like to know the pythonic way to inspect a validation error. I've come up with the below, which works, but it feels a little long winded and prone to error over a large number of tests self.valid_account.contact_number = "1234567" # Too short with self.assertRaises(ValidationError): try: self.valid_account.full_clean() self.fail("Did not raise validation error") except ValidationError as e: self.assertTrue('contact_number' in e.message_dict) raise e Is there a better way to inspect and test an exception? -
Heroku not loading procfile
I've tried other peoples solutions to getting there procfile recognised and it's just not working for me. Really confused about how I can get heroku to recognize my Procfile! I've moved it around into different folders and whatnot but it just won't recognise it. web: waitress-serve --port=$PORT alex1.wsgi:application This is my code. It's sitting right next to my requirements.txt file which is getting picked up by heroku fine. using echo to create the file or even echo is not working. https://github.com/Hewlbern/Videography-Website/tree/master/Alex1 <--- the github link that I'm trying to deploy to heroku from. Can see where i've placed it and etc if anyone can help! Such sad, many mad. -
Different databases for forms and authentification in django?
Is it possible to use one database for user authentifications in django and another database for working with django-forms? I work with non-relational data structures and feel comfortable with mongodb forms, but I unable to authorize my users, using mongodb. All posts describing mongodb-authentification with django referer to deprecated modules of mongoengine, which is no longer support django. So I decide to use mysql for user authentification and mongodb as main database, but cannot find information about defining special database for user authorization. -
Django-rest-framework: API documentation separate from app?
I want to be able to automatically generate API documentation for my project, but I don't want it to be published with the application itself, instead, I want it published in our local network and serve as a reference both for users of the API and the developers of the API. That is, I would want to design the interfaces first, write them as stubs, autogenerate the API documentation and publish it in the intranet. I have looked into a number of API documentation solutions, but all of them seem to add web-pages with the docs to the app itself. Is there a way to generate separate API docs? -
Django Models: Is it possible to overwrite the getter function of an attribute that is defined in an AbstractModel in its SubClass?
I have the following scenario: class AbstractProduct(models.Model): title = models.CharField(max_length=255) this abstractmodel is part of a third-party framework and therefore I cannot (should not) change the code of this abstract model. In my codebase I have the following: class Site(models.Model) domain = models.CharField(max_length=255) class ProductSiteLink(models.Model) product = models.ForeignKey(Product) site = models.ForeignKey(Site) product_title = models.CharField(max_length=255) class Product(AbstractProduct): price = models.DecimalField(decimal_places=2, max_digits=12) site = models.ManyToManyField(Site, through='ProductSiteLink') My goal is to move the title attribute of the Product to the ProductSiteLink Relation (product_title). Of course I could define get_product_title function in my Product model that looks up the right title for the product in the ProductSiteLink table and returns it. But since I cannot delete the title attribute of the Product model because it is defined in the AbstractProduct I would also have the possibility in the codebase to call product.title which would be misleading because it would return something different than get_product_title() . According to In Django - Model Inheritance - Does it allow you to override a parent model's attribute? : In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are … -
(fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
ERRORS: blog.Post.author: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I know that I need to swap in settings.AUTH_USER_MODEL for auth.User, but for some reason doing this causes my blog to not show up. The routing is correct when I try to view blog from navigation bar but there is no content anymore. I also cannot login or create a new user on Django admin. These issues started occuring with setting an AUTH_USER_MODEL in settings for accounts. blog/models.py from django.db import models from django.utils import timezone from fitness_project import settings class Post(models.Model): author = models.ForeignKey('auth.User', related_name='User') #author = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', 'blog', 'membership', 'accounts', 'django_forms_bootstrap', ] AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuth', ) blog/admin.py from django.contrib import admin from .models import Post admin.site.register(Post) -
Django-reversion add new version to already created revision
I have created a "backup" functionality using the Django Reversion library for an object that keeps revision of a registered model, including the related objects (foreign keys etc.). Let's use the following case as an example. class Newspaper: title = models.CharField() class Article: newspaper = models.ForeignKey('Newspaper') When the user clicks to keep a backup of a newspaper object, a revision of the newspaper is created along with the already created articles, under the same revision. I did it so that when the user chooses to revert back to the latest backup, all related objects under the same revision to be reverted. The problem starts when a new article of the newspaper is created after the revision is created. The issue is that if the user chooses to revert to the previous revision (the one before creating the new article), the new article will still be there because it was not registered in the latest revision. Furthermore, I don't want to create a new revision every time a new article is created because then there might be other changes included that the user will not want to include to the revision. What I think might be a suitable solution, is when … -
python 3.5.2, django 1.11.5
Halo, i'm trying to upload a file using filefield. But i always failed. when statement form.errors.as_data() executed, the browser return 'tempfile'. I already trying to find solution from django documentation and some django references. But, still can't fix it. ;( Here's my view.py def dataprocessing(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): import pdb; pdb.set_trace() newdoc = Document(docfile=request.FILES['myfile']) newdoc.save() #Redirect to the dataprocessing after POST #return render(request, 'dataprocessing.html') return HttpResponse("success") else: return HttpResponse(form.errors.as_data()) else: import pdb; pdb.set_trace() form = DocumentForm() #A empty, unbound form return render(request, 'dataprocessing.html', {'form': form}) models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') forms.py class DocumentForm(forms.Form): tempfile = forms.FileField() And dataprocessing.html <form method="post" enctype="multipart/form-data" action="{% url "dataprocessing" %}"> <div class="form-group"> <label for="up">Input Data</label> {% csrf_token %} <input type="file" name=myfile class="filestyle" data-buttonName="btn-primary" data-buttonBefore="true" data-size="sm" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" id="up"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Upload Data</button> <button type="button" class="btn btn-primary btn-block">Download Template</button> </div> </form> -
How to lay out a REST Project?
I recently tried learning the django-restframework and now I want to turn my new and fragile knowledge into a test project. It is a Project that contains rendered html templates as well as an API to a React Native front-end. Is it recommendable to write all the views as APIViews (api_views for function based) instead of regular Django views (e.g. GCBV)? Since I usually declare a template_name property it the view it is - sort of -bound to the website? Or can I later declare the way I want to render dynamically depending on weather I want to render to the app or the website? Or do I need separate views for the website and app regardless? -
DRF3 Creating nested serializers on m2m-relation
I have a User-model and a Concert-model. The Concert-model has a m2m-field to the User-model. In the Concert-views, I want a list of dictionaries of the User's with a relation to the Concert-model. This is what I got: models.py class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() name = models.CharField(max_length = 255, default = "") date_added = models.DateField(auto_now=False, auto_now_add=True) email = models.EmailField(unique=True, db_index=True) (more but irrelevant) class Concert(models.Model): name = models.CharField(max_length = 255) technicians = models.ManyToManyField(User) serializers.py class ConcertListSerializer(serializers.ModelSerializer): technicians = UserDetailSerializer( many=True, read_only=True, source='concert_set' ) class Meta: model = models.Concert fields = [ 'name', 'technicians', 'id', ] class UserDetailSerializer(ModelSerializer): class Meta: model = User fields = [ 'name', 'email', 'id', ] What I expect is the technicians-field in the ConcertListSerializer to be a list of dictionaries with name, email and id of the users. Why does it not provide this like the DRF Documentation on Nested Serializers says it will .. ? -
Django channels websocket disconnects after handshake
I am building a simple chat room following examples of django channels. Everything worked like a charm yesterday and I managed to create a chatroom and even managed to chat in there. All of a sudden without any change in my code the Websocket started disconnecting immediately after connection and handshake. My setup: Django == 1.10.5 Python == 2.7 channels == 1.1.8 asgi-redis == 1.4.2 daphne == 1.3.0 My consumers.py looks like this: consumers.py: @channel_session def ws_connect(message): room = message.content['path'].strip("/") message.channel_session['room'] = room Group("chat").add(message.reply_channel) message.reply_channel.send({"accept": True}) And the frontend part : $(function() { // When we're using HTTPS, use WSS too. var ws_scheme = window.location.protocol = "ws"; var chatsock = new WebSocket(ws_scheme + '://' + window.location.host + window.location.pathname); chatsock.onmessage = function(message) { var data = JSON.parse(message.data); var chat = $("#chat"); var ele = $('<tr></tr>'); console.log(data); ele.append( $("<td></td>").text(data.timestamp) ); ele.append( $("<td></td>").text(data.handle) ); ele.append( $("<td></td>").text(data.message) ); chat.append(ele) }; $("#chatform").on("submit", function(event) { var time = new Date(); var string = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); // var timestamp = time.getHourMinuteSecond(); var message = { timestamp: string, handle: $('#handle').val(), message: $('#message').val() }; console.log("submit"); chatsock.send(JSON.stringify(message)); $("#message").val('').focus(); return false; }); }); Maybe an update in some technology is out. I am struggling … -
Create an estimator tool in Django Python
I am new to Django. I have read the official documentations and managed to create models in Django. I have a task to create an estimator tool that could provide the estimate(cost) to the user when he selects the hardware/softwares etc. This could be something similar to this http://calculator.s3.amazonaws.com/index.html. This is only for reference but I want to add details dynamically and I want to have edit option also for the details added. So far I have come to this below point (check image for reference) but I cannot edit this once I save. Could anyone direct me to any tutorial/project that I can follow to achieve my task? -
Issue with Django Template Background
I'm getting an issue with my background template picture. Each time I'm loading Django template, my background is black in the first time, then becomes good with my picture after 0.5/1 second. I wrote in my script (Common HTML Template) : {% load staticfiles %} {% load static %} {% load user_tags %} {% load variables %} <style> body { background-image:url("{% get_static_prefix %}{{ mytheme }}/images/bg.jpg"); } </style> The url path is good because my picture is loaded, but I have this black background before during ~ 1s I didn't write background picture in my CSS file, but only in my common template (navbar template which is called each time). Do you have any idea ? -
How to overwrite django-redux default user registration form
When the default django-registration-redux registration page loads, it displays fields for username, email, password, along with labels instructing the user on minimum xters for username, and a list of instructions on setting password. I want to be able to add some fields to the form, also, I want to remove the list of instruction labels. I could do it with JS but how do i overwrite the class from the django-registration-redux. Pls i really need help. I have tried subclassing different classes, yet no headway. -
How socket file is created in Gunicorn
I am deploying a Django project using Gunicorn as application server and Nginx as a web server. This is the tutorial http://tutos.readthedocs.io/en/latest/source/ndg.html which I am following. Code for the gunicorn_start.sh (kept in the folder where the project resides). #!/bin/bash NAME="visualization" DJANGODIR=/var/www/dist/adc # Django project directory* SOCKFILE=/var/www/dist/run/gunicorn.sock USER=barun GROUP=barun NUM_WORKERS=1 DJANGO_SETTINGS_MODULE=adc.settings DJANGO_WSGI_MODULE=adc.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/barun/anaconda3/envs/adcenv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/barun/anaconda3/envs/adcenv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ #we should put the address gunicorn address --name $NAME \ --workers $NUM_WORKERS \ --user $USER \ --bind=unix:$SOCKFILE Code for gunicorn.service (/lib/systemd/system/gunicorn.service): [Unit] Description=visualization gunicorn daemon [Service] Type=simple User=barun WorkingDirectory=/var/www/dist ExecStart=/home/barun/anaconda3/envs/adcenv/bin/gunicorn --workers 3 -- bind unix:/var/www/dist/run/gunicorn.sock adc.wsgi:application [Install] WantedBy=multi-user.target Everything is working fine. The location is given in gunicorn_start.sh file for creating a socket file, the run folder is created but gunicorn.sock file is not creating. There is not permission related problem Apart from this, The error I am getting in Nginx error.log file is: 4783#4783: *1 connect() to unix:/var/www/dist/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 172.16.1.213, server: 192.16.1.213, request: "GET / HTTP/1.1", upstream: … -
Django How to make use of the creation method for a custom user with permissions?
So I have this method: def create_editor(self, email, dob, password): user = self.create_user( email, dob, accepted_tos=True, password=password ) try: editors = Group.objects.get(name__iexact="Editors") except Group.DoesNotExist: editors = Group.objects.create(name="Editors") editors.permissions.add(Permission.objects.get(codename="can_give_discount")) # add can_give_discount permission user.groups.add(editors) user.save() return user To create a normal user and then add the user to the editor group I want to be able to create a manager from the normal django admin. But it looks like I have to manually create the group from the admin side. -
Django-machina 0.5 install bug
I try to use Django-machina 0.5 as forum-implementation above django-1.11.5. This line from PIL import Image as PILImage does not work in Django-machina 0.5 but works in my Python interpreter (which means that my Pillow==4.0.0 is good) Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image as PILImage >>> My error-message is as follows (skyenv) D:\prj\skyenv\feldman2017>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0432E978> Traceback (most recent call last): File "D:\prj\skyenv\lib\site-packages\machina\core\compat.py", line 13, in <module> from PIL import Image as PILImage ModuleNotFoundError: No module named 'PIL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\prj\skyenv\lib\site-packages\machina\core\compat.py", line 17, in <module> import Image as PILImage # noqa ModuleNotFoundError: No module named 'Image' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\prj\skyenv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\prj\skyenv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\prj\skyenv\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "D:\prj\skyenv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "D:\prj\skyenv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\prj\skyenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File … -
How to create a custom widget using django for use on external sites
I hava a new site that I am working on. The site will have prior agreement with eCommerce sites to include add-ons on their website. Consider the following example: My website, ABC.com is targeting ecommerce sites. For every ecommerce site that sells product X, I want them to include an add-on that gives buyers the option to purchase service Z if they so desire. ABC.com will be communicating with the ecommerce sites through a REST API. My challenge is how to integrate my service as an add-on into the external ecommerce sites. This I assume will be in the form of a widget, HTML code, or a bit of javascript. Something similar to the attached image from Amazon.com. I'm aiming to make a simple integration with the external sites to avoid having them do too much on their end. Is there a best practice on how to handle this? See an example from Amazon: -
How to get a value from related object in a django template
I'm quite new with python and django and I apologize if the topic was already covered, but I coudln't find an answer to my question. I have theese classes in my models.py class Category(models.Model): category_type = models.CharField(max_length=50) description = models.TextField() def __unicode__(self): return self.category_type class Area(models.Model): area_type = models.CharField(max_length=50) description = models.TextField() def __unicode__(self): return self.area_type class Topic(models.Model): topic_type = models.CharField(max_length=50) description = models.TextField() def __unicode__(self): return self.topic_type class Tag(models.Model): tag_type = models.CharField(max_length=50) description = models.TextField() def __unicode__(self): return self.tag_type class GenericRecord(models.Model): document_title = models.CharField(max_length=500) category = models.ForeignKey("Category") area = models.ForeignKey("Area") topic = models.ForeignKey("Topic") tag = models.ForeignKey("Tag") note = models.TextField(null=True, blank=True) link = models.TextField(null=True, blank=True) file_upload = models.FileField(upload_to='GenericRecord/', null=True, blank=True) class Meta: abstract = True class Document(GenericRecord): code = models.CharField(max_length=500, null=True, blank=True) reference = models.CharField(max_length=500) issue_date = models.DateField(auto_now=False, auto_now_add=False) validation_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) def get_admin_url(self): return reverse("admin:%s_%s_change" % (self._meta.app_label, self._meta.model_name), args=(self.id,)) def __unicode__(self): if self.code: return "%s-%s" % (self.code, self.document_title) else: return "--%s" % self.document_title And this piece of code in views.py def documents_list(request): # Generate counts of some of the main objects num_docs=Document.objects.all().count() docs=Document.objects.all() num_articles=Article.objects.all().count() articles=Article.objects.all() template='documents_management.html' for object in docs: object.fields = dict((field.name, field.value_to_string(object)) for field in object._meta.fields) # Render the HTML template documents_management.html with the … -
Django why is a permissions code name different from checking if it has a permission?
When adding a permission to a group I use: managers.permissions.add( Permission.objects.get(codename='add_user') ) Using the codename add_user Now when checking if a user has a particular permission, I use users.add_user ie. the app_name prepended self.assertTrue(self.user.has_perm('users.add_user')) Why is that. Is it possible to get the permission with users.add_user. When I try it I get: django.contrib.auth.models.DoesNotExist: Permission matching query does not exist. -
What happen if `queryset` and `get_queryset` are both defined on a Django ViewSet that inherits from GenericViewSet
I've inherited some Django code and I am struggling to work out what the previous developers have intended with their code. There is a ViewSet which is configured, which inherits from GenericViewSet. In the class it defines a queryset variable but also defines a get_queryset method. I'm struggling to work out from the docs and tutorials what this even means? What's more interesting is that the get_queryset method returns a queryset of one type, but the queryset variable defines a different type. What I'm hoping for is for both querysets to be combined (which is the desired behaviour, and which appears to be happening on one server, but not another, so some additional investigation will be needed to work out why) Code below: class FeedbackFieldViewSet(NestedViewSetMixin, customer_mixins.CustomerProviderMixin, mixins.ListModelMixin, viewsets.GenericViewSet): ## # Instantiates and returns the list of permissions required by this viewset. # # @return The list of permissions. # def get_permissions(self): # Maps action names to tuples of permission classes. permissionDict = { "list": self.listPermissionClasses, } if self.action in permissionDict: return [permission() for permission in permissionDict[self.action]] if self.request.method == "OPTIONS": # Anyone can submit an options request return [] raise ProgrammingException("A request with an unknown permission model was received.") listPermissionClasses … -
Change queryset before passing to template Django
I have a many-to-many relationship between two models Foo and Bar. class Foo(models.Model): ... class Bar(models.Model): ... foo = models.ManyToManyField(Foo) I do the following database queries in order to get all of the entries for Foo that are null for a certain field. I am then able to get all the entries in Bar that match the many-to-many relationship. bar = Bar.objects.filter(field__isnull=True) foo_bar_pks = bar.values('foo') foo = Foo.objects.filter(pk__in=foo_bar_pks) I want to replace the value stored at Bar.foo to the corresponding value in foo. Because when I pass to the template I want to use a for loop to go through bar and be able to display the correct foo value. -
Modify required flag of field in Django Class Based View
I have following model used in my Django CBV CreateView: class Agreement(BaseModel): offer = models.ForeignKey(Offer, null=True, blank=True) owner_name = models.CharField(), max_length=15, null=True, blank=False) has_second_owner = models.BooleanField(default=False) second_owner_name = models.CharField(max_length=15, null=True, blank=True) And form: class AgreementForm(BootstrapFormMixin, forms.ModelForm): class Meta: model = Agreement fields = ('owner_name', 'has_second_owner', 'second_owner_name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-5' self.helper.field_class = 'col-sm-7' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.form_id = self.__class__.__name__.lower() self.helper.layout = Layout( Field('owner_name'), Field('has_second_owner'), Field('second_owner_name'), ) I am using CreateView to crate instances of Agreement model. By default, second_owner_name isn't required (because has_second_owner is False). In case user change has_second_owner field I have to modify second_owner_name field to be required in the view. How should I do this? What is a proper method to modify fields depending on POST data? Thank you -
Django InlineFormset : Customize inputs and widget
I’m using inlineformsets for an Image Model in combination with a Product Model. For the Image Model (using javascript): 1) a remove/delete button will be available to remove an image; the image can be remove not only on edit, but also on creation(the use upload the image, but before saving doesn’t like the image and removes it) 2) An add button, when the user clicks a new input and corresponding fields are added By default the inlineformset code is like this: <tr><th><label for="id_product_images-0-document">Document:</label></th><td><input type="file" name="product_documents-0-document" id="id_product_images-0-document" /></td></tr> <tr><th><label for="id_product_images-0-file_type">File type:</label></th><td><input type="text" name="product_documents-0-file_type" maxlength="255" id="id_product_images-0-file_type" /></td></tr> <tr><th><label for="id_product_images-0-DELETE">Delete:</label></th><td><input type="checkbox" name="product_documents-0-DELETE" id="id_product_images-0-DELETE" /><input type="hidden" name="product_documents-0-id" id="id_product_images-0-id" /><input type="hidden" name="product_documents-0-product" id="id_product_images-0-product" /></td></tr> Using inputs I can do it with javascript, but things get a little more complicated for what I want to do: The user should click on an image button a modal window will appear with the option to crop. Now the Upload button is in the modal window. The user is cropping, I select and save the coordinates with javascript, also show a cropped image (simulated using css). How do I transfer all this mechanism to Django inputs so formsets can understand what I want to do ? -
Unable to render Payfort response in new tab as html
I am trying to submit Payfort form through iframe and get response in a new tab using javascript but my problem is response is rendering as unicode rather then html. see attachment image. Any Help? PageContent