Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to loop based on the each item quantity in django
here one item has item quantity as 2 and second item has item qty as 3 so total of 5 times the for loop should be iterated(i.e for first item 2 times and second item 3 times ) in context_dict when passing the data(i.e range) to template its is passing only last item quantity(i.e 3) so its printing both items 3times but actually i need is first item as 2 times and second item as 3times class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() items_list = [] for c in items: item_dict = {} item = c.item if c.item.season_interest: try: item_dict['season_interest'] = (',').join(eval(c.item.season_interest)) except: item_dict['season_interest'] = (',').join(c.item.season_interest.split(';')) if c.item.summer_foliage_colour: try: item_dict['summer_foliage_colour'] = (',').join(eval( c.item.summer_foliage_colour)) except: item_dict['summer_foliage_colour'] = (',').join(c.item.summer_foliage_colour.split(';')) if c.item.exclude_intolerant: try:s item_dict['exclude_intolerant'] = (',').join(eval(c.item.exclude_intolerant)) except: item_dict['exclude_intolerant'] = (',').join(c.item.exclude_intolerant.split(';')) if c.item.item_name: item_dict['item_name'] = c.item.item_name if c.item.categories: item_dict['categories'] = c.item.categories if c.item.part_number: item_dict['part_number'] = c.part_number if c.batch_number: item_dict['batch_number'] = c.batch_number if c.item.common_name: item_dict['common_name'] = c.item.common_name if c.item.flower_colour: item_dict['flower_colour'] = c.item.flower_colour if c.item.growth_rate: item_dict['growth_rate'] = c.item.growth_rate if c.item.date_purchased: item_dict['date_purchased'] = c.item.date_purchased if c.ready_date: item_dict['ready_date'] = c.ready_date if c.due_date: item_dict['due_date'] = c.due_date if c.item.tree_type: item_dict['tree_type'] = c.item.tree_type if c.quantity: item_dict['quantity'] = c.quantity items_list.append(item_dict) template = … -
Django How to display a link from user input form safely
I have an model (posts) that is tied to a form that when a certain character is used it creates a link to another portion of the web app. The user can enter several of these characters/links to different areas of the webpage in one post then I want to display all of the users posts to the user in a list looping over the model that stores the link. However, how can I do this while maintaining security? I do not want to allow the user to enter in HTML and it be rendered. For example: User enters form information: "Hello this is a @test and @about is a test too" User selects submit button and background magic to get the words test and about and convert them into links to take the user to the test and about pages in the web application. Display all of the inputs/posts that have been created: "Hello this is a @test and @about is a test too" I know that I can use the safe tag and just store the HTML link in the model and call like normal but since this is from user input I don't want to allow them … -
Displaying a dictionary value from django model in a html
I have a django model that consists of a JSONField(). What I am trying to do is pass the details of this field to html, by the form of a context variable. The JSONField() stores a dictionary. For some reason the I only the first part of each dictionary element shows up in the presented html file. Models.py: class WholeValues(models.Model): eb_top_items_list = models.JSONField() Main.py #updating JSONField() values with a dictionary eb_numbers_for_upload = WholeValues.objects.all() eb_numbers_for_upload.update(eb_top_items_list=df_eb_values.head(n=6).to_dict()) html <ul> {% for item in eb_top_items %} <ul> {{ item }}</ul> {% endfor %} </ul> So the dictionary that is in my .JSONField() looks as follows {'ElectricBikeA': 13, 'ElectricBikeB': 12, 'ElectricBikeC': 11, 'ElectricBikeD': 11, 'ElectricBikeE': 7} However displayed on the page is only the text part of the dictionary. what is displayed is missing the number values. All it has is ElectricBikeA, ElectricBikeB....etc So i guess the real question is how can I get a context variable to show the values of the dictionary as well as the name? -
django - restrict visibility of divs for specific user group
I have created a blog app in Django framework. I have set up a login, logout, and sign up authentication system so authorized users can see everything and unauthorized can see only the home page. I am using django cms so people can add and edit content on website. I created 2 groups of users on admin page: managers and editors. Managers can edit, delete and add posts and editors can only edit posts. I'd like to apply something like this but directly on HTML pages and limit elements in my Blog posts (DetailvedView pages) for editors. I have 2 divs in my blog post page. First div(class='everyone') is visible for everyone and the second div (class='managers') is visible only for managers group? In other words, first 50% of the page is visible for everyone so for managers and editors group and 100% of the page is vsible only for managers group. How can I achieve something like that? -
The current path didnt match any of these Error when adding a link to a button
Been trying to add a link and it keeps sending me errors although the templates are working. Views.py def store(request): context = {} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] main.html <a class="nav-link" href="{$ url 'cart' %}">Store <span class="sr-only"> (current)</span></a> <a class="nav-link" href="{$ url 'store' %}">Store <span class="sr-only"> (current)</span></a> <a class="nav-link" href="{$ url 'checkout' %}">Store <span class="sr-only"> (current)</span></a> the url route sends me an error but I can access to the templates by 127.0.0.1:8000/cart and 127.0.0.1:8000/ works for store and 127.0.0.1:8000/checkout works for checkout. but I can not access thru the links -
Implementing Third Party API in Django
I am currently working on a project where I am consuming a third party API. In my views.py I have two views, the first is a FormView called GetShipmentRates that displays a form to the user, validates the form, makes an API call to get shipment rates using the form data and then redirects to the second view where the response from the API will be displayed. Here is the code: class GetShipmentRates(FormView): template_name = 'PartShipper/GetPitneyBowesShipmentRates.html' form_class = ShipmentForm success_url = reverse_lazy('PartShipper:view_rates') def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super().post(self, request, *args, **kwargs) def form_valid(self, form): return super().form_valid(form) class DisplayRates(TemplateView): template_name = 'PartShipper/DisplayRates.html' def get(self, request, *args, **kwargs): return super().get(self,request,*args, **kwargs) def post(self,request,*args, **kwargs): return super().post(self,request,*args, **kwargs) Here is where I am lost - I want to know which method should call the API request, should it be handled in the form_valid() method of my FormView, or maybe the post method of my FormView (Note that if I make the API request in the post method then this happens before the form is validated which is probably not ideal). I was also thinking of handling the API request in the second view … -
Not able to Crawl HTTPS web pages with Scrapy
I have a web scrapper which works without any issues locally but it's not able to crawl HTTPS web pages on the production server (CentOS). FYI. everything works as expected when I run the script through the command line (i.e. python scan.py) but I'm getting below errors when I run crawler from Django view. I use the Apache webserver on CentOS. (Also, it works fine in my local Django setup) I'm getting the below error when trying to crawl HTTPS web pages [scrapy.core.scraper] ERROR: Error downloading <GET https://validurl.com/> Below is the full error log Traceback (most recent call last): [Wed Oct 20 08:55:14.843638 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/internet/defer.py", line 1658, in _inlineCallbacks [Wed Oct 20 08:55:14.843643 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] cast(Failure, result).throwExceptionIntoGenerator, gen [Wed Oct 20 08:55:14.843647 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/internet/defer.py", line 63, in run [Wed Oct 20 08:55:14.843652 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] return f(*args, **kwargs) [Wed Oct 20 08:55:14.843656 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/python/failure.py", line 500, in throwExceptionIntoGenerator [Wed Oct 20 08:55:14.843660 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] return g.throw(self.type, self.value, self.tb) [Wed Oct 20 08:55:14.843664 2021] [wsgi:error] [pid … -
Django query with filter order by and distinct errors out
I have this query for receiving objects with a filter and our distinct for users ordered by date HallOfFame.objects.filter(group=group).order_by('-time').distinct("winner__id") It errors out with this raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("groups_halloffame"."winner_id") "groups... Got to know its a postgres issue -
DRF testing - create object with a many-to-many relation
I have the following model Project: class Project(models.Model): name = models.CharField(max_length=128) slug = models.SlugField(blank=True) assigned_to = models.ManyToManyField( User, blank=True, related_name="assignees") created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=False, auto_now=True) If I need to create a new project, all I need to do is supply the name alone. This works for both the Admin dashboard and DRF APIVIEW. But when I try to test the functionality with DRF with an API call, I get the error: [b'{"assigned_to":["This field is required."]}'] Although the field is not required. My test code below import datetime from marshmallow import pprint from rest_framework.test import APITestCase, APIClient from freezegun import freeze_time from accounts.models import User from .models import Project @freeze_time("2021-11-14") class ProjectTests(APITestCase): client = APIClient() project = None name = 'IOT on Blockchain' dead_line = datetime.date(2021, 11, 21) data = { 'name': name, 'dead_line': dead_line, } def create_user(self): username = 'test_user1' email = 'test.user1@gmail.com' password = '@1234xyz@' user_type = 'regular' data = {'username': username, 'email': email, 'password': password, 'user_type': user_type, } return User.objects.create_user(**data) def create_project(self): project = Project.objects.create(**self.data) user = self.create_user() project.assigned_to.add(user) return project def test_create_project_without_api(self): """ Ensure we can create a new project object. """ self.project = self.create_project() self.assertEqual(Project.objects.count(), 1) self.assertEqual(self.project.name, 'IOT on Blockchain') self.assertEqual(self.project.dead_line, datetime.date(2021, 11, 21)) … -
getting url error , on custom action in drf django
I am trying to test my custom action but I am getting a URL incorrect error don't know where I am going wrong about this , I have included these URLs in project directory but somehow custom action is not working class DocumentViewset(viewsets.ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Document.objects.none() serializer_class = DocumentSerializer def get_serializer_class(self): if self.action == 'list': return DocumentSerializer if self.action == 'retrieve': return DocumentRetrieveSerializer return DocumentSerializer def get_queryset(self): queryset = Document.objects.filter(created_by=self.request.user).order_by('-id') return queryset @action(detail=False,methods=['get'],url_path='get_documents') def get_documents(self, request, pk=None): if pk == None: documents = self.get_queryset() else: documents = self.get_queryset() serialized_data = self.get_serializer_class(documents,many=True) data ={} data['serialized_data']=serialized_data.data data['id'] = pk return Response(data, status=200) router.register('document', DocumentViewset) router.register('notifications', NotificationsViewset) URL I am testing http://127.0.0.1:8000/api/document/1/get_documents -
Edit API POST Data before saving it in the Database
I've been stuck for 3 entire days on this. Frontend (Angular) is sending a Form data via POST: {name: 'Mario', surname: 'Super', location: 'New York', inputdatetime: '20-10-2021 15:52'} The "inputdatetime" is the custom date format "dd-MM-yyyy HH:mm" requested for the users and it is a string. I need to save it on my model via DRF: class Position(models.Model): id= models.AutoField(primary_key=True) name= models.CharField(max_length=20) surname= models.CharField(max_length=20) location= models.CharField(max_length=40) inputdatetime= models.DateTimeField() How can I convert 'inputdatetime' from a string in DateTimeField to be able to save it in the database creating a new record? So far I have tried to change DRF format date and Django format date to reflect "dd-MM-yyyy HH:mm", but the POST request went through only trying to pass the 'inputdatetime' as a ISOString, but, again, I need to do the "conversion" in the backend. -
Changed Django .py files not updating on nginx app
I'm updating a Django 1.7 application running on a Linux server with Nginx. I've updated my views.py and added some data to the payload sent to populate the template, to present in the resulting web page, but there's no update to the data being sent to the template. I made changes to the template files (html) to see if anything at all changes, and yes, the changes to the template were shown in the resulting web page. I figured that the -py files were being cached by something (web server maybe?) so I've restarted the nginx service again and again, but no change. The .pyc files did not update, so I removed them, restarted nginx, but no new .pyc files were generated. I ran python -m compileall in python 2, and new .pyc files were created, but the resulting web page still wasn't being updated. Bottom line... No changes made to my .py files are affecting the application being run. Changes to template files, javascript files and so on... no problem at all. Everything byt the .py files seem to work. I don't really know what more to present here to give more hints about my problem, so please ask. -
Django Multi-Social Authentication
I'm new to django. I'm seeking to to learn / develop rapidly and know stack overflow community has a lot of knowledge. Unfortunately I'm unable to find an answer to the problem I'm facing. Summary: Multiple social account authentication. Current State: I am using google authentication for user registration/login. Problem: I want user to link external accounts (i.e. instagram, facebook, coinbase) to their top level profile (as established through google authentication). Desired Outcome: A user will login using their google account. The associated accounts that have been linked to their profile will display. This means multiple accounts associated with their top level profile. I haven't written the code yet in hopes that an answer already exists. Any help is appreciated. -
Celery sync nodes of differents queue in a single prompt
I'm running Celery 4.4.2 and using differents queues and nodes on same machine. My objective is to separate and organize each Django Apps process. The queues are running ok on separetly nodes. The header example of each tasks are: @shared_task(name = "task1_App1", bind = True, result_extended = True, queue = 'App1') @shared_task(name = "task1_App2", bind = True, result_extended = True, queue = 'App2') And I run 2 Celery nodes in separetly prompt with: celery -A siteconfig worker-Q App1 -l info -n app1@%h -P gevent celery -A siteconfig worker-Q App2 -l info -n app2@%h -P gevent When I run a task in the node app1, it appears in the prompt running the node app2, with the message "app1 sync with app2". I want each node showing only its tasks, without sync to other node prompt. What options I can use? I'm using Win, Python 3.7.8 and Django 2.2. -
Django sessions for anonymous users on create Orders
I have views for add Order for user, it's working, and it's ok. But I need the same thing, but only for an anonymous user, through a session. I haven't worked with sessions, and I read the documentation, try it, but I can't. Please, write me, using my example in the else thread, how can I create an Order in a session for unauthorized users? def add_to_cart(request, pk): item = get_object_or_404(Item, pk=pk) if request.user.is_authenticated: if order = Order.objects.filter(user=request.user).first(): if order.products.filter(pk=product.pk).exists(): if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: order = Order.objects.create(user=request.user) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ??? # for Anonymous user in session # ??? Any information, tips, and links to similar situations - I will be very grateful for any help. -
Django admin - using autocomplete and filter on choices fields (not ManyToMany or ForeignKey)
This is my model: class Academic(models.Model): SCHOOL_COLLEGE_SERVICE = [ ('School Of Humanities', 'School Of Humanities'), ('School Of Culture & Creative Arts', 'School Of Culture & Creative Arts'), ('School Of Modern Languages & Cultures', 'School Of Modern Languages & Cultures'), ('School Of Critical Studies', 'School Of Critical Studies'), ('Arts College Of Arts Administration', 'Arts College Of Arts Administration'), ] school = models.CharField(choices=SCHOOL_COLLEGE_SERVICE, max_length=50, blank=True, null=True) I'd like to have a nice autocomplete / filter in my Django administration interface. Unfortunately it seems that it is not possible to have autocomplete if the dataset doesn't come from a ManyToMany or ForeignKey relationship. This is what I tried: from django.contrib import admin from .models import Academic, Partner, Project from admin_auto_filters.filters import AutocompleteFilter import django_filters @admin.register(Academic) class AcademicAdmin(admin.ModelAdmin): search_fields = ['surname', 'forename'] #school = django_filters.ChoiceFilter(choices=Academic.SCHOOL_COLLEGE_SERVICE) #autocomplete_fields = ['school'] I know I can also set a queryset like so: class SchoolFilter(django_filters.FilterSet): class Meta: model = Academic fields = ['school',] But Django still complains that The value of 'autocomplete_fields[0]' must be a foreign key or a many-to-many field. How can I achieve what I want? -
User signature api endpoint of outlook
I want a signature API endpoint to get the user outlook mail signature, API is needed in python or can drop API endpoint also -
AssertionError when calling put or create in Django Rest Framework
I am trying to update my Teachers view in DRF by instead of including the link to the department field, I would display the name of the department. When I added the PrimaryKeyRelated field, I was able to see the department.name but couldnt use update or create within DRF. Is there a way I could change the display without causing the need for the methods or is that not the case? Error The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `school.serializers.TeacherSerializer`, or set `read_only=True` on dotted-source serializer fields. The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer `school.serializers.TeacherSerializer`, or set `read_only=True` on dotted-source serializer fields. models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' # dont need success url if get_absolute_url on create and update view def get_absolute_url(self): return reverse('teacher', kwargs={'pk': self.pk}) serializers.py class TeacherSerializer(serializers.HyperlinkedModelSerializer): department = serializers.PrimaryKeyRelatedField( source='department.name', queryset=Department.objects.all()) class Meta: model = Teacher fields = ['url', 'name', 'department', 'tenure'] class DepartmentSerializer(serializers.HyperlinkedModelSerializer): teacher_set = TeacherSerializer(many=True, required=False) class Meta: model = Department … -
I can't override the create method, on serializers.ModelSerializer
I assure you that before writing I searched the whole internet. So my problem is this: I am trying to add a field on a model's ModelSerializer, the field is passed from the view and I am trying to add it to the response. I tried to override the create () but it doesn't even fit into it serializers: class MetricsV2Serializer(serializers.Serializer): aggregation_date = serializers.DateTimeField(read_only=True) week = serializers.IntegerField(read_only=True) month = serializers.IntegerField(read_only=True) year = serializers.IntegerField(read_only=True) ticket_total = serializers.IntegerField(read_only=True) in_queue = serializers.IntegerField(source="ticket_queue") in_queue_expiring = serializers.IntegerField(source="ticket_queue_expiring") social_page = serializers.CharField(read_only=True) team = serializers.CharField(read_only=True) category = serializers.CharField(read_only=True) store = serializers.CharField(read_only=True) solved = serializers.IntegerField(source="ticket_solved") pending = serializers.IntegerField(source="ticket_pending") processing = serializers.IntegerField(source="ticket_processing") unapplicable = serializers.IntegerField(source="ticket_unapplicable") closed = serializers.IntegerField(source="ticket_closed") #ticket_closed = serializers.IntegerField() store_tickets = serializers.JSONField(source="ticket_store") store_managed_tickets = serializers.JSONField(source="ticket_store_managed") store_total_tickets = serializers.JSONField(source="ticket_store_total") avr_management_work_time = serializers.SerializerMethodField(read_only=True) avr_management_time = serializers.SerializerMethodField(read_only=True) ticket_today_closed = serializers.IntegerField(source="ticket_closed") ticket_today_queue = serializers.IntegerField(source="ticket_queue") total_ticket_today = serializers.IntegerField(source="ticket_total") total_managed = serializers.SerializerMethodField() total_managed_today = serializers.CharField(write_only=True) class Meta: model = TicketAggregation fields = ( "aggregation_date", "week", "month", "year", "team", "category", "social_page", "store", "ticket_total", "in_queue", "in_queue_expiring", "solved", "pending", "processing", "unapplicable", "closed", "store_tickets", "store_managed_tickets", "store_total_tickets", "avr_management_time", "avr_management_work_time", 'ticket_today_closed', 'ticket_today_queue', 'total_ticket_today', 'total_managed', 'total_managed_today' ) # get_field etcetc def create(self, validated_data): log.info('nothing') log.info('nothing') log.info('nothing') ll = validated_data.pop('total_managed_today', '0') log.info('llllllllllllllllllll') log.info(ll) log.info('llllllllllllllllllll') log.info('llllllllllllllllllll') return super().create(validated_data) view class MetricsListV2(APIView): # … -
WebSocket connection to 'ws://http//127.0.0.1:8000/trainer_notifs/ws/notifications/' failed: (anonymous) @ trainer_notifs:124
const webSocket = new WebSocket( 'ws://' + window.location + '/ws/notifications/' ); webSocket.onopen=function(event){ webSocket.send(JSON.stringify({ 'message': 'From Client' })); } -
django Link two different fields in different record inside same table
I have been tryin to link two different fields within different records but in the same table/model in django using mysql. But I have been confused how to do the foreign key and call it. Any help -
Django not recognizing base.html java script
My django is not recognizing Java Script BootStrap, I have tried to open HTML without django and it is working, but when i put in django template dont work. Django not found the jquery.min.js and bootstrap.bundle.min.js please help me My Terminal [20/Oct/2021 10:08:42] "GET /auth/login/ HTTP/1.1" 200 2533 Not Found: /auth/login/js/jquery.min.js Not Found: /auth/login/js/bootstrap.bundle.min.js Html code <html> <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <link rel="stylesheet" href="C:\Users\marco\OneDrive\Documentos\Python\Django\Jornal\jornal\templates\style.css"> </head> <nav class="navbar navbar-expand navbar-dark background-color #070981" style="background-color: #070981;"> <a href="#menu-toggle" id="menu-toggle" class="navbar-brand"><span class="navbar-toggler-icon"></span></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample02" aria-controls="navbarsExample02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample02"> <ul class="navbar-nav mr-auto" > <h1 class="nav-titulo" href="#" style="padding-left: 1px; color: #fff;">Esportivo Regional</h1> <li class="nav-item active" > <a class="nav-link" href="#"> <img src="C:\Users\marco\OneDrive\Documentos\Python\Django\Jornal\jornal\templates\logo.png" alt=""><span class="sr-only">(current)</span></a> </li> </ul> <form class="form-inline my-2 my-md-0" > </form> </div> </nav> <div id="wrapper" class="toggled"> <!-- Sidebar --> <div id="sidebar-wrapper"> <ul class="sidebar-nav"> <li class="sidebar-brand"> Esportivo Regional </li> <li> <a href="#">Inicio</a> </li> <li> <a href="#">Login</a> </li> </ul> </div> <!-- /#sidebar-wrapper --> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <h1>Teste</h1> </div> </div> <!-- /#page-content-wrapper --> </div> <!-- /#wrapper --> <!-- Bootstrap core JavaScript --> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.bundle.min.js"></script> <!-- Menu Toggle Script --> <script> $(function(){ $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); … -
In python, django modules are not connected to python
from django.shortcuts import render. Import "django.shortcuts" could not be resolved from sourcePylance(reportMissingModuleSource ) this is error.please help me., i thought its virtualenv problem but i created one directory,in that virtualenv, files django is installed. The virualenv file contains all his folders and files,site-packages all., but still shows error -
Django custom admin widget subclassing ForeignKeyRawIdWidget
I am trying to create a custom admin widget which will be used in several different models to display a custom ForeignKey to an Image model. The goal is to display a thumbnail next to the ForeignKey input field. I have been following the blog post here but am running into the error: ValueError at /admin/events/event/2697/change/ Cannot assign "11": "Event.image" must be a "Image" instance. It looks like the save_form_data method in django.forms.models is expecting an instance of the Image model, rather than the id, but I'm not sure how to pass this via my custom model field, or form field. Here is the code: class ImageForeignKeyWidget(ForeignKeyRawIdWidget): def render(self, name, value, attrs=None, renderer=None, image=''): context = self.get_context(name, value, attrs) html = self._render(self.template_name, context, renderer) if value: image = Image.objects.get(id=value) thumb = image.version_url('thumb') image = f''' <div style="margin-top: 5px !important;"> <a href="{image.file.url}"> <img style='border: solid 1px #ccc;' src="{thumb}"/> </a> </div>''' return mark_safe(html + image) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) class ImageFormField(fields.IntegerField): def __init__(self, model=None, *args, **kwargs): super(ImageFormField, self).__init__(*args, **kwargs) self.widget = ImageForeignKeyWidget(model._meta.get_field('image').remote_field, admin.site) class ImageModelField(models.ForeignKey): def formfield(self, **kwargs): defaults = { 'form_class': ImageFormField, 'model': self.model } defaults.update(kwargs) return models.Field.formfield(self, **defaults) Is … -
Is there a way to join two models in Django?
I have a model with four important fields, I want to query this model for sum of values for each month, but these values are calculated differently based on their currency. So for example if currency = USD the formulae will be a * b / c and if it is GBP it will be a * b * c. This is what I have done so far; # model class Permit(models.Model): CONVERSION = [ (decimal.Decimal('1.0000'), '1.0000'), (decimal.Decimal('0.0006'), '0.0006'), (decimal.Decimal('0.0007'), '0.0007'), (decimal.Decimal('0.0010'), '0.0010'), (decimal.Decimal('0.0015'), '0.0015'), ] UNITS = [ ('m2', 'm2'), ('m3', 'm3'), ] CURRENCY = [ ('USD', 'USD'), ('GBP', 'GBP'), ('CFA', 'CFA'), ('Euro', 'Euro'), ] product = models.ForeignKey(Product, on_delete=models.CASCADE) specie = models.ForeignKey(Specie, on_delete=models.CASCADE) grade = models.ForeignKey(Grade, on_delete=models.CASCADE) info = models.ForeignKey(Info, on_delete=models.CASCADE) # volume volume = models.DecimalField(max_digits=19, decimal_places=3) conversion_factor = models.DecimalField( choices=CONVERSION, max_digits=5, decimal_places=4) units = models.CharField(choices=UNITS, max_length=2, default='m3') unit_price = models.DecimalField(max_digits=19, decimal_places=3) currency = models.CharField(choices=CURRENCY, max_length=5) ex_rate = models.DecimalField( max_digits=19, decimal_places=7, verbose_name='Exchange Rate') def __str__(self): return str(self.info.exporter) @property def euro_value(self): if self.volume and self.unit_price and self.ex_rate != None: if self.currency == 'USD': ev = self.volume * self.unit_price ev = ev / self.ex_rate ev = round(ev, 2) else: ev = self.volume * self.unit_price * self.ex_rate ev = round(ev, 2) else: …