Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django REST framework parse request.data raising error
In Django view, I am trying this- @csrf_exempt @api_view(['GET', 'POST']) def EmployeeList(request): if request.method == 'GET': employees = PersonalInfo.objects.all() serializer = PersonalInfoSerializer(employees, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) print data serializer = PersonalInfoSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) On posting data from postman, It raising attribute error { "detail": "JSON parse error - No JSON object could be decoded" } when using data = JSONParser().parse(request.data) instead of data = JSONParser().parse(request) getting this error : AttributeError: 'QueryDict' object has no attribute 'read' -
how to test inline formset
There is an inline formset that works perfectly well. It fails only in testing. there is a model that connects two types of participants: senders and receivers. models.py: class SendReceive(models.Model): receiver =jmodels.ForeignKey(Player, related_name='receiver') sender = models.ForeignKey(Player, related_name='sender') amount_requested = models.IntegerField() amount_sent = models.IntegerField(blank=True) An inline formset is shown to senders, who choose how much to send to receivers: forms.py: class SRForm(forms.ModelForm): class Meta: model = SendReceive fields = ['amount_sent'] SRFormSet = inlineformset_factory(Player, SendReceive, fk_name='sender', can_delete=False, extra=0, form=SRForm, ) and views.py (CBV): def post(self): context = super().get_context_data() formset = SRFormSet(self.request.POST, instance=self.player) context['formset'] = formset if not formset.is_valid(): return self.render_to_response(context) formset.save() return super().post() so, when I try to test it, the line formset.save() brings in error: django.db.utils.IntegrityError: NOT NULL constraint failed: riskpooling_sendreceive.receiver_id as the receiver id was not set. Although, if I look at the content of the formset.forms which is returned, everything is in there. Again, in the real life everything is ok, and is properly saved. So only testing results in error. What I am doing wrong? -
django running on local machine cannot connect to docker container running MYSQL
Hi all so i'm attempting to run django on my local machine to connect to a docker container running mysql but keep getting an error when attempting to install mysqlclient via pip. First i got this error when attempting to install mysqlclient : Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-mejs2ys1/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-mejs2ys1/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-mejs2ys1/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found Then i went ahead and installed mysql-connector-cvia brew. I reran pip install mysqlclient and now i get this error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-8wu06grt/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-8wu06grt/mysqlclient/setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-8wu06grt/mysqlclient/setup_posix.py", line 54, in <listcomp> libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-8wu06grt/mysqlclient/setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] … -
submit multiple forms in a single django template
I have a django project with a single html template. i am want to know if it is possible to pass multiple forms into a single template. I want to process the form differently for each of the forms that are passed. Is that possible to do and how can I differentiate the different forms for processing... if anyone can help, I would much appreciate it. -
I am getting following error when I create a django project in pycharm for Mac OS
I have been installed django using following command in terminal: sudo pip3 install django and I got this response: kinredondeMacBook-Air:~ kinredon$ sudo pip3 install jiango The directory '/Users/kinredon/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/kinredon/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already satisfied: jiango in /usr/local/lib/python3.6/site-packages Requirement already satisfied: django<1.5,>=1.4 in /usr/local/lib/python3.6/site-packages (from jiango) then I create a django project in Pycharm and I get this following error: Error:Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/bin/django-admin.py", line 2, in <module> from django.core import management File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax Anyone can help me? Thanks! -
AttributeError at /admin/login/ 'tuple' object has no attribute 'rsplit'
Hye . i come accross this error when i try to login to my admin page . AttributeError at /admin/login/ 'tuple' object has no attribute 'rsplit' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.10 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'rsplit' Exception Location: C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\utils\module_loading.py in import_string, line 15 Python Executable: C:\Users\Adila\Envs\tryFOUR\Scripts\python.exe and i dont know why this error is raised and i dont know how exactly to fix it . i do search about this error and most of them when they try to run the collectstatic command. the error is caused by the comma and i did delete the comma behind the closed bracket here : STATICFILES_DIRS= ( os.path.join(os.path.dirname(BASE_DIR), "static", "static") ) but i still cant access to my admin page . i did follow to the traceback : def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) module = import_module(module_path) i try to make my own custom registration page for user and super … -
Django file uploading error
i am trying to upload file but unable to do so, my function in view, def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) if form_new.is_valid(): return redirect('in') else: form_new = Fileupload() return render(request, 'accounts/in.html', {'form_new': form_new}) my form, class Fileupload(forms.Form): BrowseFile=forms.FileField() class Meta: model=User and my template, <form action="." method="POST" enctype="multipart/form-data" > <h3>Welcome to DropBox<br><br></h3> {% csrf_token %} {{form_new.as_p}} <p><input type="submit" value="Save" ></p> <br> <a href="{% url 'logout' %}">Logout</a> {%else%} <p>You must login first</p> <a href="{% url 'login' %}">Logout</a> {% endif %} <br> </form> after pressing submit button i do not see any doc in media location. Am i doing something wrong or anything missing? Thanks in advance. -
django model get field method
I have a requirement, when a field say Price in a django model Lead is accessed I have to apply some business logic and update the price. I can accomplish in Serializers / Views. However this object is accessed by several views and hence its not a viable design to have a code in several place. So i'm looking for a way where i can get control like get_price(self). class Lead(models.Model): price = models.IntegerField(_('price'), default=10) def get_price(self): ''' Looking for something like this ''' get_price to be called when any serializers/ views access this model. -
Using bt module in Django gives error for pandas Key error volume Exception
index = [u'bfh', u'qhf'] then i will convert into comma seprated value like index = ", ".join(str(bit) for bit in index) after run, data = bt.get(index, start=start, end=end) gives an error Django Version: 1.8 Exception Type: KeyError Exception Value: 'Volume' in pandas -
Use a 'join-query' like ‘’SQLAlchemy‘’ in ‘’Django‘’?
How to use Django: get user followed_set all articles? use in sqlAlchemy: Article.query.join(Follow, Follow.followed_id == Article.user_id)\ .filter(Follow.follower_id == self.id) My Code: class User(AbstractUser): # Author pass class Article(models.Model): content = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Follow(models.Model): # user ManyToMany timestamp = models.DateField(auto_now_add=True) follower = models.ForeignKey(User, related_name='followed_set', on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name='follower_set', on_delete=models.CASCADE) -
Trouble updating BooleanField with Django ModelForm
Using Django 1.11 and Python 3.4 I have a model: class ToDo(models.Model): completed = models.BooleanField(default=False) I want users to be able to update this field for the model by clicking a checkbox, so I made a ModelForm as follows: class CompletedForm(ModelForm): class Meta: model = ToDo fields = ['completed'] The problem I am having is understanding how I can get the database to update whenever the user clicks the checkbox, so that the completed field will toggle between True or False. In views.py: if request.method == 'POST': for x in range(0, all_todos.count()): a = all_todos[x] completedform = CompletedForm(request.POST, instance=a) else: for x in range(0, all_todos.count()): a = all_todos[x] print(a) completedform = CompletedForm(instance=a) I've rendered the checkboxes in the event of either GET or POST method, and linked each box to a particular instance. I assume that most of the logic will take place in the POST method since this is making a change to the database. Thank you -
How to Embed a Hyperlink - Django app
I'm pretty much new to web development using Django, python, html, I've created have a basic Django app that displays a list of users from mysql, and all works just fine. I now want to make it so that user can click on the return value such as total books by users, date, etc.. is a link that when clicked on will redirect to other page and displays the detail of that query, hopefully someone can walk me through..Thanks in advance.. # here I get all counter I need and it works just fine def _get__user_info(self, qs): user.data['total_book'] self._get_all_count(mydata, "total") ..... -
Context from Django Render Not Displaying Till Refresh?
I am using an AJAX call to POST a value to my views. From my views I am finding the product based on the value(id) passed to my view. I add it to my invoice and apply it to my context which I render at the bottom of my view. The context will not be displayed until I refresh, but I can't have that. I am stuck. ... elif request.is_ajax(): product_id = request.POST.get('value') if product_id: product_info = Product.objects.get(id=product_id) new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info) invoice.attached_products.add(new_invoice_product) context['attached_products'] = invoice.attached_products.all() ... return render(request, 'inventory/invoice_create.html', context)