Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the field validation (fields level and object level both) in the serializer not work?
I need to implement a limitation for creating an instance of the model so that if the Vendor model has the status active=True, then a validation error will appear. models.py class Vendor(models.Model): active = models.BooleanField(default=False) ... class VendorContacts(models.Model): vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True) ..... serializer.py class VendorContactCreateSerializer(serializers.ModelSerializer): email = serializers.CharField(validators=[RegexValidator(regex=r'[^@]+@[^\.]+\..+', message='Enter valid email address')]) vendor = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = VendorContacts fields = ('vendor', 'contact_name', 'phone', 'email', 'primary', ) def create(self, validated_data): phone = validated_data.pop('phone', None) vendor = validated_data.pop('vendor', None) result = re.sub('[^0-9]', '', phone) contact = VendorContacts.objects.create(vendor=vendor, phone=result, **validated_data) return contact def validate_email(self, value): print('Start validation') exist_contact = VendorContacts.objects.filter(email=value) if exist_contact: vc = get_object_or_404(VendorContacts, email=value) v = vc.vendor if v.active: raise serializers.ValidationError('Email {} already exists'.format(value)) return value But validation doesn't work. Also the variant with validation at the object level def validation() does not work: -
How to handle files in Django Rest Framework?
I'm building an Angular + Django project, and I need to add some files to it, the idea is this model Ticket should receive some files, like imgs or pdf ... Wich Field should I use in the model? FileField? class Ticket (models.Model): titulo = models.CharField(max_length=100, blank=True) estagio = models.ForeignKey( Estagio, related_name='tickets', on_delete=models.CASCADE, null=True) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True) org = models.ForeignKey(Organizacao, on_delete=models.CASCADE, null=True) produto = models.ManyToManyField(Produto) valorestimado = models.IntegerField(null=True) termometro = models.CharField(max_length=100, null=True, blank=True) vendedor = models.ForeignKey( Vendedor, on_delete=models.CASCADE, null=True) vendedorext = models.ManyToManyField( VendedorExt, related_name='leads', blank=True) obs = models.ManyToManyField(Obs, related_name='tickets') status = models.CharField(max_length=155, blank=True, default='Aberto') mtvperd = models.CharField(max_length=155, null=True, blank=True) cmtperd = models.CharField(max_length=155, null=True, blank=True) created = models.ForeignKey(Created, on_delete=models.CASCADE, null=True) updated = models.ManyToManyField(Updated) def __str__(self): return str(self.titulo) And How can I handle this img in the view? : class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all().order_by('-id') serializer_class = TicketSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def create(self, request): data = request.data print(data['titulo']) print(request.user) print(request.headers) c = Created() c.user = request.user c.save() V = Vendedor.objects.get(id=int(data['vendedor'])) print(V) T = Ticket() T.titulo = data['titulo'] T.estagio = Estagio.objects.get(id=int(data['estagio'])) T.cliente = Cliente.objects.get(id=int(data['cliente'])) T.org = Organizacao.objects.get(id=int(data['org'])) T.valorestimado = int(data['valorestimado']) T.termometro = data['termometro'] T.vendedor = V T.status = 'Aberto' T.created = c T.save() try: if data['obs'].length >= 1: for … -
How to display Django DayArchiveView by clicking on a Calendar cell?
I have a calendar that tracks orders. All calendar cells are interactive. My goal is to display a panel with orders for a specific day that user has clicked on a calendar. I have created the DayArchiveView: class OrderDayArchiveView(DayArchiveView): queryset = Order.objects.all() date_field = "create_date" allow_future = True The template: {% extends 'ocal/base.html' %} {% block content %} <h1>Orders for {{ day }}</h1> <ul> {% for order in object_list %} <li> <a href="/ocal/{{ order.id }}/detail">Order {{ order.id }} </a> {{ order.status_str }} </li> {% endfor %} </ul> {% endblock %} And the url: path('date/<int:year>/<str:month>/<int:day>/', OrderDayArchiveView.as_view(), name="order_archive_day"), In utils.py I have created Calendar class with the function formatday where I added a href attribute on td: def formatday(self, day, events): events_per_day = events.filter(create_date__day=day) d = '' for event in events_per_day: d += f'<li> <a href ="{event.status}" style ="background-color: #FFDCDC;">{event.status}</a>' if day != 0: return f"<td><a href=''><span class='date'>{day}</span><ul>{d}</ul></a></td>" return '<td></td>' My idea was to add appropriate value to href attribute in utils.py. The value should display the OrderDayArchiveView based on the cell that was clicked, but I don't know what value should that be. Also, I believe it's important to mention that this view should be displayed on the same page where … -
Django Custom Manager for Reverse Foreignkey Lookup
I'm using a custom Model-Manager for Soft-Deletion and want to do a reverse Foreignkey lookup. The Manager: class SoftDeletionQuerySet(QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now()) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete() def alive(self): return self.filter(deleted_at=None) def dead(self): return self.exclude(deleted_at=None) class SoftDeletionManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): self.status = kwargs.pop("status", "all") super(SoftDeletionManager, self).__init__(*args, **kwargs) def get_queryset(self): if self.status == "alive": return SoftDeletionQuerySet(self.model).filter(deleted_at=None) elif self.status == "dead": return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) else: return SoftDeletionQuerySet(self.model) def hard_delete(self): return self.get_queryset().hard_delete() class SoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager(status="alive") dead_objects = SoftDeletionManager(status="dead") all_objects = SoftDeletionManager() class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def hard_delete(self): super(SoftDeletionModel, self).delete() Used for a Model: class Sowi(SoftDeletionModel): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Now, for a given user, i want to get his user.sowi_set, but only those SoWi's which are 'alive'. The "normal" user.sowi_set also returns the Elements which are dead, i.e. which have a deleted_at value != None. How do I only get the alive objects? Thanks in Advance! -
What is the best / easiest way to integrate the Jupyter Notebook editor to a 3rd party website?
My friend and I are working on our pet project, a website for hosting algorithms that test sociological hypotheses and accumulate knowledge on sociology. We envision our site to be similar to Wikipedia with one exception: we want to present all the articles on the site in the form of Jupyter Notebooks. Our site engine is based on Django. Could you please tell me what is the best / easiest way to add the Jupyter Notebook editor to a 3rd party website? We understand that Jyputer runs on Tornado, that it is single-user, and we need to write a lot of the server logic. Our current understanding is to use the Jyputer Client to work with IPython, take the UI from Jupyter Lab, and write the server handlers ourselves. Could you please tell me if this is the right approach? What should we keep in mind? Is there an easier way to achieve our goal (for example, base our work on Jupyter Server instead of Jupyter Client)? We would like to focus on developing our site and keep compatibility with Jupyter as much as possible so that we can update / commit a change to the Jupyter project if it … -
Django 'object is not iterable' error when using get() method
get() method is not working in Django, I have a model BlogPost, when I try to fetch data from that model using get() method it shows Error : 'BlogPost' object is not iterable def blog_post_detail(request, slug): query = BlogPost.objects.get(slug=slug) template_name = 'blog/post.html' context = {'query': query} return render(request, template_name, context) But the same thing works using filter() method def blog_post_detail(request, slug): query = BlogPost.objects.filter(slug=slug) template_name = 'blog/post.html' context = {'query': query,} return render(request, template_name, context) Note: I have only one post in BlogPost -
PermissionError: [Errno 13] Permission denied - Python/Django Locallibrary
So I'm following this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page Using this code in my urls.py: urlpatterns += [ path('catalog/', include('catalog.urls')), ] Throws me the error PermissionError: [Errno 13] Permission denied: '/home/jakoubu/django_projects/locallibrary/catalog/urls.py' Anyone knows what's up? I've searched the entire internet for answers... -
Database creation failing during django testing
I have a functional Django project with a functional database. When I try to run tests on this project, I get this error during database creation: django.db.utils.InternalError: (1553, "Cannot drop index 'One response per question per level': needed in a foreign key constraint") I had a unique_together constraint in one of the tables which I later removed. This line 'One response per question per level' is related to that unique_together constraint and is present in two migration files - first time during the creation of the table and second time during the removal. When I run the tests, it is throwing this error and the database is not getting created. How can I solve this problem? -
Django Model with non-unique names
I'm trying to create a simple kanban style board for my task manager app in Django 3.0.3. I've already written the code for projects and tasks, but I'm having trouble figuring out the best way to create the models for the kanban boards. I currently have two models, but can I do this in one for simplicity? My basic requirement is that every project can have its own board, and each board will have multiple panels. Here is an example: Board: Development Backlog Started Development etc... Board: Operations Requested Working Pending etc... With only one model, I'm not sure if this will have the flexibility I need to fully design it. But having multiple models may be too cumbersome to manage for the ultimate user. Here are my current models: class Board(models.Model): """ Defines Kanban boards """ name = models.CharField(max_length=25) slug = models.SlugField(default="") project = models.ForeignKey(Project, on_delete=models.CASCADE) tags = TaggableManager(blank=True) def __str__(self): board_name = self.project.name + ":" + self.name return board_name class BoardPanel(models.Model): """ Defines panels in project board """ title = models.CharField(max_length=30) slug = models.SlugField(default="") board = models.ForeignKey(Board, on_delete=models.CASCADE) tasks = models.ManyToManyField(Task) def __str__(self): panel_name = self.board.name + ":" + self.title return panel_name -
How to use coreapi to create custom API schema with reponse stauts?
I have written an API using DRF's APIView class. I don't have models and directly call another API end from my API. I want to document my API, hence using Django rest swagger. Its recent version does not support YAML docstring. So I have written manual coreapi.Document schema for generating parameters. I have taken reference from this answer .But i am struggling to add response status code to it, otherwise, it is rendering empty response section with by default 201 code. Is there any way i can add custom response status? -
Static file 404 error when DEBUG=False in django
I made django project for localhost, it fetch the static files ex) http://127.0.0.1:8000/static/myapp/test.img It works well when DEBUG=True in setting.py Now I changed to DEBUG=False This http://127.0.0.1:8000/static/myapp/test.img returns net::ERR_ABORTED 404 (Not Found) DEBUG = True if DEBUG: ALLOWED_HOSTS=['*'] else: ALLOWED_HOSTS=['*'] -
Django DetailView Two Forms Only One Works
I am struggling to debug this as it doesn't show an error when I submit the form that doesn't work, I can't figure out why it isn't working any help is appreciated... class ProfileDetailView(FormMixin, DetailView): template_name = 'users/profile_detail.html' model = Profile form_class = ReviewForm other_form = ProfileContactForm success_url = '/' def get(self, request, *args, **kwargs): self.other_form = ProfileContactForm return super(ProfileDetailView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) profile = self.object reviews = Review.objects.filter(user_id=self.kwargs['pk']).order_by('-review_date') imgs = ProfileImages.objects.filter(profile_id=self.kwargs['pk']) context['reviews'] = reviews context['imgs'] = imgs context['profile'] = profile context['other_form'] = self.other_form return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() other_form = self.other_form() if form.is_valid(): Review = form.save(commit=False) Review.user = self.object Review.reviewer = request.user Review.save() return self.form_valid(form) if other_form.is_valid(): subject = other_form.cleaned_data['date'] message = other_form.cleaned_data['service'] your_email = request.user.email try: send_mail(subject, message, your_email, ['anthonya1@live.co.uk']) except BadHeaderError: return HttpResponse('Invalid header found.') else: return self.form_invalid(form) Form_class (ReviewForm) is working fine... Other_form is the one I'm having issues with, I just need it to go through the send mail code but it doesn't seem to be reaching it as it doesn't send mail and my server doesn't show an attempt to send mail... -
Django internationalization not working for REST API custon JSON response in view.py
In my django project, I am using internationalization. It's working fine for REST framework viewsets like ModelViewSet but fails for function based JSON response views. Here are code: #settings.py from django.utils.translation import ugettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('tr', _('Turkish')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] Views.py includes: #views.py from django.utils.translation import ugettext as _, get_language from rest_framework.response import Response from django.views.decorators.csrf import csrf_exempt from rest_framework.permissions import AllowAny from rest_framework.decorators import api_view, permission_classes @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def LoginwithUsernameApi(request): username = request.data.get("username") password = request.data.get("password") if username is None: return Response({'detail': _('Please provide username.')}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': _('Invalid username or password.')}, status=HTTP_404_NOT_FOUND) serializer = UserSerializer(user) return Response(serializer.data, status=HTTP_200_OK) In request header sending Accept-Language:tr , Also print(get_language()) returns tr as output. django.po also contains message: #django.po #: registration/views.py:145 registration/views.py:181 #: registration/views.py:199 registration/views.py:252 msgid "Please provide all required data." msgstr "" -
Using pip on OSX Mojave forces me to install recently release python packages
So I recently updated an old macbook pro up to Mojave (osx 10.14) and decided to use it as a side laptop for development. Using python 3.7, I created a virtualenv like so: python3.7 -m venv myvirtualenv Pulled the repo I am working on, enabled my virtualenv and started installing requirements: billiard==3.6.1.0 boto3==1.9.248 botocore==1.12.248 celery==4.3.0 certifi==2018.8.24 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.2 django-appconf==1.0.3 django-autoslug==1.9.6 django-celery==3.3.1 django-cors-headers==3.1.0 django-heroku==0.3.1 django-mailing==0.1.3 django-storages==1.7.2 django-otp==0.5.0 django-redis-cache==2.1.0 django-templated-mail==1.1.1 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 djoser==1.7.0 docutils==0.15.2 idna==2.7 importlib-metadata==0.23 jmespath==0.9.4 kombu==4.6.5 more-itertools==7.2.0 oauthlib==2.1.0 Pillow==6.2.0 psycopg2==2.8.3 PyJWT==1.6.4 python-dateutil==2.8.0 python-http-client==3.2.1 python3-openid==3.1.0 pytz==2018.5 redis==3.3.8 requests==2.19.1 requests-oauthlib==1.0.0 rest-social-auth==1.4.0 s3transfer==0.2.1 sendgrid==6.1.0 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 sqlparse==0.3.0 urllib3==1.23 vine==1.3.0 gunicorn==19.9.0 whitenoise==4.1.4 zipp==0.6.0 django-celery-beat==1.5.0 Thing is, pip refuses to install this versions and force me to use updated packages. For example, I cant install Django 2.2.12 (only 3.0.5 and onwards): pip install django==2.2.12 Looking in indexes: https://pypi.python.org/pypi/ Collecting django==2.2.12 ERROR: Could not find a version that satisfies the requirement django==2.2.12 **(from versions: 3.0.5)** ERROR: No matching distribution found for django==2.2.12 Same for pretty much all the packages on my requirements. Ive tested with several python versions (from 3.4 to 3.8) and several pip versiones (from 10 to 20, downloading the get-pi.py script and running it). I am pretty sure I am … -
Django Rest Framework throws IntegrityError. null value in column "creator_id" violates not-null constraint
Django Rest Framework keeps throwing an integrity error at /posts/ with the message: null value in column "creator_id" violates not-null constraint. Not entirely sure what is causing this issue. From the admin panel, I can create a post without an issue. Here's my Post Model. the User is a foreign key: class Post(models.Model): """Post object""" creator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False, blank=False) content = models.TextField(blank=True, null=True) audio_file = models.FileField( null=False, blank=False, upload_to='audio_directory', validators=[validate_file_extension, validate_file_size] ) cover_image = models.ImageField( upload_to='images/post_covers', default='images/defaults/default_cover.png', blank=False, null=False ) tags = models.ManyToManyField(Tag, blank=True) duration = models.CharField( max_length=6, blank=True, default=0, help_text='Length of post in minutes' ) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) featured = models.BooleanField(u'Featured', default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() sorted_objects = PostQuerySet.as_manager() class Meta: verbose_name = _('post') verbose_name_plural = _('post') ordering = ('-featured', '-created_at',) def __str__(self): return self.title @property def is_featured(self): return self.featured Here's thePost view uses ModelViewSet as shown in the code below: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer search_fields = (['title', 'creator', 'category']) def get_queryset(self): sorting = self.request.query_params.get('sorting', None) if sorting == 'newest': return Post.sorted_objects.newest() if sorting == 'trending': return Post.sorted_objects.likes_last_week() return Post.sorted_objects.likes() def get_permissions(self): return (permissions.IsAuthenticated(),) @method_decorator(cache_page(60)) def dispatch(self, *args, **kwargs): return super(PostViewSet, self).dispatch(*args, **kwargs) @action(methods=['post'], permission_classes=[permissions.IsAuthenticated], detail=True) … -
hosting Django on Apache
I'm following a tutorial trying to host Django on apache server, now as I finally installed mod_wsgi using cmd, I try to use the command: mod_wsgi-express module-config now i get another bugging error - which is: "syntaxError: Unicode error unicodeescape codec can’t decode bytes in position 2-4: truncated\xXX escape" I'm looking for help! thanks, -
create a publish file in django like that asp.net core
I am a beginner to Django, currently, I have developed a simple Django project with postgres database and want to create a publish file like of Asp.net core project publish file, how can I create it, or can't we create. I want to host my django project in iis like that of asp.net core project -
A for loop works in Python but doest work in Django
I need to parse h2 tags from the site. I use BeautifulSoup Here is the Views.py part. I search for all the H2 tags h2_all = soup.find_all('h2') h2_num = len(h2_all) And than pass the in the context: 'h2_all':h2_all, 'h2_num':h2_num, In the template part. When I try to display h2_all - it works. The result is: [<h2>Запись к врачу</h2>, <h2>Запись на диагностику</h2>] But when I'm trying to loop to get each of h2 tag. {% for h2 in h2_all %} {{ h2 }} {% endfor %} The result is the following: [] [] I'a a beginner and this is my first project on Django. I've already spent several hours trying to solve the problem, but have no result... Please help... -
Django AJAX reload part of the HTML
I have a problem rendering the HTML element 'live'. This is my idea, I have a topbar which is included(not extending anything) in the 'base.html' like this : ... base.html <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <!-- Top Bar --> {% include 'topbar.html' %} ... And this is the 'topbar.html' itself : topbar.html <!-- Topbar --> {% load static %} {% load custom_tags %} {% notification_tag as notifications %} {% current_time as current_time %} {% events as all_events %} ... <ul class="navbar-nav ml-auto"> <!-- Nav Item - Alerts --> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-bell fa-fw"></i> <!-- Counter - Alerts --> {% if notifications %} {% for notif in notifications %} {% if notif.date_to_remind <= current_time %} <span class="badge badge-danger badge-counter">{{ notifications.count }}</span> {% endif %} {% endfor %} {% endif %} </a> <!-- Dropdown - Alerts --> <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="alertsDropdown"> <h6 class="dropdown-header"> Obaveštenja </h6> {% for n in notifications %} {% if not n.viewed %} <a class="dropdown-item d-flex align-items-center" href="{% url 'notification' n.pk %}"> <div class="mr-3"> <div class="icon-circle bg-primary"> <i class="fas fa-file-alt text-white"></i> </div> </div> <div> <div class="small text-gray-500">{{ n.eluid_posla … -
How to access json object passed from django?
I have an object from Django view as follows: [{ 'id': 49, 'user': { 'username': 'somename', 'id': 1 }, 'category': 4, 'sub_category': 49, 'title': 'amazing stuff', 'content': 'amazing stuff' }, { 'result': 'success' }] A portion of the view function: ret = get_forums() result = { 'result': 'success' } // used as indicator that the new post is saved ret.append(result) print(ret) return JsonResponse(ret, safe = False) jQuery AJAX: success: function(data) { if (data.result == 'success') { console.log(data); alert("Data sending was successful"); data = JSON.parse(data); update_forum_posts(data); } else { console.log(data); alert("Data sending was unsuccessful"); } }, The if condition is not valid if (data.result == 'success') The question is: how can I access the data which is ret in the view function and satisfy the if condition? NOTE: when I send a POST it is saved successfully but I get alert("Data sending was unsuccessful") -
How to upload large files to Google Storage using Google App Enginer + Django and JQuery File Upload
There is literally no example source code for Django and Large resumable file upload to Google Storage but only this https://cloud.google.com/storage/docs/performing-resumable-uploads#upload-resumable. Are there any examples on how I may achieve this ? -
How to dsiplay value from another model based on the same if form another model in django
I have db and the following classes: in models.py class Student(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=500) class Class101(models.Model): name=models.CharField(max_length=200) math=models.DecimalField(max_length=200) english=models.DecimalField(max_length=200) in views.py total_grade=Class101.objects.filter(Q(math__gt=70) & Q(english__gt=58)) context ={'tg':total_grade} in template.html {% for grade in tg %} <p> {{grade.name}} </p> {% endfor %} it lists name of students however i want to put in the template : {{grade.name}} - {{grade.surname}} {{grade.surname}} where surname is from model Student This code does display surname . How to make to display surname from another model where both models have the same name? -
include_tag considers the argument as a string
I'm trying to define an inclusion_tag and pass to it a dataframe as argument. Here is the definition. @register inclusion_tag('tabla_ampliadaV2.html') def tabla_ampliadaV2(df): dataframe = df t = datetime.datetime.now() today = datetime.date.today() manana = today + datetime.timedelta(days=1) manana_weekday = calendar.weekday(manana.year, manana.month, manana.day) pasado_manana = manana + datetime.timedelta(days=1) pasado_manana_weekday = calendar.weekday(pasado_manana.year, pasado_manana.month, pasado_manana.day) return {'Dia': ['Hoy', str(t.day)+'/'+str(t.month)], 'Manana': [manana_weekday, str(manana.day)+'/'+str(manana.month)], 'Pasado': [pasado_manana_weekday, str(pasado_manana.day)+'/'+str(pasado_manana.month)], 'Nubosidad': dataframe.loc['Nubosidad'], 'Temp_aire': dataframe.loc['Temp_aire'], 'Dir_viento': dataframe.loc['Dir_viento'], 'Vel_viento': dataframe.loc['Vel_viento'], 'Temp_agua': dataframe.loc['Temp_agua'], 'Altura_ola': dataframe.loc['Altura_ola'], 'Dir_olas': dataframe.loc['Dir_olas'], 'Periodo_olas': dataframe.loc['Periodo_olas'], 'Mareas': dataframe.loc['Mareas']} Then, when I call this tag as {% tabla_ampliadaV2 my_df %} I can see that it's considering my_df as a string and thus it doesn't work. I don't know what's wrong, in the docs it is said you can pass arguments of any type. Any help please? -
Django - translate clause "WHERE identity IN (SELECT identity ... GROUP BY identity)" to django orm
I have such a schema: http://sqlfiddle.com/#!17/88c6a It is simple variation on versioning model, where all versions of single entity have the same identity. I have to find all records which used to have category = 2 in their history. How can I reproduce such query in Django? SELECT * FROM some_table a WHERE identity IN (SELECT identity FROM some_table WHERE category = 2 GROUP BY identity ) AND is_latest = true; I tried to retrieve these identities in application class SomeTableQueryset(QuerySet): def had_category_2(self): with connection.cursor() as cursor: cursor.execute(""" SELECT identity FROM some_table WHERE category = 2 GROUP BY identity; """) valid_identities = [i[0] for i in cursor.fetchall()] and filter queryset by qs = qs.filter(identity__in=valid_identities) But such approach has several cons: it's not lazy, so query will be executed as soon as had_category_2 is called it's very slow for obvious reasons So, what can I do? -
Django context not passing context well
I was trying to pass a query set using context. But on template page the context is not working. As I am implementing two queries in same view one query set is working fine but the other query is not passed well. Here is my view # Create your views here. def xray_result_view(request): q=query_holding_together.objects.filter(which_user=request.user) for x in q: all_reports=xray_result.objects.get(which_query=x) print(all_reports.sys_gen_result) return render(request,'XRay/result.html',{'reports':all_reports}) when q is passed as template it is working as it should but it is not working for all reports. here is my template {% extends "login/successful.html" %} {% block middle_window %} </div> <div class="container adjust-ment"> <div class="row"> <div class="col-12"> Previous X-ray Results </div> </div> <div class="row"> <div class="col-12"> Result </div> </div> <div class="row"> <div class="col-12"> {% for y in reports.iterator %} File Name:<br> Date and Time of Upload:<br> System Generated Result:{{ y.sys_gen_result }}<br> Doctor's Comment on Result:{{ y.doctor_comment }}<br> {% endfor %} </div> </div> </div> {%endblock middle_window %}