Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Matplotlib's NavigationToolbar with Django
Is there any way to use NavigationToolbar (such like in tkinter) to generate interactive charts in django or the only sensible choice is to use chart.js? -
Django crispy form CrispyError for DetailView with added model
I wanted to have a form that shows (retrieves) user information in the crispy form style, based on two models using a DetailView: class DashboardView(DetailView): model = User form_class = DashboardForm template_name = 'dashboard.html' def get_context_data(self, **kwargs): context = super(DashboardView, self).get_context_data(**kwargs) pk = self.kwargs['pk'] user = get_object_or_404(User, pk=pk) context.update({'user': user}) profiles = Profile.objects.filter(owner=user) if profiles.count == 1: context.update({'profile': profiles[0]}) else: # TODO - error return context With the form defined as: class DashboardForm(forms.Form): def __init__(self, *args, **kwargs): super(DashboardForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( '', 'user.username', 'profile.code' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) And code in the template as: {% load crispy_forms_tags %} ... <form> {{ user.username|as_crispy_field }} {{ profile.code|as_crispy_field }} <input type="submit" value="Submit" class="btn btn-success"> </form> But this gives an error: CrispyError at /dashboard/1/ |as_crispy_field got passed an invalid or inexistent field I am not sure that this is the right way to combine two related records on a crispy read only / retrieve style form. -
'ModuleNotFoundError: No module named 'MySQLdb' In Django
creating my first module in django, I am using mac Tried steps: 1.installed python 3.6.+ version, 2.cloned git project 3.setup local env, to create a module, trying with command env=dev python3 manage.py startapp supriya_module_inflow; getting error in console : Environment Selected :dev Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 24, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv)...... ... raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' -
What kind of proficiency is required for a junior developer position? [on hold]
I am interested in what would be considered as a good complexity for a project that would be used at an interview for a junior/entry level developer position. For reference I mainly use React/Flask or React/Django, if that makes a difference I am interested in what would be expected. Would a blog site with users be too sinplistic? Something like yelp to complex? Do I need an app with multiple databases using multiple api's? I am wondering how to know if I am ready for a junior position. (Obviously I can apply for jobs and find out at technical interviews etc, but I was more asking how could I know on my own) -
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail".
I am getting the common DRF hyperlinked model-detail error, and I'd like to understand what it means so I stop getting it. The view is as such: import json import time from django.http import JsonResponse from django.contrib.auth.models import User from rest_framework import serializers, viewsets from utils.general import unpack_request_body from .models import Restaurant #------------------------------------------------------------------------------------ class RestaurantSerializer(serializers.HyperlinkedModelSerializer): # answered by bovenson: # https://stackoverflow.com/questions/20550598/django-rest-framework-could-not-resolve-url-for-hyperlinked-relationship-using # what just happened here? idk what HyperlinkedIdentityField does url = serializers.HyperlinkedIdentityField(view_name="restaurant:restaurant-detail") class Meta: model = Restaurant fields = '__all__' class RestaurantViewSet(viewsets.ModelViewSet): queryset = Restaurant.objects.all() serializer_class = RestaurantSerializer #------------------------------------------------------------------------------------ def find_restaurant_owned_by_a_username(username): try: user = User.objects.get(username=username) except: return None restaurants_owned = user.restaurants.all() if restaurants_owned: return restaurants_owned[0] else: return None def restaurants_owned_by_this_username(request): """ for now only returns one restaurant """ # TODO: will need to support multiple restaurants owned by one user in the future if request.method == "POST": body = unpack_request_body(request) username = body['username'] restaurant_owned = find_restaurant_owned_by_a_username(username) if restaurant_owned: serializer = RestaurantSerializer(restaurant_owned, context={'request': request}) return JsonResponse({'result': serializer.data}) else: return JsonResponse({'result': None}) else: error_message = "This method only responds to POST" print(error_message) return JsonResponse({'error': error_message}) urls: urlpatterns = [ ... url(r'^api/restaurants-owned', csrf_exempt(views.restaurants_owned_by_this_username), name="restaurants-owned"), ] models.py: from django.contrib.auth.models import User class Restaurant(models.Model): name = models.CharField(max_length=250, null=False, blank=False) phone = models.CharField(max_length=12) owner = … -
Object of type 'Response' has no len() in DRF
ive combined two models. one model's field is annotated to another model's so they can merge. However, when I try to return the data, I get TypeError: object of type 'Response' has no len(). I've followed several examples on stackoverflow and it doesnt seem to be working. Here's what I have: class ExploreAPIView(generics.ListAPIView): def get_queryset(self): merged_queryset = Place.get_queryset(self.request.user) usr_pks = [u.pk for u in merged_queryset] queryset = Place.objects.filter(pk__in=usr_pks) serialUser = UserSerializer( User.objects.annotate(time=Extract('date_joined','epoch')), many=True).data[:] serialPlace = PlacesSerializer(queryset, many=True).data[:] chained_list = sorted(serialPlace +serialUser, key=lambda x: x.get('time')) return Response(chained_list) I dont understand why it returns no len() when it returns items if i print out the chained_list -
Access Django db by another python progra
I have a Django project working fine (deployed in nginx), using postgresql database. I have to access ORM database from another python program. I'm doing this with this code: if os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebSite.settings'): import django django.setup() from WebSite.operation.models import Registers, OperationMode from WebSite.trend.models import TrendRegister from django.utils import timezone else: raise sys.exit(1) When i execute the program with default user (pi is my default user), works fine, but if a execute the program in root mode, the following erro occurrs: "password authentication failed for user root" I must have to execute this other program in root mode. How can i resolve this? -
Push notifications in django
I want to use fcm in django with firebase, but in the device model there are: Device ID , Registration Token and Device Type, but I dont know how to get this data. Thanks. -
How I can retrieve exact field from db table Django
someadwebsite Lets assume, that kind of site making now and I could print all object in same blocks from one database table with for loop but I don't have an idea how can I dynamicly request only exact field per link when follow the link , I need to print data on exact field Hope I understandably wrote Please help me! -
Embed opencv (jpg) image into html5 canvas in an editable form
I'm using python and opencv to segment an image. I read the image using opencv, perform the color clustering operations, and then output the image with cv2.imshow. What I want to do (and I have no idea how), is to embed the resulting segmented image into a html5 canvas (represent it like a svg or a similar "editable" format), so users can change the colors of each segmented region or hide some regions (operations are based on colors - I want to be able to dynamically change the colors of segmented regions, not just upload a "plain" jpg image in a html5 canvas). I'm using Django for implementing the web application. How can I achieve this? Note: if the question is offtopic, please kindly tell me where it would be suitable to post it? -
Using modelformset_factory and access attributes of an object
I have some Containers and they have a number of Boxes I want to edit. So, naturally, I use modelformset_factory. It works very good: container = get_object_or_404(Container, id=container_id) BoxFormSet = modelformset_factory(Box, fields=('a', 'b', 'c')) formset = BoxFormSet(queryset=container.box_set.all()) In my template I iterate over formset to show the boxes I want to modify. This works very well and I can edit the attributes a, b and c of each Box. But each box has also a label. I want to access the value to show it in the label but it should not be editable, like an input-field. I just need the value. How can I achieve that? -
DRF SessionAuthentication login page insecurity?
In the Django Rest Framework SessionAuthentication documentation it says that Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. Why should I use Django's standard login views on login pages? If I would like to make my own login views (for example, in React, Vue or Angular), what I should take into account to make the view "as secure as the Django's standard login view"? -
get django-cms plugin instance from another page
I have a django-cms page and am still trying to figure out best practices for it. I have the following problem: I have written a projects page, with an plugin ProjectsOverview, which can hold plugins of the type Project. Every Project has a 'tags' list to it, in order to filter the projects. this is done in the ProjectsOverview plugin: def unique_tags(self): split_tags = map(lambda project: project.tags.split(","), self.child_plugin_instances) tags = [item.strip() for sublist in split_tags for item in sublist] return list(set(tags)) by clicking on a project, the visitor is redirected to a new page, set via a PageField in the Project plugin. Now what I'd like to do is reference the different categories in the project page to easily go back to the projects overview. I figured out I can get hold of the plugins by doing this: {% for placeholder in current_page.parent.get_placeholders %} {% for plugin in placeholder.get_plugins_list %} {{plugin}} {% endfor %} {% endfor %} I do not know how to get a plugin instance (something like plugin.instance.unique_tags) from there. Maybe there is someone able to help? Thank you very much! -
django-celery and rabbitmq, scheduled task not executed
I have the following setup: django 1.8.13 celery 3.1.17 RabbitMQ 3.6.12 My relevant settings.py snippet: CELERY_WORKER_DIRECT = True CELERYD_TASK_TIME_LIMIT = 7200 CELERYD_TASK_SOFT_TIME_LIMIT = 7000 CELERY_ROUTES = { 'vdr.tasks.process_uploads': {'exchange': 'C.dq', 'routing_key': 'celery@node1.mailin.msp'}, 'vdr.tasks.send_html_mail_async': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'vdr.tasks.handle_file': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'queued_storage.tasks.TransferAndDelete': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'vdr.tasks.TransferAndDeleteNonLocked': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, 'queued_storage.tasks.Transfer': {'exchange': 'C.dq', 'routing_key': 'celery@node1.worker.msp'}, } CELERYBEAT_SCHEDULE = { 'process-uploads-every-minute': { 'task': 'vdr.tasks.process_uploads', 'schedule': timedelta(seconds=60), }, } BROKER_URL = 'amqp://%(user)s:%(password)s@%(host)s:%(port)s//' % {"host": os.environ.get("RABBITMQ_PORT_5672_TCP_ADDR", "rabbitmq"), "port": os.environ.get("RABBITMQ_PORT_5672_TCP_PORT", 5672), "user": os.environ.get("RABBITMQ_ENV_RABBITMQ_DEFAULT_USER", "user"), "password": os.environ.get("RABBITMQ_ENV_RABBITMQ_DEFAULT_PASS", "password")} CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True I can see in the celery beat log that the tasks gets sent periodically, as expected: [2017-11-25 14:56:57,759: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2017-11-25 14:56:59,775: DEBUG/MainProcess] Open OK! [2017-11-25 14:56:59,776: INFO/MainProcess] Scheduler: Sending due task process-uploads-every-minute (vdr.tasks.process_uploads) [2017-11-25 14:56:59,779: DEBUG/MainProcess] using channel_id: 1 [2017-11-25 14:56:59,780: DEBUG/MainProcess] Channel open [2017-11-25 14:56:59,781: DEBUG/MainProcess] beat: Synchronizing schedule... [2017-11-25 14:56:59,782: DEBUG/MainProcess] vdr.tasks.process_uploads sent. id->cdfd9873-dc27-4e3b-a226-3a367dc4e05f [2017-11-25 14:56:59,782: DEBUG/MainProcess] beat: Waking up in 59.99 seconds. The worker that is meant to execute the task is also up and running: [2017-11-25 15:22:44,826: INFO/MainProcess] Connected to amqp://user:**@172.17.0.2:5672// [2017-11-25 15:22:44,846: INFO/MainProcess] mingle: searching for neighbors [2017-11-25 15:22:45,869: … -
Controlling permission based views in Dojo on hash change
I have a Dojo website in which different widgets are loaded on hash change. I am trying to restrict user access to certain widgets based on permissions. I am able to achieve the same using Django template where I have access to the request object and I can render or not render views based on that. I am wondering if this could somehow be done on client side in dojo. The simplest way I could think of is to make an xhr call before the hash change handler in javascript and show 403, permission denied page based on response. Is there a better way of achieving the same. Code Sample for my current hash change handler : switch (hash) { case "home": { var Starter= dojo.require("widgets.Starter"); var starter= new Starter(); domConstruct.place(starter.domNode, contentDivId); starter.placeAt(contentDivId); starter.startup(); break; } case "form-mapping": { var FormMapping = dojo.require("widgets.assignForms.FormMappingHome"); var formMapping = new FormMapping(); domConstruct.place(formMapping.domNode, contentDivId); formMapping.placeAt(contentDivId); formMapping.startup(); break; } } -
Many duplicate queries when using image tag in Wagtail
I'm using Wagtail v1.13.1 for my website project. I'm trying to optimize db queries... models.py class ProductPage(Page): ... main_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', blank=True, null=True ) class ProductIndexPage(Page): ... def get_context(self, request, *args, **kwargs): context = super(ProductsIndexPage, self).get_context(request) all_products = ProductPage.objects\ .prefetch_related('main_image__renditions')\ .live()\ .public()\ .descendant_of(self)\ .order_by('-first_published_at') paginator = Paginator(all_products, 10) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context['products'] = products return context product_index_page.html I'm outputting product card in a for loop. Each product card has this tag: {% image product.main_image fill-600x300 %} But still getting a separate call to db for each image. Models are connected in this way: ProductPage --fk--> wagtailimages.Image <--fk-- wagtailimages.Rendition The question is: What is the proper way to prefetch renditions and eliminate duplicate db queries? -
Could not resolve URL for hyperlinked relationship using view name "blog-detail"
I am trying to work with dynamic url in foreign key relationship into django rest framework url.py router = routers.DefaultRouter() router.register(r'(?P<topic_name>\w+)', views.BlogViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] models.py class Blog(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=100) class Topic(models.Model): name = models.CharField(max_length=100) views.py class BlogsViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = Serializerblog lookup_field = 'topic' def list(self, request, *args, **kwargs): response = super(BlogViewSet,self).list(request,*args,**kwargs) return Response( response.data) When I tried to call url getting following error. ImproperlyConfigured at /test/ Could not resolve URL for hyperlinked relationship using view name "blog-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://localhost:8000/test/ Django Version: 1.11 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "blog-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Exception Location: /home/TestProjeect/env/lib/python3.4/site-packages/rest_framework/relations.py in to_representation, line 386 Python Executable: /home/TestProjeect/env/bin/python Python Version: 3.4.3 Python Path: ['/home/', '/home/TestProjeect/env/lib/python3.4', '/home/TestProjeect/env/lib/python3.4/plat-x86_64-linux-gnu', '/home/TestProjeect/env/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/home/TestProjeect/env/lib/python3.4/site-packages'] Server time: Sat, 25 Nov 2017 14:57:16 +0000 -
Invalid Syntax Error in Django
I'm facing invalid syntax error in urls.py ] ^ SyntaxError: invalid syntax Code: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='home.html'), url(r'^about/$', TemplateView.as_view(template_name='about.html')), url(r'^contact/$', TemplateView.as_view(template_name='contact.html')), ] -
django upload to image model with foreign key to user
I'm using Django's Extended User Profile and instead of having many image fields I want to make a new Images class in my models that I can upload many images which automatically get assigned to the right user. Then the user can view and edit all their images. I'm basically stuck on the last part (view and edit). My app is called ve models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) ... etc class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) forms.py class ImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Images fields = ( 'image', ) 1. Edit Image(s) This setup, uploads image (in admin) but doesn't assign the user. Another problem is I can only upload/edit 1 image. views.py @login_required @transaction.atomic def edit_images(request): if request.method == 'POST': images_form = ImagesForm(request.POST, request.FILES) if images_form.is_valid(): images_form.save() return redirect('ve:index_account') else: pass else: images_form = ImagesForm(request.POST, request.FILES) return render(request, 've/cp/edit_images_account.html', { 'images_form': images_form, }) edit_images_account.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ images_form.as_p }} <button type="submit">Upload</button> </form> 2. View Image(s) views.py @login_required def index_account(request): args = {'user': request.user} return render(request, 've/cp/index_account.html', args) index_account.html <p><a href="{% url 've:edit_images' %}">Edit your images</a></p> {% if user.images.images %} … -
I want add a about page using django
the about page is like about me ,about the website... I hope the about page not static.It can be register and easy edit through django.admin. I had try to add a model named About , and the views.py is like.. that's a stupid method , and i don't know how to deal with pk when it changes.Do you have a good method? enter image description here -
django: How to get objects from a ContentType instance
I want to get a queryset of objects from a ContentType instance and then be able to filter them. From the doc, it is possible to get() an object using: ct.get_object_for_this_type(**kwargs) How can I make a similar filter() for that instance? -
Django how form class’s fields map to HTML form <input> elements
In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form elements. (A ModelForm maps a model class’s fields to HTML form elements via a Form; so how the following are translated from a model to html input. I am using a ModelForm. models.CharField(max_length=200,unique=True,null=False) models.SlugField(unique=True) models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM) models.DateTimeField(auto_now=True, auto_now_add=False) models.DecimalField() like type, name, label etc. Is there any list of mappings. -
Tic tac toe game Type error None python
Hi I am trying to create a tic tac toe game with the board values ["0", "1", "2", "3", "4", "5", "6", "7", "8"] coming from the front end and going back to the back end and then all this values being returned to the front end with a X from the user or a 0 from the random maths. The first time I input a value, it works, but the second time I input a value I get this error. if board[cell1] == char and board[cell2] == char and board[cell3] == char: TypeError: 'NoneType' object is not subscriptable The error sounds like that the board list disappears but when I print the board on my codes it shows that the board is there. def tic(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) input_str = body['value'] input = int(input_str) board = body['x'] print(board) # Here I see the board is always there if board[input] != 'x' and board[input] != 'o': board[input] = 'x' if check_match(board,'x') == True: winner = 'x' return JsonResponse({'input': input, 'board': board, 'winner': winner}) board = opponent_fun(board) if check_match(board,'o') == True: winner = 'o' return JsonResponse({'input': input, 'board': board, 'winner': winner}) else: winner = … -
How to put Array data in CharField(validators=[validate_comma_separated_integer_list])?
I chose CharField(validators=...) for alternative to CommaSeparatedInteger field to store array into the field. The Http request has selectedColorsIds body field and I want to put the data into color field of PostDetail model ... "selectedColorIds": Array [ 112, 110, ], ... models.py from django.core.validators import validate_comma_separated_integer_list class PostDetail(models.Model): ... color = models.CharField(validators=[validate_comma_separated_integer_list], max_length=30, blank=True, null=True) ... views.py :> But I'm getting this error when I try to put the array into the field. AttributeError: 'tuple' object has no attribute 'color' error color = self.request.data.get('selectedColorIds') # [112, 110] detail_instance = PostDetail.objects.get_or_create(post=post_instance) detail_instance.color = color <<- error here Why am I getting this error and how can I store array in the Django model? -
Django with apache2 ,only sometimes the server refuse the connection
I have two django projects in my server. I use virtualhost to handle that, i enabled two sites in apache2 configuration: the first is old_cheese.conf using \VirtualHost *:80: ServerName cheese ServerAdmin webmaster@localhost DocumentRoot /home/little_baker/cheese Alias /static/ /home/little_baker/cheese/static/ <Directory /home/little_baker/cheese/static> Require all granted </Directory> WSGIScriptAlias / /home/little_baker/cheese/cheese/wsgi.py <Directory /home/little_baker/cheese> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined the second is new_cheese.conf using \VirtualHost *:8000: ServerName new_cheese ServerAdmin webmaster@localhost DocumentRoot /home/little_baker/new_cheese/ Alias /static/ /home/little_baker/new_cheese/static/ WSGIScriptAlias / /home/little_baker/new_cheese/new_cheese/wsgi.py <Directory '/home/little_baker/new_cheese/static/'> Require all granted </Directory> <Directory /home/little_baker/new_cheese> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined It works most of times, in log there is no exception raised. But something unreasonable happen sometimes: If i open the old cheese page, and exception will be raised in error.log: ImportError: No module named 'new_cheese' If i open new cheese page : ImportError: No module named 'cheese' It seems like these two project try to import each other. This exception is not often raised. Most of time I can reach my page. I don't know the reason why. Is something wrong with apache2 or my project