Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The correct way to upload and modify image with Django FormWizard
I have two templates. post_new.html: This is for uploading image. post_confirm.html: This is for confirmation of post. If we want to modify image or title, push the Edit button, and go back to post_new.html to modify. I have many questions. The First Question: I don't know how to display uploaded image file in post_confirm.html. And If I uploaded images in post_new.html, I can see file name like And then I go to post_confirm.html, I want to see the uploaded image file. But I don't know how to display image file. The Second Question: If I go back to post_new.html by pushing edit button, There is no files like In short, I don't know how to handle image file totally. views.py TEMPLATES = {'0': 'classifieds/post_new.html', '1': 'classifieds/post_confirm.html',} class PostWizard(SessionWizardView): form_list = [RealEstatePostForm, PreviewForm] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp')) def get_template_names(self): return [TEMPLATES[self.steps.current]] def get_context_data(self, form, **kwargs): c = super(PostWizard, self).get_context_data(form=form, **kwargs) c.update({'post_to': 'Real Estate'}) if self.steps.current == '1': form = self.get_form(step='0', data=self.storage.get_step_data('0'), files=self.storage.get_step_files('0')) c.update({ 'form': form, }) return c def done(self, form_list, **kwargs): for form in form_list: post = form.save() post.save() return redirect('post_detail_real_estate', pk=post.pk) post_new.html {% extends "base.html" %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content … -
How to iterate over the same index twice in a Python for loop? Django [on hold]
I fetch random data for users. For each city I fetch two sets of data one for males and one for females. When I create profiles, I want to send the same city twice (for males and females of London, for males and females of Paris ...etc.). cities = populate_cities() # random data URLs urls = ['https://randomuser.me/api/?nat=gb&gender=male&results=5', 'https://randomuser.me/api/?nat=gb&gender=female&results=5'] #go through random data urls for i in range(len(urls)): users_in_json = get_json(urls[i])#bring json data for users of specific city and gender user_list = get_users(users_in_json)#returns list of User objects #send User objects list, json data and City objects to create profiles # this is where my problem is as I want to send the same City object twice user_profiles = get_profiles(user_list, cities[i], users_in_json) -
Filtering on many to many in Django
i can't get this query to return more than one exercise object, even though if i use the generated query in sql it returns both exercises as i expect class Workout(models.Model): created = models.DateTimeField(auto_now_add=True) workout_type = models.ForeignKey(WorkoutType, on_delete=models.CASCADE) exercises = models.ManyToManyField(Exercise, through=u'WorkoutExercise', related_name=u'workout_exercises') class WorkoutExercise(models.Model): exercise = models.ForeignKey(Exercise) workout = models.ForeignKey(Workout) class Exercise(models.Model): name = models.CharField(max_length=255, unique=True) And the query is to return every exercise for the latest workout workouts = Workout.objects.latest('created') exercises = Exercise.objects.filter(workout_exercises__exact=workouts) As stated, this only returns a single exercise when the query it generates should and does return 2 in sql. -
How to exclude formatting of text when dealing with numbers? Django
In my template I'm outputting various numbers which range in the millions. I'm using Humanize function to format the numbers. {% load humanize %} ..... {{ aircraft.maximum_range|floatformat|intcomma }} On my comparison page I have the following code which returns all of the numerical attributes. I could use |floatformat|intcomma to format the numbers but I'm also returning the title of the post also in the variable of Value. Can I do an if statement which states for the text not to be formatted? {% for value in row %} {% if forloop.counter0 == 0 %} <th>{{ value }}</th> {% else %} <td class="text-center"><strong>{{ value }}</strong></td> {% endif %} {% endfor %} By doing {{ value|floatformat|intcomma }} the title isnt included but I need it there. How do I solve this? -
How to pass user id or username in url after login form submit in django
Since i am using the default django User model, i want to display a username in the url using class based view after login form submit, to redirect to the user profile page. I have been using the following url pattern currently to login: url(r'^client/', views.IndexClientView.as_view(), name='indexClient') Now what i want to do is replace the client/ with the username/. My IndexClientView: class IndexClientView(TemplateView): template_name = 'startup/index-client.html' Login form submitted as: if user is not None: if user.is_active: login(request, user) # messages.add_message(request, messages.INFO, 'Login Successfull.') return redirect('indexClient') -
not enough values to unpack (expected 2, got 1)
I have a problem with a queryset in one view. My idea is show all users who are not registered in a program, I put here the models: models.py class UCAUser(AbstractUser): dni_cif=models.CharField( max_length=9, blank=True, verbose_name="DNI/CIF" ) class InscripcionRealizada(models.Model): formulario = models.ForeignKey(Formulario) inscrito = models.ForeignKey(UCAUser, related_name="inscripciones_realizadas") fecha_registro = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Inscripción realizada" verbose_name_plural = "Inscripciones realizadas" def __str__(self): return "{} - {} - {}".format(self.formulario.programa, self.formulario.edicion, self.inscrito) You can see UCAUser and InscripcionRealizada are connected by InscripcionRealizada.inscrito field. view.py class InscribirUsuariosListView(ListView): template_name = "inscripciones/InscribirUsuariolist.html" model = UCAUser group_required = ['Administrador'] login_url = "auth-login" def get_queryset(self): qs = super(InscribirUsuariosListView, self).get_queryset() return qs.filter(UCAUser.objects.filter(inscripciones_realizadas__formulario!=self.kwargs['formulario_id'])) def get_context_data(self, **kwargs): context = super(InscribirUsuariosListView, self).get_context_data(**kwargs) context['formulario_id'] = self.kwargs['formulario_id'] return context When I try this, I get an error: not enough values to unpack (expected 2, got 1) Any idea? Thanks a lot! -
Django: How save partial filled form state
I don't know exactly how to ask this question. The thing is that I have a main view to create new entries in a model. This model has some 1-many relations, so I added a + button to add new entries of this fields (secondary model) in case they did not exist. When I submit this new data I redirect to the previous page (main view), and if you already filled some fields in the main view, that information is lost. Can someone suggest me what the best way to deal with this would be? Thanks in advance! -
framework similar to spring sleuth in python
I have recently used spring sleuth framework in my project where all the microservices were in spring boot. I really liked the way distributed logging is being done using spring-sleuth. I would like to know if there is any similar framework available in python + Django framework. I could find opentracing framework. https://github.com/opentracing/opentracing-python any suggestions will be welcome. -
How to Un-register ( remove ) service worker from a Django login and admin pages?
I had developed an application using Django and implemented service worker on it. but when I redirect to the login and admin page, I want to remove the service worker -
Give a ModelSerializer, can I get related model fields used for QuerySet.only?
I found my drf view is too slow due to Fat SQL SELECT Clause from DB. So I want to select columns only required by bound serializer, thus I can write my view class like this: class ListRetrieveProductViewSet(UpdateNonExistentMixin, viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def get_queryset(self): return self.queryset.select_related( 'company' ).only(*self.serializer_class.get_model_field_names()) self.serializer_class.get_model_field_names() may result ['id', 'name', 'company__id', 'company__name']. How to implement get_model_field_names or is there any existing implementations? -
Restricting access via user email Django Saleor
I want to try setup a private website, where users can purchase bookings but only their own bookings can be viewed within the entire shop when logged in. Saleor seems to be the most complete ecommerce package for Python/Django. Is there a way i can block access to using categories? As in, i can create a category 'Johnson Family' and only select certain users to have access to 'Johnson Family' categories, if i approve their email to have access. Then those users would then see 'products' or 'bookings' specifically for them within the shop. -
Django select only models with different field
I have a model called Product_Variation: class Product_Variation( models.Model ): color = models.ForeignKey('Color', verbose_name="Color", on_delete=models.CASCADE, null=True, blank=True) size = models.ForeignKey('Size', verbose_name="Size", on_delete=models.CASCADE, null=True, blank=True) sku = models.CharField(verbose_name="SKU", max_length=255, null=True, blank=True) main_picture = FilerImageField(related_name="main_picture", verbose_name="Main Picture", null=True, blank=True) image_gallery = models.ManyToManyField('Media', related_name="image_gallery", verbose_name="Image Gallery", blank=True) regular_price = models.FloatField(verbose_name="Regular Price", null=True, blank=True) sale_price = models.FloatField(verbose_name="Sale Price", null=True, blank=True) stock_quantity = models.PositiveIntegerField(verbose_name="Stock Quantity", default=0, null=True, blank=True) weight = models.FloatField(verbose_name="Weight", default=0, null=True, blank=True) dimension_length = models.FloatField(verbose_name="Length", default=0, null=True, blank=True) dimension_width = models.FloatField(verbose_name="Width", default=0, null=True, blank=True) dimension_height = models.FloatField(verbose_name="Height", default=0, null=True, blank=True) barcode = models.CharField(verbose_name="Barcode", max_length=255, null=True, blank=True) priority = models.PositiveIntegerField(verbose_name="Priority", null=True, blank=True) total_view = models.PositiveIntegerField(verbose_name="Total View", default=0, null=True, blank=True) total_sales = models.PositiveIntegerField(verbose_name="Total Sales", default=0, null=True, blank=True) created = models.DateTimeField(default=now) product = models.ForeignKey('Product', verbose_name="Product that Variation belongs to", on_delete=models.CASCADE, null=True, blank=True) How do i get Product_variations that have distinct color? I am using mysql. -
Images getting rotated in Django Template
I am loading some images into a Django model. When I display these images through a Django template, portrait images are rotated. If I view these same images through Django Admin by clicking on the link they display as I would expect. This is my view to load the images: def upload_profile(request, user_id): variables = {} if request.POST: user_form = UserForm(request.POST, instance=User.objects.get(id=request.user.id)) myuser_form = MyUserForm(request.POST, request.FILES, instance=MyUser.objects.get(user__id=request.user.id)) if user_form.is_valid() and myuser_form.is_valid(): user_form.save() myuser = myuser_form.save() myuser.photo = apply_orientation(myuser.photo) myuser.save() return game_selection(request) variables['user_form'] = user_form variables['myuser_form'] = myuser_form return render(request, 'esc/profile.html', variables) And this is how I am applying the rotation: def flip_horizontal(im): return im.transpose(Image.FLIP_LEFT_RIGHT) def flip_vertical(im): return im.transpose(Image.FLIP_TOP_BOTTOM) def rotate_180(im): return im.transpose(Image.ROTATE_180) def rotate_90(im): return im.transpose(Image.ROTATE_90) def rotate_270(im): return im.transpose(Image.ROTATE_270) def transpose(im): return rotate_90(flip_horizontal(im)) def transverse(im): return rotate_90(flip_vertical(im)) orientation_funcs = [None, lambda x: x, flip_horizontal, rotate_180, flip_vertical, transpose, rotate_270, transverse, rotate_90 ] def apply_orientation(im): """ Extract the oritentation EXIF tag from the image, which should be a PIL Image instance, and if there is an orientation tag that would rotate the image, apply that rotation to the Image instance given to do an in-place rotation. :param Image im: Image instance to inspect :return: A possibly transposed image instance """ try: … -
Uncaught TypeError: $(...).Datatable is not a function. But Jquery is already loaded before I call datatable
Here's the format of one of my html file {% extends 'base.html' %} {% block main_content %} <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> DataTables Advanced Tables </div> <!-- /.panel-heading --> <div class="panel-body"> <table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th>Engine version</th> <th>CSS grade</th> </tr> </thead> <tbody> <tr class="odd gradeX"> <td>Trident</td> <td>Internet Explorer 4.0</td> <td>Win 95+</td> <td class="center">4</td> <td class="center">X</td> </tr> <tr class="even gradeC"> <td>Trident</td> <td>Internet Explorer 5.0</td> <td>Win 95+</td> <td class="center">5</td> <td class="center">C</td> </tr>d </tbody> </table> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-12 --> </div> {% endblock %} {% block javascript %} <!-- Datatable JS --> <script type="{% static 'js/jquery.dataTables.min.js' %}"></script> <script type="{% static 'js/dataTables.bootstrap.min.js' %}"></script> <script type="{% static 'js/dataTables.responsive.js' %}"></script> <script> $(document).ready(function() { $('#dataTables-example').Datatable({}) }); $(document).ready(function() { $('#dataTables-example').DataTable({ responsive: true }); }); </script> {% endblock %} Here's the javascript segment of my Base.html <!-- jQuery --> <script src="{% static 'jquery/jquery.min.js' %}"></script> <!-- Bootstrap Core JavaScript --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <!-- Metis Menu Plugin JavaScript --> <script src="{% static 'js/metisMenu.min.js' %}"></script> <!-- Custom Theme JavaScript --> <script src="{% static 'js/sb-admin-2.js' %}"></script> {% block javascript %} {% endblock %} I'm trying on replicating … -
cannot find index.js when react ES 6 app served by django
i've built a react app in ES6 and created a bundle.js and anchored it in an HTML page served by django. The app worked fine during development running on the node server, but when the page is served by django linking to the static bundle.js file, i got the following error: VM1517:1 Uncaught Error: Cannot find module "./src/index.js" note that index.js is the entry point of this react app. any help is appreciated! thanks! the webpack.config.js is below: module.exports = { entry: [ './src/index.js' ], output: { path: __dirname, publicPath: '/', filename: 'bundle.js' }, module: { loaders: [{ exclude: /node_modules/, loader: 'babel' }] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { contentBase: './' } }; -
JQuery and Django: Issues with location of the include of jQuery JavaScript libraries
I am creating a template which inherits a base template. The base template has provided block {% block main_body %} for the main body of the page, which I have to override. And the base template has included the jQuery and JavaScript libraries after this block, near the end because of performance concerns. Now in my child template, I have to build a table. The headers of this table are use case specific, so I have some if-else statements within which I define different headers of the table. Similarly the row content of the table is loaded via an ajax call. Problem: The <script> tag to make ajax call uses $(document).ready(function()...). This is all there in my child template and hence in the block {% block main_body %}. And the jQuery is included in the base template at the end of this block. Hence it's not working since the include is after. I am reluctant to move the include of jQuery and JavaScript before the {% block main_body %} because of performance concerns. Please suggest what are my options here. -
How to prevent Django from autoescaping html
I entered a "responsibility.description" via the Django Admin panel that contained an embedded <a>. When showing it in the template I want the <a> to appear as a link instead of being escaped as &lt;a&rt;. I found this advice (How to disable autoescape in django feeds?) but still doesn't seem to be working for me. I've tried marking it as "safe": {% for responsibility in software.responsibilities.all %} <li>{{ responsibility.description|safe }}</li> {% endfor %} and also turning autoescape off: {% for responsibility in software.responsibilities.all %} {% autoescape off %} <li>{{ responsibility.description|safe }}</li> {% endautoescape %} {% endfor %} Am I missing something or are there any other methods I can try? -
What can be used instead of "SubfieldBase" in django 1.11
I have done my coding in Django 1.9 then I have upgraded my Django version to 1.11, In 1.11 there is no SubfieldBase when I searched about it, It is deprecated in 1.10 and use "Field.from_db_value" instead but there is no Field.from_db_value in 1.11, what can be used for correcting this error -
How do i start a django project in Atom IDE
I have already installed all the required packages including atom-django and the package-manager. I don't know how to start a django project so that it has the .idea, migrations, settings.py and those other stuff. Is there any command i should put in the package-manager? Please help! -
(Django) Edit db.sqlite3 database on a HTML Contenteditable table using Ajax
I'm trying to create an content editable HTML table that'll update the db.sqlite3 database on keypress. The table can't have an input field in it because I also require it to be able to be filter and search using data-tables. so far I manage to retrieve the input on enter keypress but i don't know how to POST it straight to database (Presumably using AJAX) instead of JSON. Here's my code : Model.py class MyModel(models.Model): a = models.CharField(max_length=10) b = models.CharField(max_length=10) def __str__(self): return self.a form.py class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ['a', 'b'] view.py def display_table(request): context = { "table_list": MyModel.objects.all(), "title": "Table_List" } return render(request, 'tables/display.html', context) display.html <form action="" method="post" id="test_post">{% csrf_token %} <div id="debug" contenteditable data-name="custom-text">Some text you can edit.</div> <table id="myTable" class="display"> <thead> <tr> <th>A</th> <th>B</th> </tr> </thead> <tbody> {% for data in table_list %} <tr > <td contenteditable="true" data-name="a_name" id="{{data.id}}">{{data.a}}</td>{% csrf_token %} <td contenteditable="true" data-name="b_name" >{{data.b}}</td>{% csrf_token %} </tr> {% endfor %} </tbody> </table> </form> <script> document.addEventListener('keydown', function (event) { var esc = event.which == 27, nl = event.which == 13, el = event.target, data = {}; if (esc) { // restore state document.execCommand('undo'); el.blur(); } else if (nl) { // … -
TypeError at /mypath/ 'dict' object is not callable
I have defined the next form: class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label="Email Address") password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput, label="Confirm password") #password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username','email', 'password', 'password2' ] def clean_password2(self): print(self.cleaned_data) password = self.cleaned_data('password') #This is the line 21 as the message say password2 = self.cleaned_data('password2') if password != password2: raise forms.ValidationError("Password confirmation must match") return password The page is rendered ok, but, when the submit button is called, I get this error: TypeError at /mypath/ 'dict' object is not callable Request Method: POST Request URL: http://localhost:8000/mypath/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: /Users/MyUser/Documents/Projects/pfproject/pf/pf/forms.py in clean_password2, line 21 What is producing this error? -
using asyncio to do periodic task in django
I know that may sound a stupid question, but do you think it is possible to use asyncio to run a task every n seconds in django, so that the main process wouldn't be blocked? something for example that would print every 5 min in console, like: import asyncio from random import randint async def do_stuff(something, howmany): for i in range(howmany): print('We are doing {}'.format(something)) await asyncio.sleep(randint(0, 5)) if __name__ == '__main__': loop = asyncio.get_event_loop() work = [ asyncio.ensure_future(do_stuff('something', 5)), ] loop.run_until_complete(asyncio.gather(*work)) it seems that django will stop working while the loop is running. Thank you! -
django-tinymce to work on all textareas in django admin
I have been trying to get tiny mce to work for my django admin site on all textareas without having to add each field's widget. I have a lot of forms and would like this to work as "automagically" as possible. I have installed tiny mce using the "pip install django-tinymce" method. I have followed the following article and even though it does not throw any errors in firebug or developer mode I cannot see what I am doing wrong. https://blog.bixly.com/django-tinymce-in-djangos-admin-app I have followed this to a the letter with no luck at all. Any thoughts or suggestions to get this working on all textareas would be greatly appreciated. Thanks, jAC -
Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s)
A brief description of what I am trying to do is I am trying to access my 'home.html' web page (which exists on the home app) by clicking on the logo on the 'rates.html' web page (which exists on the rates app), the way I tried to achieve this is as follows. I looked at the other similar problems here and they all seem to forget to specify the namespace part on the appname\urls.py part of the code. I feel like I have done this properly specifying app_name = '[namespace]' into the urls.py. The exact error that it shows specific to my problem is: Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] the error highlights a line of html code on 'rate.html': <div id="logoholder"> <a href="**{% url 'getrate:home' %}**"><img src="{%static 'home/images/transparentWatermark.png' %}" width="40" height="40" style="margin:5px 10px"></a> </div> getrate\urls.py: from django.conf.urls import url, include from . import views app_name = 'getrate' urlpatterns = [ url(r'^$', views.ViewRate, name='rate'), url(r'^home/', include('home.urls', namespace='home')), ] home\urls.py from django.conf.urls import url, include from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.ViewHome, name='home'), ] mysite\urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = … -
How to return JSON Response correctly in joining multiple table in Django
Currently I am using Django 1.10. For example we have the models below: class ModelOne(models.Model): description = models.CharField(max_length = 50) class ModelTwo(models.Model): description = models.CharField(max_length = 50) m1 = models.ForeignKey( ModelOne) class ModelThree(models.Model): description = models.CharField(max_length = 50) m2 = models.ForeignKey(ModelTwo) Everytime a request is made then a JSON response is return using the code below: from app.models import * from django.http import HttpRequest,JsonResponse def ViewThatReceiveRequest(request): qs = list(ModelThree.objects.filter(description__icontains='beauty').select_related('m2__m1) data = [] for key in qs: temp_obj = {} # if necessary I will convert the values before equating temp_obj['desc3'] = key.description temp_obj['desc2'] = key.m2.description temp_obj['desc1'] = key.m2.m1.description data.append(temp_obj) return JsonResponse( {'message' : 'success', 'qs' : data }, safe = False) Note: - I am using Django as my back-end and ReactJs for my front-end so I only need JSON Response My question, - Do I need to do these for every views that receive request? - Do we have other way to solve these simpler?