Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use different database within same app in django?
I have a app named xyz and I have 2 views in that app view1.py and view2.py I have router configured as if model._meta.app_label == 'xyz' return database1 Is there a way to select a different database from this app 'xyz'. I mean two different database within same app. Is there a way or does django allow this in first place. -
Django Detail View returns 404 error (other stackoverflow solutions don't work)
I recently asked a question about DetialViews and linkify, but realized, the problem was not with the linkify, but getting the Detail View to show up. Whenever I try to get the detail view to show up, I get "404 error". How to get this to work? I've literally been working on this for a week, please help. I don't know where to look. Here is urls.py url patterns: (I've tried a bunch of different patterns and cannot get it to work.) path('hospitals/', views.HospitalListView.as_view(), name='hospital_list'), re_path(r'^hospitals/(?P<pk>\d+)$', views.HospitalDetailView.as_view(), name='hospital_detail') Here is my views.py: class HospitalListView(generic.ListView): model = Hospital context_object_name = 'hospital_list' template_name = 'hospital_list.html' class HospitalDetailView(generic.DetailView): model = Hospital def hospital_detail_view(request, primary_key): hospital = get_object_or_404(Hospital, pk='primary_key') return render(request, 'hospital_detail.html', {'hospital': hospital}) Here is my models.py. class Hospital(models.Model): """Model representing Hospitals.""" name = models.CharField(max_length=200, primary_key=True) hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular hospital in database') location_text = models.CharField(max_length = 800) class Meta: ordering = ['hopid'] def __str__(self): """String for representing the Model object.""" return f'{self.name} ({self.location_text})' Here is my html file - hospital_detail.html {% extends "base_generic.html" %} {% block content %} <h1>Hospital List</h1> {% if hospital_list %} <ul> {% for hospital in hospital_list %} <li> <a href="{% url 'hospital_detail' pk=hospital.pk %}">{{ … -
overriding put method in django serializers
Im using nested serializers and successfully overrided create method to save to the models.Now i have to do the same for the put method by overriding the update method . Im getting errors like: Direct assignment to the reverse side of a related set is prohibited. Use levels.set() instead. My serializer: class WorkflowSerializer(serializers.ModelSerializer): levels = WorkflowLevelSerializer(many=True) class Meta: model = Workflow fields = ('name', 'description', 'levels') def create(self, validated_data): levels = validated_data.pop('levels') workflow = Workflow.objects .create(**validated_data,tenant=self.context['request'].user.tenant) for index, level in enumerate(levels): level_var = WorkflowLevel() level_var.workflow = workflow level_var.level = level['level'] level_var.operation=level['operation'] level_var.save() for permission in self.initial_data['levels'][index] ['workflow_permissions']: permission_obj = WorkflowPermission.objects .filter(short_name=permission['short_name']).first() workflowlevelpermission = WorkflowLevelPermission() workflowlevelpermission.level = level_var workflowlevelpermission.permission=permission_obj workflowlevelpermission.save() return workflow def update(self, instance, validated_data): print(validated_data) levels = validated_data.get('levels') instance.name = validated_data.get('name', instance.name) instance.desciption = validated_data.get('description', instance.description) instance.levels = levels for index, level in enumerate(levels): level_var = WorkflowLevel() level_var.workflow = workflow level_var.level = level['level'] level_var.operation=level['operation'] level_var.save() for permission in self.validated_data['levels'][index] ['workflow_permissions']: permission_obj = WorkflowPermission.objects .filter(short_name=permission['short_name']).first() workflowlevelpermission = WorkflowLevelPermission() workflowlevelpermission.level = level_var workflowlevelpermission.permission=permission_obj workflowlevelpermission.save() return instance Can anyone suggest the correct way to write this update method? -
Django post data to redirect to same page with different variables
My homepage sends post data to the other player's page with its player_name variable. But when I try to do the same thing with player's page sending another player's post data, it doesn't redirect and pass the updated variable. Why is that, and how can I fix this? My url.py from django.conf.urls import url from site import views urlpatterns = [ url(r'^$', views.HomePage.as_view()), url(r'^player/(\w+)', views.PlayerPage.viewProfile, name = 'player_name'), ] My view.py class HomePage(ListView): template_name = 'index.html' def post(self, request): form = searchUser(request.POST or None) context = { 'form': form } if form.is_valid(): player = form.cleaned_data['player'] context.update({'player': player}) return HttpResponseRedirect("player/" + player) def get_queryset(self): return class PlayerPage(ListView): template_name = 'player.html' def viewProfile(request, player_name): return render(request, 'player.html', {'player_name' : player_name}) def post(self, request): form = searchUser(request.POST or None) context = { 'form': form } if form.is_valid(): player = form.cleaned_data['player'] context.update({'player': player}) return HttpResponseRedirect("player/" + player) My player.html <html> <body> {% block body %} <form role="form" method="post"> {% csrf_token %} <input name="player" placeholder="Search Player" type="search"> </div> </div> </form> {% endblock %} <br> {{player_name}} </body> </html> -
Difference between ViewSet and GenericViewSet in Django rest framework
I have a Django rest framework GenericViewset for which I am trying to set up pagination as follows: #settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20 } #views.py class PolicyViewSet(viewsets.GenericViewSet): def list(self, request): queryset = Policy.objects.all() page = self.paginate_queryset(queryset) serializer = PolicySerializer(page, many=True) return self.get_paginated_response(serializer.data) This works as expected.However, if i try to do the same with just a normal Viewset as follows: #views.py class PolicyViewSet(viewsets.ViewSet): def list(self, request): queryset = Policy.objects.all() page = self.paginate_queryset(queryset) serializer = PolicySerializer(page, many=True) return self.get_paginated_response(serializer.data) I get an error stating: 'PolicyViewSet' object has no attribute 'paginate_queryset' How do i set up pagination with a normal Viewset. What is the difference between a GenericViewset and Viewset in DRF ? -
Using PUT for update Gives a Value Error in Nested Object Django
I am trying to update the following model using PUT in django. and I have been unsuccessful till now. class Site(models.Model): siteID = models.CharField(max_length=255, primary_key=True) class EndDevice(models.Model): class Meta: unique_together = ("edevID", "siteID") edevID = models.CharField(max_length=255) siteID = models.ForeignKey(Site, related_name='endDeviceList', on_delete=models.CASCADE) deviceCategory = models.BigIntegerField() I have tried a couple of ways which are shown below: class ViewDevice(generics.RetrieveUpdateAPIView): ''' GET edev/{pkID}/ PUT edev/{pkID}/ ''' queryset = EndDevice.objects.all() serializer_class = DeviceSerializer def get(self, request, *args, **kwargs): try: a_dev = self.queryset.get(edevID=kwargs["pk"]) return Response(DeviceSerializer(a_dev).data) except EndDevice.DoesNotExist: return Response( data={ "message": "Device with id: {} does not exist".format(kwargs["pk"])}, status=status.HTTP_404_NOT_FOUND) def put(self, request, *args, **kwargs): try: a_dev = self.queryset.get(edevID=kwargs["pk"]) serializer = DeviceSerializer() updated_dev = serializer.update(a_dev, request.data) return Response(DeviceSerializer(updated_dev).data) except EndDevice.DoesNotExist: return Response( data={ "message": "Device with id: {} does not exist".format(kwargs["pk"])}, status=status.HTTP_404_NOT_FOUND) It gives me the error Cannot assign "'home3'": "EndDevice.siteID" must be a "Site" instance The other way which I tried was: def put(self, request, *args, **kwargs): try: a_dev = self.queryset.get(edevID=kwargs["pk"]) updated_dev = EndDevice.objects.update( edevID=a_dev.edevID, siteID = a_dev.siteID, deviceCategory=request.data["deviceCategory"],) return Response(DeviceSerializer(updated_dev).data) except: .... This gives me the error UNIQUE constraint failed: registration_enddevice.edevID, registration_enddevice.siteID_id And my serializer is below: class DeviceSerializer(serializers.ModelSerializer): class Meta: model = EndDevice fields = ("edevID", "siteID", "deviceCategory") Any help will be appreciated, … -
Update 1 or many fields in django model without if else condition statement
I currently have the following code: @csrf_exempt @jwt_authentication @require_http_methods(["POST"]) def update_tenant(request, unique_key): instance = get_object_or_404(Tenant, unique_key=unique_key) form = TenantUpdateForm(request.POST, instance=instance) if form.is_valid(): form.save() payload = {"status": True, "description": "Tenant fields updated."} return HttpResponse(json.dumps(payload, indent=2, cls=json_encoder), content_type='application/json', status=200) else: payload = {"status": False, "description": "Form is invalid.", "form": form.errors.as_json()} return HttpResponse(json.dumps(payload, indent=2, cls=json_encoder), content_type='application/json', status=404) So far everything works fine. but When I try to update just a single field it throws validation for missing fields. There is a way without using if else statement and value comparition to update any random field on a single model? -
Django: How to create child model's id grouped by its parent
What I'm trying to do is to add an id to Comment object but I want to create id depending on its parent Entry. User can post Comment to Entry. If Entry already has 3 Comment object, the next Comment child_id would be 4. However, I don't want to use count because I want to include Comment that is already deleted. models.py class Entry(models.Model): ... class Comment(models.Model): topic = models.ForeignKey(Entry, on_delete=models.CASCADE) child_id = ... Is there a good approach? -
Trying to create session shopping cart in Django
The case is that im trying to make session based shopping cart for my shop webapp but something goes wrong and i dont know where is problem, but im pretty sure that my code isnt good(This is my first time doing shopping cart). For now problem is that instead getting cart dictionary with products i get this: <cart.cart.Cart object at 0x00000000046C7EF0>. My html for now looks like this: {%block content%} Produkty w koszyku: {{cart}} {% endblock %} because for now i just want to see if products are correctly added to cart This is rest of my code which is related to cart: cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session=request.session cart=self.session[settings.CART_SESSION_ID]={} self.cart=cart def add(self, product, quantity=1, ): product_id=str(product.id) if product_id not in self.cart: self.cart[product_id]={'quantity':0, 'price':str(product.price) } else: self.cart[product_id]['quantity']+=quantity self.session[settings.CART_SESSION_ID] = self.cart def remove(self, product): product_id=str(product.id) if product.id in self.cart: del self.cart[product_id] self.session[settings.CART_SESSION_ID] = self.cart def __iter__(self): product_ids=self.cart.keys() products=Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)] ['product']=product for item in self.cart.values(): item['price']=Decimal(item['price']) item['total_price']= item['price'] * item['quantity'] yield item def clear(self): del self.session[settings.CART_SESSION_ID] forms.py QUANTITY_CHOICES=[(i, str(i)) for i in range (1, 11)] class CartAddForm(forms.Form): quantity=forms.TypedChoiceField( choices=QUANTITY_CHOICES, coerce=int) views.py from django.shortcuts import render, … -
Register user cognito in django
I am applying cognito into django and try to write a registered user api I used warrant library and are faulty. boto3.setup_default_session(region_name='ap-southeast-2') user_cognito = Cognito('your-user-pool-id','your-client-id') user_cognito.register(user['username'], user['password']) print(user_cognito) my error is: NotAuthorizedException at /api/register_user An error occurred (NotAuthorizedException) when calling the SignUp operation: Unable to verify secret hash for client 'your-client-id' please help me -
How to populate a django manytomany database from excel file
I'm trying to transfer data from a excel file into a manytomany table in my sqlite3 database. model.py from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) class School(models.Model): name = models.CharField(max_length=50, db_index=True) majors = models.ManyToManyField(Major) class professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberofRatings = models.CharField(max_length=50) #delete major from the model school = models.ForeignKey(School , on_delete=models.CASCADE) major = models.ForeignKey(Major , on_delete=models.CASCADE) def __str__(self): return self.ProfessorName Populating Script # populate.py, school_major_link import os import django from django_xlspopulator.populator import Populator os.environ.setdefault('DJANGO_SETTINGS_MODULE','blog_project.settings') django.setup() from locate.models import Major pop = Populator('C:/Users/David/Desktop/db_setup/School_Majors.xlsx', school_majors) pop.populate() Error message when attempting to run script Traceback (most recent call last): File "populate_school_major.py", line 9, in <module> pop = Populator('C:/Users/David/Desktop/db_setup/School_Majors.xlsx', school_majors) NameError: name 'school_majors' is not defined But it makes sense since this script looks for the class name in the models section verses the name of the table, so I'm not too sure how I would be able to populate the correct table, Note that I already have a table named majors which is already populated using this script, but since django makes manytomany relationships via a variable verses a seperate class i'm stuck. I tried using the populating script above, but noticed that … -
Why wont this object display for me in Django/Python
So I have a model with a bunch of CharField string questions (they do include , ? : in string, thought that might have been a problem but when I removed them it did not solve anything) I could not figure out a way to send the first id of the model using object.get or object.all, all I would see with print commands was the name, or first field in the model. Ended up finally getting the whole thing to display using print when I used this in my view: questions = Questionnaire.objects.filter(id=1).values() so then I get this returned with print but how do i display it (or should i be doing this differently) in html without trying to pick each field by name like Questionnaire.name Questionnaire.one ect ... I can not get a successful "for" parse on it <QuerySet [{'id': 1, 'name': 'Neuropathy', 'one': 'How often does the pain bother you?', 'two': 'Do you take medications to control pain?', 'three': 'Time of Day your symptoms bother you most: rate your level of pain during each time period.']> I tried doing a for q in questions and can do the q.one q.two q.three but how do i just loop that? … -
Django template doesn't show the entire list in my view
My view function printing all of the list in terminal but it is show just 1 line in template(web ,html page) how to fix my code for like terminal output /views.py def snmpWALK(request): if request.method=='GET': host= 'localhost' oid = '1.3.6.1.2.1.1.9.1.2' for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget((host, 161)), ContextData(), ObjectType(ObjectIdentity(oid)), lookupMib=False, lexicographicMode=False): if errorIndication: print(errorIndication, file=sys.stderr) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr) break else: for varBind in varBinds: print('%s = %s' % varBind) results ='%s = %s' % varBind return render(request, 'snmpWALK.html', {'results':results}) /snmpWALK.html {% block content %} {{results}} {% endblock %} terminal printing 1.3.6.1.2.1.1.9.1.2.1 = 1.3.6.1.6.3.11.3.1.1 1.3.6.1.2.1.1.9.1.2.2 = 1.3.6.1.6.3.15.2.1.1 1.3.6.1.2.1.1.9.1.2.3 = 1.3.6.1.6.3.10.3.1.1 1.3.6.1.2.1.1.9.1.2.4 = 1.3.6.1.6.3.1 1.3.6.1.2.1.1.9.1.2.5 = 1.3.6.1.6.3.16.2.2.1 1.3.6.1.2.1.1.9.1.2.6 = 1.3.6.1.2.1.49 1.3.6.1.2.1.1.9.1.2.7 = 1.3.6.1.2.1.4 1.3.6.1.2.1.1.9.1.2.8 = 1.3.6.1.2.1.50 1.3.6.1.2.1.1.9.1.2.9 = 1.3.6.1.6.3.13.3.1.3 1.3.6.1.2.1.1.9.1.2.10 = 1.3.6.1.2.1.92 web printing 1.3.6.1.2.1.1.9.1.2.10 = 1.3.6.1.2.1.92 -
Django does not appear on HTML page
{% extends 'Post_html/Layout.html' %} {% include 'Add_css/arrow.html' %} {% block body %} <!DOCTYPE html> <html> <head> <title>Three Column HTML Layout</title> <style type="text/css"> .kolon { float:right; padding:5px; margin:5px; } </style> </head> <body> <table width = "100%" border = "0"> <tr valign = "top"> <td width = "20%"> <a style="margin-left:38px;" href="{% url 'help_post_urls:create_post' %}">Post Oluştur </a> <br /> </td> <td class="container" height = "200" width = "60%"> <!– Sayfanın akış bölümü –> {% for post in post_list %} <h3><a href="{% url 'help_post_urls:post_detail' post.pk %}">{{ post.title }} </a></h3> <img src="{{ post.image_post.url }}"> <p>{{ post.content }}</p> <small >Oluşturulma Tarihi : {{ post.create_post}} <small > Güncellenme Tarihi: {{ post.update_post|timesince }}</small></small> <form class="kolon" action="{% url 'help_post_urls:update_post' post.pk %}"> <input name="post_güncelle" type="hidden" value="{{ post.pk }}"> <input class="btn btn-danger" style="height: 35px;" type="submit" value="Güncelle"> </form> <form class="kolon" action="{% url 'help_post_urls:delete_post' post.pk %}"> {% csrf_token %} <input name="post_sil" type="hidden" value="{{ post.pk }}"> <input class="btn btn-danger" style="height: 35px;" type="submit" value="sil"> </form> <br> <br> <hr> {% endfor %} </td clas> <table> </body> </html> {% endblock %} <model> <!-- begin snippet: js hide: false console: true babel: false --> ` from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, HttpResponse, HttpResponseRedirect, reverse, get_object_or_404 from .post_form import PostForm from .models import Post_article # Create your … -
The view management.views.home didn't return an HttpResponse object. It returned None instead
I keep getting this error while trying to submit my django form. I'm quite new to django and this error has got me stuck for days. here's my model.py class Person(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) choices = ( ('Staff', 'staff'), ('Building Manager', 'BM'), ) type = models.CharField(max_length=30, choices=choices) def __str__(self): return '{0} {1} {2}'.format(self.pk, self.name.first_name, self.name.last_name) class Building(models.Model): address = models.CharField(max_length=100) person = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.address class Device(models.Model): name = models.CharField(max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) total = models.IntegerField() building = models.ForeignKey(Building, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Ticket(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE) issue = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) room = models.CharField(max_length=255) urls.py urlpatterns = [ path('', views.home, name='home'), path('ajax/load-devices/', views.load_device, name='ajax_load_device') ] views.py def home(request, cls=TicketForm): items = Building.objects.all() if request.method == "POST": form = cls(request.POST or None) if form.is_valid(): form.save() return redirect(reverse('home')) else: form = cls() return render(request, 'home.html', {'form': form, 'items': items, 'header': 'Building'}) def load_device(request): category_id = request.GET.get('category') devices = Device.objects.filter(category_id=category_id).order_by('name') return render(request, 'device_dropdown.html', {'devices': devices}) forms.py class TicketForm(forms.ModelForm): class Meta: model = Ticket fields = ['name', 'issue', 'category', 'device', 'room'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['device'].queryset = Device.objects.none() if 'country' in self.data: try: … -
Render django_tables2.Column with select tag inside
I've written a custom editable table with columns subclassing from django_tables2.Column, but keep struggling with rendering a select tag in my custom column. Considering the model: myapp/models.py from django.db import models from myapp.utils.enums import MyModelChoices class MyModel(models.Model): options = models.CharField( max_length=50, blank=True, null=True, choices=MyModelChoices.choices() ) and my enum in myapp/utils/enums.py: class MyModelEnum: __metaclass__ = EnumMeta # Logic irrelevant First = 'First', Second = 'Second', Third = 'Third' I end up with custom column like this: import django_tables2 as tables from django.forms import ChoiceField class ChoicesColumn(tables.Column): def __init__(self, choices, attrs=None, **extra): self.choices = choices kwargs = {'orderable': False, 'attrs': attrs} kwargs.update(extra) super(ChoicesColumn, self).__init__(**kwargs) def render(self, value, bound_column): select = ChoiceField(choices=self.choices) return select.widget.render( bound_column.name, self.label_to_value(value) ) def label_to_value(self, label): for (v, l) in self.choices: if l == label: return v which is later called in my table class like this: from django_tables2 import Table from myapp.models import MyModel class MyTable(Table): options = ChoicesColumn( choices=lambda record: record.options.choices() ) class Meta: model = MyModel fields = ('options',) but still there's rendered just a plain <td></td> with text instead of select field. What am I doing wrong in this situation? I'm using Python 2.7 and Django 1.8. Thanks in advance for your advice! -
django admin save override
models.py : class Cars(models.Model): checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) carname=models.CharField(max_length=128,verbose_name=_('carname'),unique="True") confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.carname) class Meta: verbose_name=_('car') verbose_name_plural=_('cars') ordering = ('carname',) class Stocks(models.Model): user=models.ForeignKey(User, null=True,related_name='stockdetails') mark=models.CharField(max_length=128,blank=True, null=True,verbose_name=_('mark')) pic=models.ImageField(blank=True,null=True,verbose_name=_('pic'),upload_to = 'stocks', default = 'stocks/nopic.jpg') car=models.ForeignKey(Cars,blank=True,null=True,verbose_name=_('car'),on_delete=models.SET_NULL ,to_field='carname') description=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('description')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.id) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:detailadvertisement' ,kwargs={'id':self.id}) The table stocks has foriegn key from cars table. I want that when ever the admin saves the confirm field of stock as "approved" , the confirm field of cars saves as " approved " too . what i did is overriding the save method in admin.py : class StocksAdmin(admin.ModelAdmin): list_display=["user","raste","stname","mark","description","pic","price","confirm","car","carbrand","date","parts_cars"] list_editable=["confirm",] def save_model(self, request, obj, form, change): if obj.confirm == _('approved') : obj.car.confirm =_('approved') super().save_model(request, obj, form, change) class Meta: model= Stocks admin.site.register(Stocks,StocksAdmin) but it doesnt work -
turn off postgres parallel query for a single Django query
I have a query that I need within my Django app that I needed to hand-optimize. But getting the query to run fast means that I need to be able to tell Postgres "don't use parallelism on this". What I thought would work was: from django.db import connection cursor = connection.cursor() # start a transaction so that PGBouncer runs the next statements # on the same connection cursor.execute("begin") # turn off parallelism for this next query cursor.execute("set max_parallel_workers_per_gather = 0") # run my query cursor.execute("HAND-TUNED SELECT QUERY GOES HERE") # process the cursor results # Put this connection back in the PGBouncer pool, and reset # max_parallel_workers_per_gather. cursor.execute("rollback") But it does not seem to be working. My query continues to show up in my "slow query" logs when I run it through the Django site, and the performance remains lousy (4+ seconds with parallelism, 0.5 seconds without). Is there a way to do what I need to do? -
Django update field in many to many relationship
I have two models many to many relationships, I am trying to update the field using a form. when a leave is submitted the director is notified by email. the director can login to the system to approve the leave using the form. once the leave is approved, I want to adjust the Leave_current_balance field which in on the LeaveBalance model class LeaveBalance(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) Leave_current_balance= models.FloatField(null=True, blank=True, default=None) Year=models.CharField(max_length=100,default='') def __unicode__(self): return self.Year class NewLeave(models.Model): user=models.ForeignKey(User,default='',on_delete=models.CASCADE) leave_balance=models.ManyToManyField(Leave_Balance) leave=( ('annual','annual'), ('sick','sick'), ) Leave_type=models.CharField(max_length=100,choices=leave,blank=False,default='') Total_working_days=models.FloatField(null=True, blank=False) DirAuth=( ('Pending','Pending'), ('Approved','Approved'), ('Rejected','Rejected'), ) Director_Authorization_Status=models.CharField(max_length=100,choices=DirAuth,default='Pending',blank=False) Date_Authorized=models.DateField(null=True,blank=False) Authorized_by_Director=models.CharField(max_length=100,default='',blank=False) def __unicode__(self): return self.Leave_type class DirectorForm(forms.ModelForm): class Meta: model=NewLeave fields=('Director_Authorization_Status','Authorized_by_Director','Date_Authorized',) widgets={ 'Date_Authorized':DateInput() } This function throw the error: u'Leave_current_balance' def unitDirectorForm(request,id): if request.method=='POST': getstaffid=NewLeave.objects.get(id=id) form = DirectorForm(request.POST, instance=getstaffid) if form.is_valid(): getstaffid = form.save(commit=False) getstaffid.save() total_days = getstaffid.Total_working_days current_balance = getstaffid.user.leave_balance.Leave_current_balance diff_balance = current_balance - total_days current_balance = diff_balance current_balance=form.fields['Leave_current_balance'] current_balance.save() getstaffid.leave_balance.add(current_balance) return HttpResponse('You have successfuly Authorise the leave') else: #getstaffid=NewLeave.objects.get(id=id) form=DirectorForm() #c_balance=Leave_Balance.objects.get() balance_form = leavebbalanceForm() return render(request,'managerauthorisedform.html',{'form':form}) -
How to rank query results when using Q objects
I am building an image database using Django. The user should be able to search for an artwork using its title, the names the artists, its location, etc. I am currently using Q Objects to construct the query: query_search = request.GET.get('search') terms = [term.strip() for term in query_search.split()] q_objects = Q() for term in terms: q_objects.add(Q(title__icontains=term), Q.OR) artists = Artist.objects.filter(Q(name__istartswith=term) | Q(name__icontains=' ' + term)) q_objects.add(Q(artists__in=artists), Q.OR) q_objects.add(Q(location_of_creation__name__istartswith=term), Q.OR) keywords = Keyword.objects.filter(name__icontains=term) q_objects.add(Q(keywords__in=keywords), Q.OR) querysetList = (Artwork.objects.filter(q_objects) .exclude(published=False) .order_by('title', 'location_of_creation', 'artists') .distinct()) I would like to order the results by relevance (e.g. show title-matches before artist-name-matches). As far as I understand this is usually accomplished by using annotate(): A ranking number is set and then used by order_by(). However, I am not sure how to do this when using Q objects. Is it possible to "annotate" Q objects? Or am I barking up the wrong tree here? -
How to work with images in pure Django templates so that they work like they do in Wagtail
I intend to use images in my Django blog app, and I am wondering how do I go about this. So I only want one image to be uploaded with each post page. I added an ImageField() so that's that, however I can't force images to be uploaded to media/ folder. Also, I don't know how to force images to be automatically resized and have their names automatically changed. Right now, the declaration for the field handling Images is really simple main_image = ImageField(upload_to='media/', null=True) I don't really know how to do any of this, even though I have done my fair share of googling -
How to use default datetime serialization in Django REST Framework?
I've got a Django REST Framework serializer containing the following: from rest_framework import serializers class ThingSerializer(serializers.ModelSerializer): last_changed = serializers.SerializerMethodField(read_only=True) def get_last_changed(self, instance: Thing) -> str: log_entry = LogEntry.objects.get_for_object(instance).latest() representation: str = serializers.DateTimeField('%Y-%m-%dT%H:%M:%SZ').to_representation(log_entry.timestamp) return representation This is problematic because if the datetime formatting ever changes it will be different to all the other datetimes. I want to reuse the code path which DRF uses to serialize other datetime fields. The only answer which looked relevant doesn't actually produce the same result as DRF (it includes milliseconds, which DRF does not), presumably because it's using the Django rather than DRF serializer. serializers.DateTimeField().to_representation(log_entry.timestamp) doesn't work either; it produces a string with microsecond accuracy. -
How can I speed up Django Query aggregations on a 10 million row database with 60 features?
I have a database table in psql which contains of 10,000,000 rows and 60 columns (features). I define a Django Queryset as follows: MyQ=MyDataBase.objects.filter(Name='Mike', date=date(2018, 2, 11), Class='03') There are only 5 rows that satisfy the above filter. But when I try something like MyQ.count() #which equals 5 or MyQ.aggregate(Sum('Score'))['Score__sum'] #which equals 61 each take about 3 minutes to give me the result. Isn't that weird? Aren't query sets supposed to make life easier by focusing only on the rows that we have told them to focus on? counting 5 rows or summing one of the fields of them must not take that long. What am I doing wrong? I should also say this. The first time that I tried this code on this table, everything was fine and it took maybe 1 second to catch the result but now the 3 minutes is really annoying. And since then I have not changed anything in the database or the code. -
Issue configuring Django with vuejs
I had to use VueJs in my Django application, but when i try to test the Vue Funcionality its dont work, i did change the dellimiters but still dont work: {% block vuescripts %} <div id="starting"> <p>[[teste]]</p> </div> <script type="text/javascript"> vue = new Vue({ el: '#starting', delimiters: ['[[',']]'], data: function(){ return { teste:'dado' } } }); </script> {% endblock %} Someone have a clue? Thanks -
How to POST Powershell output in Django
I am currently working on a small Django project. I have written some powershell scripts for e.g. get active directory users and want to setup a Django app which allows me to post the output from my powershell script this is my cmdlet and output - Command - Get-OrgUser -eNumber 123456 Output - FullName : Surname, Firstname eNumber : 123456 PasswordExpired : False LastBadPasswordAttempt : 10/01/2019 12:16:28 LastLogonDate : 13/02/2019 12:59:58 LockedOut : UnLocked LockoutTime : 0 PasswordLastSet : 17/01/2019 11:52:49 My Django app should allow user to input the employee number and show the results that it gets back from Powershell command.