Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LEFT JOIN with Python-Django ORM
I have the following model in my Python-Django project and I want to join the object "id" with the object "script_id" and return the results. s_objects = S.objects.values('id','script') print(s_objects.query) j_objects = J.objects.values('script_id','name') print(j_objects.query) The SQL equivalent that I am trying to achieve would be: SELECT * FROM script LEFT JOIN job ON script.id = job.script_id WHERE job.id IS NULL; -
How to filtered list of record(groupby field) in such a way filtered list contains record from each group
Consider there is a list of recordsets. id name topic_id 1 hiii 1 2 hell 2 3 test 2 4 good 3 5 badg 4 6 byeo 4 Now I want 4 records in such a way that there is at least one record of each topic_id. It is possible through the loop, but if by default Django ORM providing such a mechanism? -
How do i validate reCAPTCHA V3 without PHP and receive a decoded response?
I am doing a django project, and i am trying to implement a reCAPTCHA V3 on my contact form. I am using a reCAPTCHA django module --> https://github.com/kbytesys/django-recaptcha3 Since i can't use PHP nor views.py file because the project uses django-CMS, i need to do the validation in javascript and return the score in the console for an example so i can see if it works (is this a security flaw?). -
How can I do to serialize with foreign key?
Hello I am trying to serialize some data from a database to json format. Here is my code : sports = Baseball.objects.filter(name=name) sports_json = serializers.serialize('json', sports) But the problem is the following : in the variable sports_json I have just the id of the foreign key... Is there a way to specify the field of the foreign key that I want ? I precise in my foreign key that I defined for instance ball I have some fields like the size, brand, color and I would like just to have only the size and the brand. Thank you for your help ! -
New line \n characters are missing when data sent through djnago restframework Response using model as dictionay
I am sending the data model which has TextField , all the '\n' characters are missing when i receive it in the browser. And not able to put it in the paragraph as same as database format. It is shown in both database and django shell. but not in the HTML response. I am trying to show a blog content in angular component. I have tried json.dumps to convert it into a string of json, I have a TextFeild in django model , with another foreign key as author, I need to display the content as it written by the user. -
How to debug Permission denied exception in Django?
I keep encountering a permission denied error when attempting to open a page in my django project. The error is: [Errno 13] Permission denied: 'C:\Users\chris\[projectname]\[appname]\templates' I have no idea why this error suddenly came up or why it is limited to this specific page. I would appreciate it if anyone point me in the right direction as to which things could be causing this error and how I would check whether it does. Please comment below if there is some specific code I could post to help solve this problem. I am not sure which part of the code would be helpful in this case. -
URL won't redirect to detailview pk Django
I have a simple project and made troubled fixing the redirection. The url is not redirecting to my statistics_detail.html. whenever i click it just adds the pk on the link but won't redirects here is my url.py: urlpatterns = [ ... re_path(r'^(?P<pk>\d+)/$', views.StatisticsDetailView.as_view(), name='detail'), ... ] views.py class StatisticsDetailView(DetailView): context_object_name = 'statistics_details' model = models.Statistics template_name = 'provision/statistics_detail here is also statistics_detail.html: {% extends 'base.html' %} {% block content %} <p>Statistics</p> <div class="container"> <table class="table"> <tr> <th>Name</th> <th>Mac ID</th> <th>Hours</th> <th>Date</th> <th>Status</th> </tr> {% for clients in object_list %} <tr> <td>{{ clients.name }}</td> <td>{{ clients.mac_add }}</td> <td>{{ clients.minutes_used|cut:".0" }}</td> <td>{{ clients.date }}</td> <td><a href="{{clients.id}}/">{{ clients.status }}</a></td> </tr> {% endfor %} </table> It is {% now "jS F Y H:i" %} </div> {% endblock %} As you can see on the screenshot below. nothing happens if i click the clients.status which supposedly redirects to statistics_detail.html Browser URL: http://127.0.0.1:8000/prov/blist/ After Click the status it would only add http://127.0.0.1:8000/prov/blist/2146/ but doesn't work -
One to One Choice Field Django
So I have a Plant Model and a Sensor Model. Between them is a One To One realationship. When I want to add a new Plant, I want the Form to show me only the 'unused' Sensors as choices(those who have no realtionship with a plant yet.). I have tried multiple ways but I cant't figure out how to make it work I have tried adding functionality to the AddPlant Form by checking all the sensors and adding the unused ones to a CHOICE tuple. After that I added a sensor ChoiceField with the CHOICE tuple as choices. It worked, but every time I wanted to add a new sensor to the database, I had to save the forms.py file to see the sensor being added to the Choices in the AddPlant form. class AddPlant(forms.ModelForm): class Meta: model = Plant fields = ( 'name', 'photo', 'type_plant', ) def __init__(self,CHOICES, *args, **kwargs): super(AddPlant, self).__init__(*args, **kwargs) self.fields['sensor'] = forms.ChoiceField(choices=CHOICES) class Sensor(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=13) photo = models.ImageField(upload_to=get_image_path, blank=True, null=True) sensor = models.OneToOneField(Sensor, on_delete=models.DO_NOTHING, null=True, blank=False,) type_plant = models.ForeignKey('TypePlant', on_delete=models.DO_NOTHING) status = models.IntegerField(null=True) def __str__(self): return self.name @login_required def add_plant(request): if len(Plant.objects.all()) >= len(Sensor.objects.all()): … -
Why after importing ModelAdmin in other app model disappears from main admin site?
So i want to use single ModelAdmin subclass in multiple places - firstly i want it registered in standard way (admin.site.register(some_model, some_modeladmin)) and then i want to import it to use in my custom admin site in custom view. After i import it, this model disappears on main admin site. Is there another option to do it or workaround? I know i can copy paste the same ModelAdmin to use in custom admin site but it's bad practice. class SomeAdminSiteConfig(AppConfig): name = 'some_admin_site' def ready(self): from someapp1.models import somemodel1 from someapp2.models import somemodel2 # Here i can't import AdminModel # As it makes model disappear from main site # from someapp1.admin import ModelAdmin1 class SomeAdminSite(admin.AdminSite): #here (in method) i want to access ModelAdmin1 ... -
How to use data obtained from a form in Django form?
I'm trying to create a form in Django using Django form. I need two types of forms. A form that collect data from user, do some calculations and show the results to user without saving the data to database. I want to show the result to user once he/she press button (calculate) next to it not in different page. A form that collect data from user, look for it in a column in google sheet, and if it's unique, add it to the column otherwise inform the user a warning that the data is not unique. Thanks -
Is there a more efficient way of annotating a field than SerializerMethodField?
I have the following code which annotates the Item.name that the ItemSale represents. It works and all but a GET on this view could call upwards of 200 ItemSale objects which, if I understand correctly, would also mean 200 queries just to get each ItemSales's Item.name? If so, I'm looking for a more efficient way of doing this, if any. ItemSale Serializer: class ItemSaleSerializer(serializers.ModelSerializer): item_name = serializers.SerializerMethodField() class Meta: model = models.ItemSale fields = ['quantity', 'price', 'item_name'] def get_item_name(self, obj): return obj.item.name Sale Serializer: class SaleSerializer(serializers.ModelSerializer): item_sales = ItemSaleSerializer(many=True, source='itemsale_set') class Meta: model = models.Sale fields = ('id', 'uid', 'dt_date', 'total', 'item_sales') I tried creating a custom manager for ItemSale and annotating the extra field through all() however it doesn't seem to get called since in this case, the list of ItemSales is being nested -
how to replace some characters of email address using * in python django
I am new in django. I have problem in replacing the some characters of string. I want some characters hidden in email address. so i want to replace some characters of email using *. email address: demo.cipher@gmail.com I want email address like demo*******@gmail.com I use replace function for replacing email address characters but isn't working. x = demo.cipher@gmail.com e = x.replace(x[5], '*') -
How to make prepopulated field with model relationship field?
I try to add prepopulated_fields at my admin class like this: class ProfileAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ('get_trainer_name',)} def get_trainer_name(self, obj): return obj.user.get_full_name() but got en error ERRORS: <class 'trainers.admin.ProfileAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'get_trainer_name', which is not an attribute of 'trainers.Profile'. models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', null=True) slug = models.SlugField() Also I tryed to make this another way - to override models save method : class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', null=True) slug = models.SlugField() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user.get_full_name()) super(Profile, self).save(*args, **kwargs) but it gave no result.. -
How to clear main processing lru_cache in celery task?
I use celery to deal some long time job; I use lru_cahe to cache some method which rely on the celery's result; So I must clear the lru_cache when the celery task is done.But I want the 'cache_clear' function doesn't work in celery work.How to fix this? -
How to restrict user not to see other user data in DRF ModelViewSet?
I've created a todo list API, which have user profiles. Each User profile can have Todo List. Now everything is working fine, but the issue here is one user can able to see other users data, but I want to restrict one user no to see other users todo list while am requesting a URL. models.py class TodoListItem(models.Model): """Todo List""" user_profile = models.ForeignKey('UserProfile', on_delete=models.CASCADE) todo_item = models.CharField(max_length=150) description = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) reminder_date = models.DateTimeField() def __str__(self): """Return the model as the string""" return self.todo_item views.py class TodoItemViewSet(viewsets.ModelViewSet): """Handles creating, reading, and updating profile Todo Items.""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.TodoItemSerializer queryset = models.TodoListItem.objects.all() permission_classes = (permissions.UpdateTodoItem, IsAuthenticated) def perform_create(self, serializer): """Sets the user profile to the logged in User.""" serializer.save(user_profile=self.request.user) serializers.py class TodoItemSerializer(serializers.ModelSerializer): """Serializer for Todo Items.""" class Meta: model = models.TodoListItem fields = ('id', 'user_profile', 'todo_item', 'description', 'created_on', 'reminder_date') extra_kwargs = {'user_profile': {'read_only': True}} permissions.py class UpdateTodoItem(permissions.BasePermission): """Allow users to update their own status.""" def has_object_permission(self, request, view, obj): """Check user is trying to update their own status.""" if request.method in permissions.SAFE_METHODS: return True return obj.user_profile.id == request.user.id Unexpected Result: [ { "id": 1, "user_profile": 1, "todo_item": "Todo Item 1", "description": "Sample todo item 1", "created_on": … -
How to upload a file and return JSON response in same click
My code for upload in views.py is def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] timestr = time.strftime("%Y%m%d-%H%M%S") fs = FileSystemStorage() uploaded_file.name = timestr+"_"+uploaded_file.name name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'upload.html', context) And my HTML webpage looks like this: I am building an API and want to return JSON response when a user clicks on the upload button after choosing their file. I am using Django and new to web development. -
SQLite objects created in a thread can only be used in that same thread with Django 2.2.2 and ipdb
I updated my Django project to version 2.2.2 and now when I call to ipdb for debugging, the server tell me that error. If I go back to Django 2.2.1, the error disappears. System check identified no issues (0 silenced). June 06, 2019 - 08:19:36 Django version 2.2.2, using settings 'laserapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. > /home/lynde/public_html/laserapp/gestion/views.py(192)get_context_data() 191 import ipdb; ipdb.set_trace() --> 192 context = super(ResumeOrderCodeView, self).get_context_data(**kwargs) 193 try: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 585, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 570, in start_django reloader.run(django_main_thread) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 288, in run self.run_loop() File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 294, in run_loop next(ticker) File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 334, in tick for filepath, mtime in self.snapshot_files(): File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 350, in snapshot_files for file in self.watched_files(): File "/home/lynde/public_html/env/laser/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in watched_files … -
How to set initial in Django forms ModelChoiceField
I'm trying to set initial value for ModelChoiceField but its not getting set I tried setting initial but it didn't helped either self.fields['query'].initial = Queries.objects.filter(category=category, query='APPLY ALL').values('id') Actual code : files = forms.ModelChoiceField(queryset=Document.objects.all()) query = forms.ModelChoiceField(queryset=Queries.objects.all(), required=False) class Meta: model = Categories fields = ('category','file_choice', 'files', 'query') def __init__(self, *args, **kwargs): super(ChoiceForm, self).__init__(*args, **kwargs) self.fields['files'].queryset = Document.objects.none() self.fields['query'].queryset = Queries.objects.none() if 'category' in self.data: try: category = (self.data.get('category')) self.fields['files'].queryset = Document.objects.filter(categories=category) self.fields['query'].queryset = Queries.objects.filter(category=category) self.fields['query'].initial = Queries.objects.filter(category=category, query='APPLY ALL').values('id') After setting initial i'm getting none at the output. -
Update form field from API by KeyUP
I am not sure if my caption is correct but I'll try to explain. forms.py: class FlightsForm(forms.Form): originplace = forms.CharField(label='Origin', max_length=30) destinationplace = forms.CharField(label='Destination', max_length=30) outboundpartialdate = forms.DateField(label='Outbound Date', widget=forms.SelectDateWidget(empty_label="Nothing")) flights.html {% load static %} <!DOCTYPE html> <html> <head> <title>Search flights</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-somethingisenteredhere=" crossorigin="anonymous"></script> <script src={% static "flights/js/locations.js" %}></script> </head> <body> <div> <form method="POST"> <table > {% csrf_token %} {{form.as_table}} <tr><td><input type="submit" name="Search" value="Search"></td></tr> </table> </form> </div> <div> {% for quote in data.Quotes %} <div>{{data.Carriers.0.Name}}</div> <div>{{quote.OutboundLeg.OriginId}} -> {{quote.OutboundLeg.DestinationId}}</div> <div>{{quote.OutboundLeg.DepartureDate}}</div> <div>Price: {{quote.MinPrice}}{{data.Currencies.0.Symbol}}</div> {% endfor %} </div> <div id="options"></div> </body> </html> Now what I need to do is when I click "originplace" or "destinationplace" it should show me on "Key-up" based on entered letters over API all available flight countries below those fields and when I click on one country it fill "originplace" or "destinationplace" with country code. And it works for "originplace" but not for "destinationplace" so I am not sure what have I done wrong: This is my javascript code for search available locations: locations.js $( document ).ready(function() { var origin = $("#id_originplace"); var destination = $("#id_destinationplace"); origin.keyup(function(){ pretrazi(origin); }); destination.keyup(function(){ pretrazi(destination); }); }); function pretrazi(element){ $.ajax({ url: "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-GB/", type: "get", //send it through get method beforeSend: function(request) { … -
UpdateAPIView not raising 404 when not exists in Django REST Framework
I'm using Django 2.2 and Django REST Framework. I have an endpoint to update existing record, extending UpdateAPIView class FakeOrderPaymentView(generics.UpdateAPIView): serializer_class = OrderPaymentSerializer permission_classes = (IsAuthenticated,) def get_object(self): log.debug(self.request.data) order_id = self.request.data.get('order_id', None) if not order_id: raise Http404 return self.serializer_class.Meta.model.objects.filter(pk=order_id).first() def perform_update(self, serializer): return serializer.save() def update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = self.perform_update(serializer) instance_serializer = OrderListSerializer(instance) return Response(instance_serializer.data) and the OrderPaymentSerializer class OrderPaymentSerializer(serializers.ModelSerializer): order_id = serializers.IntegerField(write_only=True, required=False) order_status = serializers.CharField(write_only=True, required=True) class Meta: model = Order fields = [ 'order_status', 'order_id' ] def create(self, validated_data): log.debug(validated_data) return super().create(validated_data) def update(self, instance, validated_data): status = validated_data.pop('order_status', None) order_id = validated_data.pop('order_id', None) instance.status = Order.STATUS.COMPLETED return super().update(instance, validated_data) The order_id and order_status are not model fields. They are just to carry data. If order_id is not in the PUT data or order_id is blank. It should raise 404 response. But, it's not calling get_object() method before update(). Also, even if I pass order_id in the PUT data. The perform_update() method is calling serializer's create() method instead of update() method. When is serializer's update() method called? Why get_object() is not calling automatically? -
django rest framework filter on foregin table
i'm writing API in django rest framework, i want to do a filter on a foreign key table. want to do a filter in the scripts_details table as per the user. since scripts_details is not having user, i am trying to filter in the script tables. but it is not happening. i tired return ScriptDetails.objects.filter(script=scriptid, script.user=self.request.user) Models.py class Scripts(models.Model): tutorial = models.OneToOneField(TutorialDetail) language = models.ForeignKey(Language) status = models.BooleanField(default=False) data_file = models.FileField(upload_to='scripts',blank=True) user = models.ForeignKey(User,related_name='user_id') class ScriptDetails(models.Model): cue=models.TextField() narration=models.TextField() order=models.PositiveIntegerField() script=models.ForeignKey('Scripts', on_delete = models.CASCADE) serializer.py class ScriptsDetailSerializer(serializers.ModelSerializer): class Meta: model=ScriptDetails fields=('cue','narration','order','script') views.py class ScriptsDetailsList(generics.ListCreateAPIView): serializer_class=ScriptsDetailSerializer def get_queryset(self): scriptid = self.kwargs.get('scriptid') return ScriptDetails.objects.filter(script=scriptid) urls.py url(r'^api/scriptsdetails/(?P<scriptid>[0-9]+)/', views.ScriptsDetailsList.as_view()) -
solve exception:no reverese match found
i got the error NoReverseMatch at /admin/myapp/leavdb11/6/change/ Reverse for 'emails' with no arguments not found. 1 pattern(s) tried: ['employee/emails/(\d+)/'] -
Why Debug False does not work on Ubuntu server?
I set Debug = False on my Django project on server on Ubuntu but it still shows exceptions. I fulfilled command sudo service nginx restart but nothing changed. Can somebody help? -
Add django form without refreshing the page using ajax
I am trying to implement a django model-form to add a new item to the category table from add product form using html modal pop up and the code works fine but every time I add new item the whole page refreshes. Here I want the model-form to work asynchronously without refreshing the page using javascript(ajax). How can I do this? models.py class Category(models.Model): title = models.CharField(max_length=250) class Product(models.Model): name = models.CharField(max_length=250) category = models.ForeignKey(Category,on_delete=models.CASCADE) cost_price = models.FloatField() sell_price = models.FloatField() quantity = models.IntegerField() forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class AddCategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' views.py def add_product(request): categories = Category.objects.all() if request.method == 'POST': product_form = AddProductForm(request.POST or None) if product_form.is_valid(): product = product_form.save(commit=False) product.save() return redirect('add_product') else: return HttpResponse(product_form.errors) else: product_form = AddProductForm() return render(request,'add_product.html',{'product_form':product_form, 'categories':categories}) def ajax_add_category(request): if request.method == 'POST': category_form = AddCategoryForm(request.POST or None) if category_form.is_valid(): category = category_form.save(commit=False) category.save() return redirect('add_product') else: category_form = AddCategoryForm() return render(request,'add_product.html',{'form':category_form}) html template <label>Product Name</label> <input type="text" name="name" class="form-control" placeholder="Item Name..." maxlength="200" required id="id"> <label>Category</label> <div class="form-group"> <select name="category" class="form-control mr-3" style="width:50%; display:inline;" required id="id_category"> {% for category in categories %} <option value="{{category.id}}">{{category.title}}</option> {% endfor %} Add New … -
How to trigger a <div> on a webpage by click of a button on the webpage using django?
I am making a webpage where there are multiple buttons and whenever a button is clicked, an area displays the associated thing with the button. How can I trigger the button using GET and POST request and block so that on click of the button, that element is displayed there? I tried using GET and POST request but I am getting some errors. I can use some help if somebody provide insight on it.