Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Count annotations in Django filtering causing ProgrammingError
I am running a search page on a model which has two linked models with a ManyToMany (ForeignKey) relationship. class Session(models.Model): ... fields ... class Tuition(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) ... class Housing(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) ... I would like to filter on aggregate Counts of these two models. For Housing it's just a simple Count, I want to filter by if there is housing available for that session (aka if housing_count__gt=0) queryset.annotate(housing_count=Count('housing', distinct=True)) For Tuition I'm including a filter in the Count, because I want to account for both those where the price is listed and those where it's null. And thus, I want to again filter for sessions where only at least tuition with that price (or one null price) is linked. (tuition_count__gt=1) queryset = queryset.annotate(tuition_count=Count('tuition', filter=Q(Q(tuition__price__lte=max_tuition_passed) | Q(tuition__price__isnull=True)), distinct=True)) **However, I keep running into an issue, **seemingly in particular with the tuition_count (I've tried commenting out one/both at a time). ProgrammingError at /search/programs/summer-intensives function count(integer, boolean) does not exist LINE 1: ...ECT COUNT(*) FROM (SELECT "session"."id" AS Col1, COUNT(DIST... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I've tried … -
pgAdmin Table not showing in database after successfull migration
I am trying to create a REST API using psql and Django , i've reached the stage of applying migrations to add tables to my database, these migrations are successfull but when i open pgadmin to view my database their are no tables no matter how many times i refresh. Below is how i run the migrations: python manage.py makemigrations ExampleApp python manage.py migrate ExampleApp Any help would be much appreciated as I am completely lost at this stage :) -
Choose how to order Django Model choices
When displaying the below choices, I want to be able to order them as follows Preparation, Review, Update, Finalised and Completed. Right now, they are ordered alphabetically. The below is a simple model: class Choice(models.Model): status_choices = [ ("", "Select Current Status"), ("Preparation", "Preparation"), ("Review", "Review"), ("Update", "Update"), ("Finalised", "Finalised"), ("Completed", "Completed"), ] current_status = models.CharField( max_length=32, choices = status_choices, default = "Select current status", ) class Meta: ordering = ["current_status"] I read that assigning a number in the Tuple can allow them to be ordered, which I tried per the below: status_choices = [ ("", "Select Current Status"), ("1", "Preparation"), ("2", "Review"), ("3", "Update"), ("4", "Finalised"), ("5", "Completed"), ] However, this made no difference. forms.py listed below: class TaskForm(ModelForm): class Meta: model = Choice fields = [ 'current_status', ] widgets = { 'current_status' : forms.Select(attrs={'placeholder':'Select Current Status', 'class':'table_data_request_status'}), } I feel like this should be very simple but maybe not. Any help would be greatly appreciated. I have searched previous questions but no luck. -
Creating a separate comments app for a ticket app. Keep getting NoReverseMatch error
I'm creating a separate comments app for a ticket app project. How do I get the ticket pk from the Ticket model into get_absolute_url method that's within my Comment model? These are my models ticket models.py class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('ticket-detail', kwargs={'pk': self.pk}) comment models.py class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets:ticket-detail', kwargs={'pk': self.ticket_id}) -
accordion items in jinja2 flaks for loop collapse and show together and not independently
my accordion items do not expand separately when one is clicked on. They either both show their content or both remain close. I tried interactive IDs but this did not work. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ study.uid }}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{{ study.uid }}" aria-expanded="true" aria-controls="collapse{{ study.uid }}"> {{ study.uid }} </button> </h2> <div id="collapse{{ study.uid }}" class="accordion-collapse collapse" aria- labelledby="heading{{ study.uid }}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} is it maybe something to do with jquery and bootstrap not being the same version? Inspecting the code shows that each accordion item in the loop has a different ID...enter image description here -
Heroku "Application error" on a Django/React app
I'm currently working on a to do list project for my studies and I was able to chose the technologies involved. I decided to use Django, React, MongoDB for the app and Heroku for the hosting. I had previous experience with React MongoDB and NodeJS and managed to host the app on heroku very easily. However with this new project I always get an "Application Error" whenever I try to access the website. I struggled to find up to date information on how to properly host a Django/React app on Heroku and none of the answers I found solved my problem. What concerns me the most is that the deployment log do not show any major issue during the build process : > Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 8 threads Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 356 bytes | 356.00 KiB/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: … -
django form not submitting when rendering specific fields in template
I have an UpdateUserForm: class UserUpdateForm(UserChangeForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) username = forms.CharField(max_length=100, widget=forms.TextInput()) last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'last_login', 'date_joined') def update_user_notification(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if self.is_valid(): update_user_notification_task.delay(email, username) and a UserUpdate view: class UserUpdate(generic.UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/update_user.html' def get_object(self): return self.request.user def form_valid(self, form): instance = form.save() form.update_user_notification() return HttpResponseRedirect(reverse('user_detail', args=[str(instance.pk)])) I originally wrote this form in the template as {{form.as_p}} and it worked, but there were some things I wanted to fix: <h1>Update Information...</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <button>UPDATE</button> </form> <br></br> <a href="{% url 'user_detail' user.pk %}">Back</a> <a href="/">Home</a> {% endblock %} Rendered as this: I wanted to get rid of those password related things at the bottom so I changed my form to: <form method="POST"> {% csrf_token %} <p><label>{{form.email.label}}: </label>{{form.email}}</p> <p><label>{{form.username.label}}: </label>{{form.username}}</p> <p><label>{{form.first_name.label}}: </label>{{form.first_name}}</p> <p><label>{{form.last_name.label}}: </label>{{form.last_name}}</p> <button>UPDATE</button> </form> This worked on the frontend, but now my form isn't submitting. When I click update, the page looks as if it's … -
How to populate model with having model django?
I have model People: with name, phone email, address fields using Django's management commands I want populate Contact model with the same fields command file: from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Sorting leads ' def handle(self, *args, **kwargs): pass 1.Multiple People with the same name and phone number should be merged together, so the resulting Contact contains all emails and addresses from merged Leads. 2. Multiple People with the same name, but different phone number and e-mail should be saved as separate contacts How have I do it ? Should I do with raw sql or there is better solution. -
Django ModelForm DateField value render
models.py class MyModel(models.Model): date = models.DateField() views.py if request.method == 'GET': instance = MyModel.objects.get(pk=pk) form = MyModelForm(instance=instance) return render(request, 'update.html', context={'form': form}) update.html <input type="date" name="date" value="{{ form.date.value.isoformat }}" /> Works fine. But in POST method if the form is not valid I rerender the template with errors and I want to render values got from POST data. views.py if request.method == 'POST': instance = MyModel.objects.get(pk=pk) form = MyModelForm(request.POST, instance=instance) form.is_valid(): pass return render(request, 'update.html', context={'form': form}) But then form.date.value is in isoformat already (because it came from POST) and the template's code stops render date value properly. How to fix it? The solution I have found is value="{{form.start_date.value.isoformat|default:form.start_date.value}}" but I don't think it is good. -
Django Forms Show Extra Categories For Users Part Of Group
I'd like to show these categories below additionally with users who have the blogger category. The current issue is.. For a blogger user it's only showing blogger categories when it should be showing all For a normal user it's showing blogger categories when it should only be showing the original 3 forms.py class PostCreateForm(ModelForm): class Meta: model = Post fields = [ "title", "category", "associated_portfolios", "body", ] exclude = ('allow_comments',) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) blogger = User.objects.filter(groups__name='blogger').exists() print("Current User:", user) print("Blogger User:", blogger) super(PostCreateForm, self).__init__(*args, **kwargs) self.fields['category'].choices = ( ("Watchlist", "Watchlist"), ("Lesson/Review", "Lesson/Review"), ("General", "General"), ) if User.objects.filter(groups__name='blogger').exists(): self.fields['category'].choices = ( ("Analysis", "Analysis"), ("Milestone", "Milestone"), ("Features", "Features"), ("Tutorials", "Tutorials"), ("Careers", "Careers"), ("Community", "Community"), ) -
How to model complex left join Django
I have two Django models that have a relationship that cannot be modelled with a foreign key class PositionUnadjusted(models.Model): identifier = models.CharField(max_length=256) timestamp = models.DateTimeField() quantity = models.IntegerField() class Adjustment(models.Model): identifier = models.CharField(max_length=256) start = models.DateTimeField() end = models.DateTimeField() quantity_delta = models.IntegerField() I want to create the notion of an adjusted position, where the quantity is modified by the sum of qty_deltas of all adjustments where adj.start <= pos.date < adj.end. In SQL this would be SELECT pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, CASE WHEN Sum(qty_delta) IS NOT NULL THEN pos_unadjusted.qty + Sum(qty_delta) ELSE qty END AS qty, FROM myapp_positionunadjusted AS pos_unadjusted LEFT JOIN myapp_adjustment AS adjustments ON pos_unadjusted.identifier = adjustments.identifier AND pos_unadjusted.timestamp >= date_start AND pos_unadjusted.timestamp < date_end GROUP BY pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, Is there some way to get this result without using raw sql? I use this query as a base for many other queries so I don't want to use raw sql. I've looked into QuerySet and extra() but can't seem to coerce them into having this precise relationship. I'd love for position and PositionUnadjusted to have the same model and same API with no copy-pasting since right now updating them is a lot of copy pasting. -
Getting NOT NULL CONSTRAINT from both views using django
I have an app that displays a folder which also allows you to create a subfolder within that folder. Within both the folder and the subfolder, you can upload files. Whenever I try to do that, I get the NOT NULL CONSTRAINT error. If I try uploading a file in the parent folder i get NOT NULL constraint failed: documents_document.subfolder_id and if I try uploading a file in the subfolder I get NOT NULL constraint failed: documents_document.folder_id. parent folder detail view @login_required @group_required('Document Supervisor') def folder_detail(request, pk): folder = Folder.objects.get(id=pk) documents = Document.objects.filter(folder=folder) form = DocumentForm() subfolders = SubFolder.objects.filter(folder=folder) if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.folder = folder form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() messages.success(request, "Document added successfully!") return redirect(f"/documents/folder/{folder.id}") context = { "folder": folder, "documents": documents, "form": form, "subfolders": subfolders, } return render(request, "documents/folder_detail.html", context) subfolder view @login_required @group_required('Document Supervisor') def subfolder_detail(request, pk): sub = SubFolder.objects.get(id=pk) documents = Document.objects.filter() form = DocumentForm() if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.sub = sub form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() … -
Selenium,Django, On Ubuntu 20.04 digital ocean VPD
I have created the web scraper and integrated it with Django. Everything is working perfectly fine. Now I want to host that Django app with webscraper on the VPS so that he can access it anywhere. I am using gunicorn and nginx too. I tried that Django app with webdriver.remote() using seleniumgrid its working fine on my normal windows environment, but as soon as I put it on my ubuntu vps it works only in half of cases - like all my Django stuff is accessible and operational, but when my django calls the scraper, it just passes without any response. def chromedriver_setup(): user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36' # proxies = proxies = [{"_id":"62cd1bf852694154bb14f2e7","ip":"178.32.148.251","anonymityLevel":"elite","asn":"AS16276","city":"Gravelines","country":"FR","created_at":"2022-07-12T07:00:08.515Z","google":True,"isp":"OVH SAS","lastChecked":1657848951,"latency":5.13,"org":"MICHOTTE Maxime","port":"8080","protocols":["socks4"], "speed":37,"updated_at":"2022-07-15T01:35:51.569Z" },{"_id":"60d613cdce5b3bb0e932edce","ip":"64.227.62.123","port":"80","anonymityLevel":"elite","asn":"AS14061","city":"Santa Clara","country":"US","created_at":"2021-06-25T17:35:09.953Z","google":True, "isp":"DigitalOcean, LLC","lastChecked":1657847332,"latency":153,"org":"DigitalOcean, LLC","protocols":["http"], "speed":306,"updated_at":"2022-07-15T01:08:52.862Z" ,"upTime":99.98473981382573,"upTimeSuccessCount":6552,"upTimeTryCount":6553}] # random_ip = random.choice(proxies) # PROXY = str(random_ip["ip"] + ":" + random_ip["port"]) option = webdriver.ChromeOptions() option.add_argument("--headless") option.add_argument(f'user-agent={user_agent}') option.add_argument("--window-size=1920,1080") option.add_argument("--start-maximized") option.add_argument("--disable-gpu") # # option.add_argument('--proxy-server=%s' % PROXY) option.add_experimental_option("excludeSwitches", ["enable-automation"]) option.add_experimental_option('useAutomationExtension', False) option.add_argument("--disable-blink-features=AutomationControlled") option.add_experimental_option("detach", True) print("chrome driver setup passed") driver = webdriver.Remote( command_executor='192.168.72.1:4444', desired_capabilities = DesiredCapabilities.CHROME, options=option, ) return driver Is there any way I can solve that issue or test i..? -
AttributeError: type object ' ' has no attribute 'object'
I am working on REST API and i get an error saying "AttributeError: type object 'Project' has no attribute 'object'" when trying to access http://127.0.0.1:8000/projects/ here is my files : --> views.py: from django.http import JsonResponse from .models import Project from .serializers import ProjectSerializer def project_list(request): drinks = Project.object.all() serializer = DrinkSerializer(projects, many=True) return JsonResponse(serializer.data) --> models.py from django.db import models class Project(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) def __str__(self): return self.name + ' ' + self.description --> urls.py from django.contrib import admin from django.urls import path from projects import views urlpatterns = [ path('admin/', admin.site.urls), path('drinks/', views.drink_list), ] -
Django tests suddenly failing for no apparent reason
I have a django project with hundreds of unit tests and after a big update that added about 50 more tests, all the project's tests that creates an instance of a specific model are failing with the following error message: Traceback (most recent call last): File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File ".../venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. During handling of the above exception, another exception occurred: File ".../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1145, in execute_sql cursor.close() File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 83, in close while self.nextset(): File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 137, in nextset nr = db.next_result() MySQLdb._exceptions.OperationalError: (2006, '') The update did not change … -
Got Errno 13 when trying to save image with Pillow [Python, Django]
Got [Errno 13] when trying to save images using Pillow. Exact error is: PermissionError: [Errno 13] Permission denied: 'C:/Users/django/PycharmProjects/django/csvs/photos/blah-summer-jean\cropped-788x1000'. My code is below: from PIL import Image from blah import settings from django.core.files.storage import default_storage from blah.storage_backends import MediaStorage import os app_storage = None image_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean' cropped_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean/cropped-788x1000' if settings.DEBUG: app_storage = default_storage else: app_storage = MediaStorage def crop_image(image): try: img = Image.open(image) width, height = img.size if width <= 788 and height <= 1000: pass else: xcenter = img.width / 2 ycenter = img.height / 2 x1 = xcenter - 488 y1 = ycenter - 600 x2 = xcenter + 488 y2 = ycenter + 600 image_to_crop = img.crop((int(x1), int(y1), int(x2), int(y2))) output_size = (788, 1000) final_image = image_to_crop.resize(output_size) img.close() return final_image except AttributeError: pass except Exception as e: raise e for each_image in os.listdir(image_dir): cropping = crop_image(os.path.join(image_dir, each_image)) if not os.path.exists(cropped_dir): os.mkdir(cropped_dir) cropping.save(os.path.join(cropped_dir, each_image), 'jpeg') -
Uploading Cyrillic files in Django
Good afternoon. I am writing share for a corporate portal. I ran into such a problem that after downloading files with Cyrillic, I try to download them, and Django gives a path error urls 404 the path to the file was not found. Tell me where I'm wrong. My models.py: from django.db import models from datetime import datetime from django.contrib.auth.models import User def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.owner.id, instance.name) class DirectoryItem(models.Model): name = models.CharField(max_length=200, default="New Folder", blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) # a parent folder of null/blank would indicate a root folder. # A users root folder is created upon registration date_created = models.DateTimeField(default=datetime.now) is_recycled = models.BooleanField(default=False) # auto_now: updates on changes. date_recycled will be last change # (Improve - create custom save function) date_recycled = models.DateTimeField(auto_now=True) is_public = models.BooleanField(default=False) is_shared = models.BooleanField(default=False) class Meta: abstract = True class Folder(DirectoryItem): parent_folder = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class File(DirectoryItem): parent_folder = models.ForeignKey(Folder, on_delete=models.CASCADE) file_source = models.FileField(upload_to=user_directory_path) file_type = models.CharField(max_length=20) def __str__(self): return self.name My views.py , the function responsible for downloading the file: def folders(request, folder_id): requested_folder_id = folder_id cur_user_id = request.user.id requested_folder = Folder.objects.get(id=requested_folder_id) # Is it the users folder? if (requested_folder.owner.id != cur_user_id): # Does … -
Python Django always passes id 1 on ForeignKey with to_field
I'm new to Django and trying to create a small application that shows scanned data from virtual machines that are inserted in a table named HostsFixDataScans. To access the scanned data in HostsFixDataScans via the Hosts model, I defined a ForeignKey with to_field. But unfortunately, the data returned by the linked HostsFixDataScans are wrong. I checked the SQL statements and when requesting the HostsFixDataScans table, not the id of the Host is used, but always 1. My domain = models.ForeignKey(Domains, on_delete=models.CASCADE) definition which does not use to_field works correctly. I'm pretty sure, I have a misunderstanding of the definition of this relationship. Maybe you could give me some hints how to solve the problem? Many thanks in advance! Here are the shortened definitions of the models: class Os(models.Model): operatingsystem = models.CharField(max_length=32) lsbdistcodename = models.CharField(max_length=32) lsbdistrelease = models.CharField(max_length=32, db_collation='ascii_bin') lsbmajdistrelease = models.IntegerField() remarks = models.CharField(max_length=256, blank=True, null=True) class HostsFixDataScans(models.Model): host_id = models.PositiveIntegerField(primary_key=True, unique=True) scan_id = models.PositiveIntegerField() os = models.ForeignKey(Os, on_delete=models.CASCADE) class Hosts(models.Model): hostname = models.CharField(max_length=256) domain = models.ForeignKey(Domains, on_delete=models.CASCADE) is_virtual = models.PositiveIntegerField(blank=True, null=True) os = models.ForeignKey(HostsFixDataScans, to_field='host_id', on_delete=models.CASCADE) -
How do I port Django's ModelMultipleChoiceField widget to reactjs?
This is the widget I'm talking about: https://docs.djangoproject.com/en/4.0/ref/forms/fields/#modelmultiplechoicefield Here's a picture of it: https://i.stack.imgur.com/2tZhv.png Rendering it statically and preserving the style was easy, but I'm not sure how to do that dynamically, so that I'm able to dynamically feed it a list of input and be able to submit or change it or use the provided search bar. -
protect SQL injection on django Rest API
For penetration testing purpose, I am tring sql-injection to my Django Rest API,And I can successfully take schema , table and rows information by SQLmap. I was try several times,It was just simple API. I was create function based view, also a class base view, I was try with cursor and also try ORM.raw query try with parameterize. but every time I can injected sql by SQLMAP. I can't believe, how it happens, but I see result in my implementation. I am sure that I follow proper way. Please suggest my , how can I protect all type of API, which url have params. -
Django Rest Framework Viewset Filter By Value
Let's say I have a DRF viewset like so class SecretViewset( viewsets.ModelViewSet, ): queryset = Secret.objects.all() serializer_class = SecretSerializer @action(methods=['GET'], detail=True) def name(self, request, pk=None): secrets = Secret.objects.filter(name__contains=pk) return Response(self.get_serializer(secrets, many=True).data) I want to be able to search via a name in the URL. So /api/secrets/name/NAMEHERE/ However, because ModelViewset implements mixins.Retrieve, it returns a 404 because it searches /api/secrets/ID/ first and doesn't find it, therefore throws a 404. What would the proper way be to go about adding the ability to search by name as described above? Edit Adding my urls conf from .Secret.viewsets import SecretViewset router = routers.SimpleRouter() router.register(r'^api/secrets', SecretViewset, 'secrets') # Later on, router gets imported and added on via `urlpatterns += router.urls` -
Django celery with redis is executing same task multiple times
I'm trying to creating a background task with Django celery and Redis as broker. this task is being sent from models when model post save. But the problem is that, the same task is getting executed 1000 of times (other debug or add task are working fine). i have already tried this method but this didn't resolve the issue. Please find the below codes for your reference and help to resolve. Thanks in advance. models.py from django.db.models.signals import post_save from django.dispatch import receiver from student.tasks import create_student_subject_tryout_result, add @receiver(post_save, sender=TryoutSubmission, dispatch_uid='create_student_subject_tryout_result') def result_calculation(sender, instance, **kwargs): if instance.status == 'C': print('Calculating result') create_student_subject_tryout_result.delay(instance.student.id, instance.tryout.id) celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eec.settings') app = Celery('eec') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_transport_options = {'visibility_timeout': 3600} . app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py from celery import shared_task import tryout.models @shared_task(bind=True) def create_student_subject_tryout_result(self, student_id, tryout_id): tryout_submission=tryout.models.TryoutSubmission.objects.get( student_id=student_id, tryout_id=tryout_id ) tryout_questions = tryout_submission.tryout.tryoutquestion_set.all().count() answered_qs = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_answered=True).count() correct_ans = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_correct=True).count() tryout_submission.total_questions = tryout_questions tryout_submission.answered_questions = answered_qs tryout_submission.correct_answers = correct_ans tryout_submission.total_time = tryout_submission.end_time - tryout_submission.start_time tryout_submission.save() return "Result created" settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' -
Why am I getting a IntegrityError at, null value in a column that doesn't exists... Django
I am trying to hit an external api, when a user submits a form. I am using Django and Postgresql My Model class League_Mod(models.Model): host = models.CharField(max_length=50) Espn_League_Id = models.IntegerField(unique = True) Espn_S2 = models.CharField(max_length=3000) Espn_Swid = models.CharField(max_length=300) bigdata = models.JSONField(default=dict,null=True) My Serializer class Meta: model = League_Mod fields = ['host', 'Espn_League_Id','Espn_S2','Espn_Swid','bigdata'] Views where Owners is a large dictionary. league_data = { 'host' : request.data['host'], 'Espn_League_Id' :request.data['Espn_League_Id'], 'Espn_S2' : request.data['Espn_S2'], 'Espn_Swid' : request.data['Espn_Swid'], 'bigdata' : Owners } serializer = LeagueSerializer(data=league_data) print(serializer) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) my print serializer runs, and prints the data correctly. But I get an error: integrityError at /wel/ null value in column "hello" of relation "api_league_mod" violates not-null constraint DETAIL: Failing row contains (11, JPFL, 216415, AEAylLD7uSQQ7%2BenPr6av1H%2Fx0Hqbbpn8Jvr91ngxM1ll5ynO685mhN%2BSu..., {D19D67CA-C981-4CA2-8463-AF4111D2E8E2}, {"Person1": {"2010": [0, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6,..., null). I am very unclear where the column hello is... and there is no relation to api_league_mod Model, so don't quite understand why my serializer is returning unvalid Any insight would be appreciated. Thanks! -
showing a field of multiplke choises in django admin
In my django admin I'm trying to show a field of my model which may has multiple values (like a list). Here's my definition of the field in models.py related_countries = CountryField( multiple=True, blank=True ) So when I create a model in the database, what I got as the value of the field is something like AL,AS Then for my admin page, I didn't put it in the list_display because I don't want it to be shown at the page where all the records of this models is printed. I want it to be shown only when I click one of the record and check the detail of this record. So when I'm at the page that shows everythhing, it works well. Also, the record cannont be modified on the admin page so I have this function on my admin code: def has_change_permission(self, request: HttpRequest, obj=None) -> bool: return False And there comes the issue: When I enter the page for the detail of the record, I got a TypeError at XXX unhashable type: 'list' and I'm pretty sure it comes from the field related_countries. Cause when I removed the function to make it possible to modify the record, anything … -
Render Excel templates
I'd like to have the ability to render Excel template files: and not create Excel files programmatically. There is a lib Templated-docs. But the templates themselves must be in on of the OpenDocument formats: .odt, .ods, .odp or .odg. Those templates are rendered to excel futher. This fact affects on formatting features when rendering to Excel. Is there any possibility to render directly to Excel file template?