Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
order_by() and latest() returning different queryset values
Quering the database using order_by('date') and latest('date') returning different instance.....Which is the best method to get the latest the instance. I am using python 2.7 and django1.8.19 from apps.model import MyModel def function(): using_latest = MyModel.objects.filter(member=member).latest('date').date using_latest = MyModel.objects.filter(member=member).order_by('date')[:1].values('date') -
Saving a row to database with active user id in Django
My model has a user field, which is Django's auth_user_model: class MyModel(models.Model): managed = True db_table = 'mymodeltable' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) In the view, I try to save a new row to the database, I get the following error: null value in column "user_id" violates not-null constraint However, I actually save new row with active user object class MyModelView(viewsets.ModelViewSet): @action(methods=['post']) def create(self, request): # Get active user: user = self.request.user serializer = MyModelSerializer(data={user: user}) # I also tried user.id if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In the related serializer, I return created instance: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('status', ) def create(self, validated_data): my_model_instance = MyModel.objects.create(status=False, **validated_data) return my_model_instance What am I missing? -
Deploying Django app on hosting platforms
Im very new to Django, i wanted to ask what exactly does a Django app come with? From looking at the documentations, it seems a lot of the Django code is very high level and abstracts out a lot of the native python calling code. I wanted to ask, does a Django app also provide a web server and the Django app + web server code is hosted on a machine during deplyoment or is the Django app code uploaded and hosting platforms run their own server code and embedded your Django app? -
How to extract or parse particular line of text from notepad using python?
Below I have a Multitext in notepad.txt File where I want to extract all the values of external_uid column only and print all the value in a list variable external_value using python script. Can anybody help me with the script code? For Example: external_value = ['0114e606-df6c-4657-8a57-ae104a541787', '0144d28b-95ac-4b06-8f24-678635a68f63', ......, '25b30794-ce69-4538-8675-bb568dac1296'] -
Django test.py model object instance is limited to one test
Okay this is pretty strange. This is my code that works: test.py from django.test import TestCase from django.urls import reverse, resolve from django.utils import timezone import datetime from ..models import Realtor, Listing, Contact from ..views import listing from django.test import override_settings from PIL import Image from io import BytesIO from django.core.files import File import tempfile def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGB", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) class RealestateListingViewTest(TestCase): @override_settings(MEDIA_ROOT=tempfile.TemporaryDirectory(prefix='mediatest').name) def setUp(self): image_file = get_image_file Realtor.objects.create(name='sample_realtor', photo=get_image_file()) Listing.objects.create(title='listing_sample', address='sample', realtor=Realtor.objects.get(pk=1), city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', photo_main=get_image_file(), photo_1=get_image_file(), photo_2=get_image_file(), photo_3=get_image_file(), photo_4=get_image_file(), photo_5=get_image_file(), photo_6=get_image_file()) url = reverse('btre:listing', kwargs={'listing_id': 1}) self.response = self.client.get(url) def test_listing_status_code(self): self.assertEquals(self.response.status_code, 200) The above code works but whenever I add another test to the mix, like: def test_listing_url_resolves_listing_view(self): view = resolve('/realestate/listing/1') self.assertEqual(view.func, listing) I get this error: realestate.models.Realtor.DoesNotExist: Realtor matching query does not exist. Anyone have an idea how or why this is happening? Also note that it works as long as there is only one test existing in the TestCase class which is why it is very strange to me. Also I have tried this method for the image file creation: class RealestateListingViewTest(TestCase): … -
How to use server side in django datatables?
I have datatables to present some data. I already make the serializer, viewset, and the ajax for datatables. serializer.py class UserSerializer(dserializers.DynamicModelSerializer): """UserSerializer class.""" organisation = DynamicRelationField('oree.serializers.organisation.OrganisationSerializer', embed=True, deferred=True) # id = dserializers.IntegerField(read_only=True) class Meta: # noqa D106 model = User name = 'user' fields = ('id', 'username', 'email', 'organisation', 'date_joined', 'is_staff') datatables_always_serialize = ('id', 'email') views.py class UserViewSet(dviewsets.DynamicModelViewSet): """UserViewSet.""" serializer_class = UserSerializer queryset = User.objects.order_by('email') filter_fields = ('username', 'email',) def get_options(self): """Helper method on datatables. see: https://django-rest-framework-datatables.readthedocs.io/en/latest/tutorial.html """ return "options", { "user": [{'label': obj.email, 'value': obj.pk} for obj in User.objects.all()], "organisation": [{'label': obj.name, 'value': obj.pk} for obj in Organisation.objects.all()] } class Meta: """Meta class for viewset.""" datatables_extra_json = ('get_options',) ajax.js var KTDatatablesDataSourceAjaxServer = function() { var initTable1 = function() { var table = $('#kt_datatable'); // begin first table table.DataTable({ serverSide: true, ajax: { 'type': 'GET', 'url': '/v1/users?format=datatables&include%5B%5D=organisation', // 'data' : { 'format': 'datatables' }, 'dataSrc': function(jsonObj){ if(!jsonObj.data || !jsonObj.data.users){ // console.log(jsonObj.data) return []; } console.log(jsonObj) return jsonObj.data.users; } }, columns: [ {data: 'username', searchable:true, name: 'username'}, {data: 'email', orderable: true, searchable:true, name: 'email'}, {data: 'organisation.name', searchable:true, name: 'organisation.name'}, {data: 'date_joined', orderable: true, searchable:false}, {data: 'is_staff', orderable: true, searchable: false}, ], columnDefs: [ {targets: [0,1,2,3], render: function(data){ if (!$.trim(data)) { return … -
What's happening behind django migrations?
I know what django migrations are. I want to know what happens when we run python manage.py migrate. Which tables are changed by django migrations? Why is it necessary to change those tables? When i write from myapp.models import some_model, how does django know which database table maps to which model? Did migrate add any entry for it in db? -
Why event loop not shared in thread?
I wrote a class as below. The purpose of this class is to make async call as simple as multiprocessing. class AsyncPool(object): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) def __init__(self, pool_size=1000): self.task_list = list() self.running_task = list() self.pool_size = pool_size self.current_pool_size = 0 def add_task(self, func, *args, **kwargs): self.task_list.append({ 'call': func, 'kwargs': kwargs, 'args': args }) def run(self): for item in self.task_list: if self.current_pool_size < self.pool_size: self.current_pool_size += 1 func = item.get('call') args = item.get('args') kwargs = item.get('kwargs') self.running_task.append( asyncio.ensure_future( func(*args, **kwargs) ) ) else: self.loop.run_until_complete(asyncio.wait(self.running_task)) self.current_pool_size = 0 The example usage will be like below pool = AsyncPool(pool_size=10) for num in range(1, 101): pool.add_task(hello_world, num) pool.run() The hello_world here can be any func defined by async. For example: async def hello(id, *args, **kwargs): await asyncio.sleep(5) This run well in script. But when I call it in django view. It report error as below: RuntimeError: There is no current event loop in thread 'Thread-13'. My guess is that django implement each request in seperate thread. Alough I intialize the loop attribute in the class and make it a class attribute. But the loop object can not be shared between thread. But I do not know if it is right. So could you … -
Signals do not seem to work, honestly tried a lot
creating a user model auth for website, used signals to auto create but seems to not get triggered, confused user is created, but not profile can someone help me this time models.py class InterestChoice(models.Model): INTEREST_CHOICES = ( ('A', 'traveling'), ('B', 'exercise'), ) interest = models.CharField(max_length=1, choices=INTEREST_CHOICES, unique=True) def __str__(self): return self.get_interest_display() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) dob = models.DateField() image = models.ImageField(default='default.jpg', upload_to='profile_pics') GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) interests = models.ManyToManyField(InterestChoice) def __str__(self): return f"{self.user.username} Profile" def save(self): super().save() signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() here's the apps.py code apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals -
How to display manual action to "History" in admin django?
I followed this tutorial : https://docs.djangoproject.com/en/2.2/ref/contrib/admin/actions/ And i cant't see log about this action in to History.(But changed,.. default actions of django admin can show blog on there) How can i add log to History like 'User_1 Make published' ? Thank you so much. -
NoReverseMatch UpdateView
I am writing and Update View for a model that I have created. The model is a Product Backlog Item. The UpdateView is unable to find a reverse match for my view. UpdatePBI View pk_url_kwarg = 'pbipk' kwargs={'pk_url_kwarg': 'pbipk'} model = PBI fields = ['priority', 'summary', 'story_points', 'effort_hours'] login_url = '/accounts/login' redirect_field_name = '/home' template_name = 'backtrack/PBIdetail.html' def dispatch(self, request, *args, **kwargs): print(kwargs) return super().dispatch(request, *args, **kwargs) def get_success_url(self): return "{}?all=0".format(reverse('pb', kwargs={'pk': self.kwargs['pk']})) def get_object(self, queryset=None): obj = get_object_or_404(self.model,pk=self.kwargs['pbipk']) return obj def form_valid(self, form): PBIList = getPBIfromProj(self.kwargs['pk'], '0') remove = [] priorityData = form.cleaned_data['priority'] if int(priorityData) < self.object.priority: # Remove all PBI with priority higher than post data priority # and lesser or equal than current PBI priority for PBIObj in PBIList: if PBIObj.priority < int(priorityData) or PBIObj.priority >= self.object.priority: remove.append(PBIObj.priority) PBIList = [ PBIObj for PBIObj in PBIList if PBIObj.priority not in remove] # Increase each objects priority by one for PBIObj in PBIList: PBIObj.priority += 1 PBIObj.save() else: # Remove all PBI with priority higher than post PBI priority # and lesser than and equal to Post data priority for PBIObj in PBIList: if PBIObj.priority <= self.object.priority or PBIObj.priority > int(priorityData): remove.append(PBIObj.priority) PBIList = [ PBIObj for PBIObj … -
How To Crop Django Media Image Automatically And Post
How To Crop Django Media Image Automatically And Post i don't want to crop with humans if someone upload any image our back-end crop it specific-size and post it Any Help: Appreciated!! -
How to display something in a django template according to which user is logged in?
I am displaying a table in a django template, and I have 2 identical templates but with 2 different tables. I have 2 different user groups. I want to display a different template according to which auth group the user belongs to. For example: if user is in group A: render template1.html else if user is in group B: render template2.html All I know right now is that I used the @login_required decorator, so the view is not gonna be shown if the user is not logged in. But this includes all users, and is not specific to groups. def home(request): ecv_count = Dossier.objects.filter(status_admin='ECV').count() v_count = Dossier.objects.filter(status_admin='V').count() r_count = Dossier.objects.filter(status_admin='R').count() c_count = Dossier.objects.filter(status_admin='C').count() context = { 'dossiers': Dossier.objects.all(), 'ecv_count': ecv_count, 'v_count': v_count, 'r_count': r_count, 'c_count': c_count } return render(request, 'dashboard/home.html', context) I want to have the view check the user group, and render a different template with a different context. -
Django Json Field - Find objects hat do not have key
I have a Model with a JSON Field. data = JSONField(default=dict) Is there an efficient way - or queryset filter - to find all instances of this Model that do not have a speicfic key in the json field. Django documentation includes has_key function for JSON field. Essentially i'm looking for a way to do not_has_key My current method: queryset = MyObj.objects.all() for obj in queryset: if 'my_key' not in obj.data: do_work() else: pass #key_already_exists Many thanks -
django nested query or join two tables
I list the debts of my customers from the "debts" table with the following code. However, I would like to see the name and surname of the customer with the same ID number from the "Customer" table. I get the person I specified with the following code but; I cannot print to "Debts.objects.values (" customer ")". Is there an easy way to do this? Thanks for your help. class CustomerDetailDebtListAPIView(ListAPIView): serializer_class = DebtCreateSerializer def get(self, request): # get customer , customerKey obj_customer = Customer.objects.get(customer=85) field_object_customer = Customer._meta.get_field('customer') # field_value_customer = getattr(obj_customer, field_object_customer.attname) print(obj_customer) result = Debt.objects.values('customer') \ .annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) \ .order_by('customer') return Response(result) -
Django form post contains multiple(2) csrfmiddlewaretoken in the request
I am trying to make a Django post request using a form but when I inspect the request, two csrfmiddlewaretoken are available on the request. Could someone explain to me why this might happen and how to prevent the duplication?? -
python django how to store images for streaming them as background image of bokeh plot
Im working on a live viewer. It also has to stream images as a background picture of plot/chart. These images are stored atm in a folder as jpg. Now my colleagues want to store them in a mongodb. I think this is not the correct way for storing and streaming images (1 per sec). If reciving from db : take picture convert to binary save to db read from db convert back to jpg stream to frontend The 2 converting steps are uneeded when doing it this way: take picture save to folder read from folder stream to frontend Any reason why the first way should be acceptable and why the second way is not better then the first? -
How to make a <select> through Django ModelChoiceField
I have a that is rendered manually. I want to remake it through Django ModelChoiceField.How to do it? views.py contractors = cache.get('contractors') if not contractors: contractors = Contractors.objects.values_list('name', flat='True') cache.set('contractors', contractors, 3600) Html-code <select name="contractorName" class="form-control" id="id_contractorName"> option value="" selected="">---</option> {% for contractor in contractors %} <option value="{{ contractor }}">{{ contractor }}</option> {% endfor %} </select> models.py class Contractors(models.Model): id = models.IntegerField(blank=True, null=False, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = '"processing"."contractor"' forms.py class SearchForm(forms.Form): date1st = forms.DateField(required=False) date2st = forms.DateField(required=False) numberPayment = forms.CharField(required=False) numberPhone = PhoneNumberField(region='RU', required=False) #contractorName = forms.ModelChoiceField(queryset=Contractors.objects.values_list('name', flat='True'), required=False) status = forms.ChoiceField(choices=(('', '----'),("success", "success"), ("decline", "decline"), ("refund", "refund")), required=False) -
Name server for a virtual server (Ubuntu)
I have a Django project and Apache 2 web-server on Ubuntu server but it is a virtual server. I bought a domain and I want to point it to my virtual server. I tried adding their main name servers but it didn't work so what should I do now and how can find my virtual servers's name server -
Not able to fetch data from database GET /favicon.ico HTTP/1.1
I m building a website for grocery store(Pyshop) i have created ten items using sq-lite but when i m trying to retrieve names of products i m not able to do it. This is the Pyshop >>urls.py. In this i have added address of product path('products/', include('products.urls')), In settings.py i have also added 'products.apps.ProductsConfig' in installed apps. In this we have created 2 models. one is Product and second is offer.In Product we are storing name,price, stock and an url for image.In offer I have code,description and discount. i tried reading about favicon.ico error but i m not able to understand why this error occurs and how to resolve the problem. Product>>urls.py In urls.py of product i have added views addresss. from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] Products>>views.py In views i have created two function index and offer.As models.py is in the current directory thats why we r using.models.In index i m trying to get all the items in products and then display price and name. from django.shortcuts import render from .models import Product from django.http import HttpResponse def index(request): products = Product.objects.all() return render(request, 'index.html', {'Products': products}) def new(request): … -
How to create query in Django model for PST time zone if default time is UTC
I am using the Django model to store my order details and I enabled the timezone with UTC time so the order date stored in database is UTC time. then I am using a model query to output the last 30 days order quantity by datewise and it is working great and they give me order quantity datewise by UTC time. I need to how can I get the last 30 days order quantity by PST time using model query. Order.objects.filter( purchase_date__lte=datetime.today(), purchase_date__gt=datetime.today() - timedelta(days=30) ) .values("purchase_date__date") .annotate( amount_s=Sum("amount"), quantity_s=Sum("quantity") ).order_by("purchase_date__date") Above query give me the datewise order quantity in UTC time. what can I do get order quantity in PST time. -
Jquery to select a table row on click doesn't work
I'm trying to toggle the class "highlight" of a html table row on click using JQuery. The table is created using Django template language. The table works and shows up in my development server and the Jquery works on tables not created with Django template language. I don't get any errors when running the code, but it just doesn't do anything when i click on a table row. I'm not sure what The problem could be. HTML <style media="screen"> .highlight { background-color: yellow; color: white; } </style> <div class="table-responsive"> <table class="table table table-borderless" id="food_table"> <thead> <tr> <th>#</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td>{{ order.pk }}</td> <td>{{ order.Price }}</td> <td>{{ order.Description }}</td> </tr> {% endfor %} </tbody> </table> </div> JQuery $("#food_table tbody").on('click','tr',function() { $(this).toggleClass("highlight"); }); Dummy Data [ { "pk": 9, "Description": "Pizza", "Price": "88.00" }, { "pk": 10, "Description": "Steak", "Price": "130.50" }, { "pk": 11, "Description": "Coca Cola", "Price": "25.95" }, { "pk": 12, "Description": "Water", "Price": "15.00" } ] -
How to filter RawQuerySet in Django?
I have a request that is most likely not to be done via Djangor ORM, so I am making a raw SQL query. I have a search by time period and a few more parameters. How can I make a request to RawQuerySet to filter it? Like this: paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service', 'deal__service__contractor').filter( payment_date__range=[date1, date2],).order_by('-id') I tried to use filter() and extra(), but it doesn't work. My query: SELECT "processing"."transaction"."id", "processing"."transaction"."currency_id", "processing"."transaction"."deal_id", "processing"."transaction"."payment_source_id", "processing"."transaction"."payment_date", "processing"."transaction"."amount", "processing"."transaction"."status", "processing"."transaction"."context", "processing"."currency"."id", "processing"."currency"."iso_name", "processing"."currency"."minor_unit", "processing"."deal"."id", "processing"."deal"."service_id", "processing"."deal"."currency_id", "processing"."service"."id", "processing"."service"."contractor_id", "processing"."service"."name", "processing"."service"."description", "processing"."contractor"."id", "processing"."contractor"."name", "ps"."id", "ps"."payment_type_id", "ps"."source_details", "processing"."payment_type"."id", "processing"."payment_type"."name", "psc"."source_details" FROM "processing"."transaction" LEFT OUTER JOIN "processing"."currency" ON ("processing"."transaction"."currency_id" = "processing"."currency"."id") LEFT OUTER JOIN "processing"."deal" ON ("processing"."transaction"."deal_id" = "processing"."deal"."id") LEFT OUTER JOIN "processing"."service" ON ("processing"."deal"."service_id" = "processing"."service"."id") LEFT OUTER JOIN "processing"."contractor" ON ("processing"."service"."contractor_id" = "processing"."contractor"."id") LEFT OUTER JOIN "processing"."payer_payment_source" AS "ps" ON ("processing"."transaction"."payment_source_id" = "ps"."id") LEFT OUTER JOIN "processing"."payment_type" ON ("ps"."payment_type_id" = "processing"."payment_type"."id") LEFT OUTER JOIN "processing"."payer_payment_source" AS "psc" ON ("ps"."payer_id" = "psc"."payer_id") AND "psc"."payment_type_id" = 'bank_card_details' -
Showing fields of related m2o objects in django-admin
I have model Job which is shown using modelAdmin. And also I have stop model: class Stop(models.Model): ... job = models.ForeignKey(to=Job, ...) stop_number = ... ... Job can have from 2 to 3 stops. I've tried to show first and second stop names using: @admin.register(Job) class JobAdmin(admin.ModelAdmin): def stop_1(self, obj): stop = self.stop_set.objects.get(stop_number=1) return stop.name def stop_2(self, obj): stop = self.stop_set.objects.get(stop_number=2) return stop.name list_display = ('stop_1', 'stop_2', ...) But it does many SQL queries on each list view rendering and makes it way too slow. Is there a way to query needed info in single or just few queries? -
When receiver has been garbage collected in signal?
I try to use Signal in Django, when I read document about method connect signal, it have weak parameter as following: weak – Django stores signal handlers as weak references by default. Thus, if your receiver is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect() method. I don't know when local function has been garbage collected?