Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send full image url in DRF
I am trying to get the full image URL in the API in DRF i am trying to use build_absolute_uri but i keep receiving the error The 'image' attribute has no file associated with it. the serializer.py: class VesselInfoSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, Vessel): request = self.context.get('request') image_url = Vessel.image.url return request.build_absolute_uri(image_url) vessel_component_count = serializers.IntegerField( source='vessel_components.count', read_only=True ) vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) class Meta: model = Vessel fields = '__all__' models.py: class Vessel(models.Model): name = models.CharField(max_length=255) imo = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='vessel_image') def __str__(self): return self.name the view: @api_view(['GET']) def getVesselInfo(request): vessels = Vessel.objects.all() vSerializer = VesselInfoSerializer( vessels, many=True, context={"request": request}) return Response(vSerializer.data) -
The CSV script in Django does not see the d path of the file - [Errno 2] No such file or directory
Why is my Pytnon/Django script unable to read the file path and retur. How to correctly set the path from a saved file? [Errno 2] No such file or directory: '/media/file_hll8NoJ.csv Views.py if form.is_valid(): cd = form.cleaned_data if cd['file']: obj = FileUpload() obj.file = cd['file'] obj.save() with open(obj.file.url) as f: reader = csv.reader(f) for row in reader: _, created = UserEmail.objects.get_or_create( owner=obj_instance, email=row[0], middle_name=row[2], ) Path is correct and if I open http://127.0.0.1:8000/'/media/file_hll8NoJ.csv loacal all works fine (I can see my csv file) -
How to list overdue objects?
I want to create a query that shows which user has how many overdue (out of date) missions. query_overdue = Case.objects.select_related('last_changed_by').values('due_date').order_by('assigned_to').annotate( name=F('assigned'), due=F('due_date'), ) This query shows every object but I want to filter it with not none value and overdue. How can I do it? -
İ can't pull data with JavaScript
I want to pull data using JavaScript and show it in console. I don't know what I did wrong. main.js // ADD TO CART $("#addToCartBtn").on('click',function(){ var _qty=$("#productQty").val(); var _productId=$(".product-id").val(); var _productName=$(".product-name").val(); console.log(_productId,_productName,_qty); }); I am using django framework to write backend detail.html <div class="product-btns"> <div class="qty-input"> <span class="text-uppercase">Ədəd: </span> <input class="input" type="number" value="1" id="productQty"> </div> <input type="hidden" class="product-id" value="{{product.id}}"> <input type="hidden" class="product-name" value="{{product.name}}"> <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart" id="addToCartBtn"></i> Səbətə at</button> </div> -
Session information is not stored in the database(django-session table)-I have used a custom model and backend
i use multiple backend and model for user authentication the default django auth system and m I use multiple backend and models for user authentication Default Django's model and a customized one . Default django authentication for admin-users and customized model and backend for customer-users Now The problem is when customer-users login their session information does not stored in the database(django-session table),so Because their sessions are not saved, they need to re-login each time the page is refreshed or changed -
Please help me fixing out my django chained dropdown
I am having issues with chained dropdown can someone help me fixing it out.I have created both category and sub category model, product model, html pages, views and everything neccessary to make this code work but it's not working now.it was working when before but now the same code is not working i have no idea what happened to it.I took this code from a youtube tutorials i guess that's the reason i am having trouble fixing it out. forms.py ``` class AdminProductForm(forms.ModelForm): user = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) image = forms.FileField(label='Thumbnail', widget=forms.FileInput( attrs={'class': 'form-control'}), required=False) class Meta: model = AdminProduct fields = ['user', 'title', 'details', 'image', 'sp', 'dp', 'download_link', 'preview_link','category', 'subcategory', 'tags'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = AdminSubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields['subcategory'].queryset = AdminSubCategory.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.category.subcategory_set.order_by('name') models.py class AdminCategory(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminSubCategory(models.Model): category = models.ForeignKey(AdminCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150) details = RichTextField() image = models.ImageField(upload_to="AdminProduct_Images/") download_link = … -
Add custom formatter tags in papertrail Logger in django
settings Page: "formatters": { "simple": { "format": "%(name)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, If I write here code like this: "formatters": { "simple": { "format": "%(name)s %(ip)s %(user)s %(client)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, It is showing following Error: --- Logging error --- Traceback (most recent call last): File "C:\Program Files\Python10\lib\logging\__init__.py", line 440, in format return self._format(record) File "C:\Program Files\Python10\lib\logging\__init__.py", line 436, in _format return self._fmt % values KeyError: 'ip' -
How to use Django with Docker and have no problems with migrations?
During working with docker where I dockerised Django PostgreSQL, I've entered in such problems as when I change some model and migrate it, after entering to the page, it says there is no such relationship in the database. After some research, I found that problem can be due to creating every time new migration and deleting the old. How can I fix this problem? Below you can see my configurations docker-compose-prod.yml services: app: volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles env_file: - django.env - words_az.env - words_en.env build: context: . ports: - "8000:8000" entrypoint: /app/script/entrypoint.sh command: sh -c "python manage.py collectstatic --no-input && gunicorn --workers=3 --bind 0.0.0.0:8000 django.wsgi:application" depends_on: - db nginx: build: ./nginx volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles ports: - "80:80" - "443:443" depends_on: - app - flower db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - db.env ports: - "5432:5432" redis: image: redis:alpine ports: - "6379:6379" worker: build: context: . command: celery -A django worker -l info env_file: - django.env depends_on: - db - redis - app flower: build: ./ command: celery -A django flower --basic_auth=$user:$password --address=0.0.0.0 --port=5555 --url-prefix=flower env_file: - django.env ports: - "5555:5555" depends_on: - redis - worker volumes: postgres_data: static_data: media_data: Dockerfile FROM python:3.9-alpine ENV PATH = "/script:${PATH}" … -
Is it possible to add more than one field to Meta in Model?
I´m trying to add a unique together to my model, in which I have assigned permissions for backend roles. My model is like this: class Detail(models.Model): order=models.ForeignKey('Order',related_name='orders',on_delete=models.CASCADE,verbose_name='Order') component=models.ForeignKey('Component', related_name='order_component',on_delete=models.RESTRICT,verbose_name='Component') class Meta: unique_together = ('order', 'component') permissions = (("detail_list", "detail_list"),) When I try to save, it just keep me saying this: IndentationError: unindent does not match any outer indentation level I guess I could add permissions in a latter Model, but just for curiosity, anybody please could tell me if that´s the best approach, or if there is somethig I am missing? Cheers -
Filter Django ForeignKey Dropdown based on Current User
I am using django ClassBasedViews where I have a Project and Task Models. Each task is assigned to a project and both models register who created a recording in the created_by field. class Project(models.Model): name = models.CharField(max_length=100) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) and then for the Tasks, I have class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=200) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) So the ClassBasedView to create the new task is like so, class CreateTask(LoginRequiredMixin, CreateView): template_name = 'project/new _task.html' form_class = TaskCreationForm success_message = "New Task Created" I need the dropdown in the form to Only show projects for the current logged-in user. I have gone through this post but the author did not implement my use case for *the current logged-in user. What can I do and how can I implement this? -
Django: form and list of nested objects
I can't make an object list, which itself will restrict the following object list. Let me explain: I have a model Base with a foreignkey field, referring to a model Parent1 which itself refers a foreignkey to a model Parent2. I would like to make a form where we choose the Parent2, then the Parent1 with a choice delimited by the Parent2. class Parent2(models.Model): title = models.fields.CharField(max_length=100) def __str__(self): return f'{self.title}' class Parent1(models.Model): title = models.fields.CharField(max_length=100) parent2 = models.ForeignKey(Parent2, null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.title}' class Base(models.Model): title = models.fields.CharField(max_length=100) parent1 = models.ForeignKey(Parent1, null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.title}' def base_registration(request): base_form = forms.BaseForm() if request.method == 'POST': base_form = forms.BaseForm(request.POST) if all([document_form.is_valid()]): base = base_form.save(commit=False) base.save() context = { 'base_form': base_form, } return render(request, 'base_registration.html', context=context) class BaseForm(forms.ModelForm): title = forms.CharField(max_length=20, help_text="Title") parent1 = forms.ModelChoiceField(queryset=models.Parent1.objects.all(), required=False) parent2 = forms.ModelChoiceField(queryset=models.Parent2.objects.all(), required=False) class Meta: model = models.Base fields = ['parent2', 'parent1', 'title'] -
django search where database value is part equal to search value
value_in_database = 'Computer Solutions' search_value = 'Solutions' I know that if I have values like the above, I can find my object like this: model.objects.filter(name__icontains=search_value) But I was wondering if the opposite is possible in Django? value_in_database = 'Solutions' search_value = 'Computer Solutions' model.objects.filter(name=search_value) -
Django Serializer field validator not being called
Serializer field validator not being called seems to be a common problem but I cannot find the right solution. I have a normal (NON-MODEL) serializer with a URLField and a custom validator for the field. The field validator is not being hit when running is_valid(), instead the builtin URLValidator is being called. Here is the custom validator (only to avoid http:// not included error): class OptionalSchemeURLValidator(URLValidator): def __call__(self, value): if "://" not in value: value = "http://" + value super(OptionalSchemeURLValidator, self).__call__(value) Here is the serializer: from rest_framework.serializers import Serializer class DeveloperAccessTokenSerializer(Serializer): token = CharField(read_only=True) company_website = URLField( required=False, validators=[OptionalSchemeURLValidator()], ) def create(self, validated_data): self.token = jwt.encode( jwt_payload, settings.SECRET_KEY, algorithm="HS256" ) self.company_website = validated_data.get("company_website", None) return self.company_website Here is how the serializer is being used: def post(self, request, *args, **kwargs): context = {"request": request} ser = self.serializer_class(data=request.data, context=context) ser.is_valid(raise_exception=True) token = ser.save() return Response(token, status=HTTP_201_CREATED) Validation error is being raised on is_valid(): rest_framework.exceptions.ValidationError: {'company_website': [ErrorDetail(string='Enter a valid URL.', code='invalid')]} Input value for the field is www.my-website.com -
With Django, should we be writing functions inside views, or importing them from another python file?
When writing functions for views, should they be placed within the specific views, outside of the views within views.py or inside a separate script such as viewsfunctions.py? Is there any advantage/requirement for any of these options? As an example, if we were writing a function to convert units of weight from one to another for unified measurement, where should this function be written? -
Display (4.0) Django models.JSONFields as form in webpage
I am working on a Django based website. I have defined a JSONFields in my backend DB table , let's called it "CampaignTable" The JSONFields is used to store Campaign parameters which might differ from campaign to campaign. I want to collect campaign configuration from web user in a form , this form is actually transfer from JSONFields (key:value) to Form (fields:value) Is there a way to do it in Django or any plugins I can use ? -
Django Get username from filled login entry field
Need to log when user fails to login. Function: if request.user.is_authenticated: for g in request.user.groups.all(): list_aaa.append(g.name) logging.info('User ' + request.user.username + ' logged in (from IP: ' + request.META.get('REMOTE_ADDR') + ') ' + 'Group: ' + str(list_aaa)) else: logging.info('User ' + request.user.username + ' from IP: ' + request.META.get('REMOTE_ADDR') + ' failed to log in providing incorrect credentials') After successful login this function logs User xxxx logged in (from IP: 10.10.10.0) Group: ['AAA_ENGINEER', 'BBB_VPN_'] but when user login failed it returns: User from IP: 10.10.10.10 failed to log in providing incorrect credentials I have tried replacing request.user.username with request.META.get('USERNAME') and on my local machine + PyCharm this works but on development server request.META.get('USERNAME') returns None In debug i can see following query and in the end you can see user passed as arg, but how can i reach it: 2022-05-16 12:26:45 [DEBUG] (0.002) QUERY = 'SELECT TOP 21 [auth_user].[id], [auth_user].[password], [auth_user].[last_login], [auth_user].[is_superuser], [auth_user].[username], [auth_user].[first_name], [auth_user].[last_name], [auth_user].[email], [auth_user].[is_staff], [auth_user].[is_active], [auth_user].[date_joined] FROM [auth_user] WHERE [auth_user].[username] = %s' - PARAMS = ('xxxx',); args=('xxxx',) -
getting problem with working nested json in django framework
Hi Everyone I am trying to writing a code to get nested response based on driver_id, i am not able to solve this issue, kindly help me out. views.py def retrieve(self, request, *args, **kwargs): rating= connection.cursor() rating.execute(''' SELECT...... ''') rating_data=rating.fetchall() json_res=[] obj={} for row in rating_data: json_obj=dict(week_start_date=row[0],week_end_date=row[1],driver_id=row[2],driver_name=row[3],mobile=row[4],week_period=row[5],total_trips=row[6],driver_rating=row[7]) if obj.get('driver_id')==row[2]: obj['mobile'].append(json_obj) else: if obj.get('driver_id')!=None: json_res.append(obj) obj={} obj['driver_id']=row[2] obj['driver_name']=row[3] obj['mobile']=[json_obj] json_res.append(obj) return JsonResponse(json_res,safe=False) current response [{"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "last week", "total_trips": 60, "driver_rating": "Mediocre"}]}, {"driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": [{"week_start_date": "2022-04-18", "week_end_date": "2022-04-24", "driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": "7718908984", "week_period": "4th week", "total_trips": 20, "driver_rating": "Mediocre"}, {"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": "7718908984", "week_period": "last week", "total_trips": 53, "driver_rating": "Mediocre"}]}, {"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-02", "week_end_date": "2022-05-08", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "2nd week", "total_trips": 60, "driver_rating": "Mediocre"}]}] expected output [{"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "last week", "total_trips": 60, "driver_rating": "Mediocre"}, {"week_start_date": "2022-05-02", "week_end_date": "2022-05-08", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "2nd week", "total_trips": 60, "driver_rating": "Mediocre"}]}, … -
Django Template View received post of other url and not display data
Okay, my problem is about context data that is not displayed in the template. First of all, I am pretty new in Django and js programing. I have a first page with data sending, using ajax success (I have ajax for other needs in this page). Following, my templateView class : class displayResultPage(TemplateView): template_name = 'result.html' filename = 'None' protol_file = 'None' def get_context_data(self, **kwargs): kwargs = super(displayResultPage, self).get_context_data(**kwargs) kwargs["filename"] = self.filename kwargs["protocol_file"] = self.protol_file return kwargs def post(self, request, *args, **kwargs): self.filename = copy.deepcopy(request.POST.get("img_path")) self.protol_file = copy.deepcopy(request.POST.get("json_path")) context = self.get_context_data(**kwargs) #try without get_context_data defined to add element in the context #context["filename"] = copy.deepcopy(request.POST.get("img_path")) #context["protocol_file"] = copy.deepcopy(request.POST.get("json_path")) #second try with same goal #kwargs = { # "filename": self.filename, # "protol_file": self.protol_file, #} return self.render_to_response(context) I want to send to the templace the filename and the protocol file (name). When I redirect to this new page (result.html), data are not passed. So, I try to find a way to do it. First of all, I had to defined the post method to received these data. With the debugger, the break point stop in the post function. Here, the request.POST is okay and I have data inside. After that, the step is … -
How can I order a table in Django without refreshing the whole page?
There is a feature in a Django application I'm working on that allows users to search the database by things like customer name, invoice number etc. The search result is rendered as a Django table which gives an array of results with several columns such as "Expiry Date", "Product Name", "Issue Date" etc. My problem is however, that if I click on a column name (so that we can order the results as desired) the entire page gets refreshed and all the results are gone and the form has been cleared - which is definitely not what we want! Is there a way to fix this using DJango? Or am I better off using another web application language for this feature? If so, which one? -
Execute several scripts at the same time in the background
I have a page where the user selects a Python script, and then this script executes. My issue is that some scripts take a while to execute (up to 30m) so I'd like to run them in the background while the user can still navigate on the website. I tried to use Celery but as I'm on Windows I couldn't do better than using --pool=solo which, while allowing the user to do something else, can only do so for one user at a time. I also saw this thread while searching for a solution, but didn't manage to really understand how it worked nor how to implement it, as well as determine if it was really answering my problem... So here is my question : how can I have multiple thread/multiple processes on Celery while on Windows ? Or if there's another way, how can I execute several tasks simultaneously in the background ? -
Django Many to Many 'QuerySet' object has no attribute 'members'
First, here is my Location model. It has one ManyToManyField called members. Model: class Location(models.Model): name = models.CharField(max_length=200) # ... members = models.ManyToManyField(User, related_name="members") # ... (Note, "# ..." replaces more fields) And then in a view I did this. DetailView class LocationDetailView(DetailView): model = Location context_object_name = "location" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) location = Location.objects.filter(pk=self.get_object().pk) context["members"] = location.members.all() return context Error 'QuerySet' object has no attribute 'members' -
Is there a Django ManyToManyField with implied ownership?
Let's imagine I'm building a Django site "CartoonWiki" which allows users to write wiki articles (represented by the WikiArticle-model) as well as posting in a forum (represented by the ForumPost-model). Over time more features will be added to the site. A WikiArticle has a number of FileUploads which should be deleted when the WikiArticle is deleted. By "deleted" I mean Django's .delete()-method. However, the FileUpload-model is generic -- it's not specific to WikiArticle -- and contains generic file upload logic that e.g. removes the file from S3 when it's removed from the database. Other models like ForumPost will use the FileUpload-model as well. I don't want to use GenericForeignKey nor multi-table inheritance for the reasons Luke Plant states in the blog post Avoid Django's GenericForeignKey. (However, if you can convince me that there really is no better way than the trade-offs GenericForeignKey make, I might be swayed and accept a convincing answer of that sort.) Now, the most trivial way to do this is to have: class FileUpload(models.Model): article = models.ForeignKey('WikiArticle', null=True, blank=True, on_delete=models.CASCADE) post = models.ForeignKey('ForumPost', null=True, blank=True, on_delete=models.CASCADE) But that will have the FileUpload-model expand indefinitely with more fields -- and similar its underlying table will gain more … -
How to replace values between two curly brackets in python?
I want to replace values in strings between two curly brackets. e.g: string = f""" my name is {{name}} and I'm {{age}} years old """ Now I want to replace name, and age by some values. render_param = { "name":"AHMED", "age":20 } so the final output should be. my name is AHMED and I'm 20 years old. -
Unable install Django through Dockerfile
when I run 'docker build .' command, "ERROR: Invalid requirement: 'Django=>4.0.4' (from line 1 of /requirements.txt) WARNING: You are using pip version 22.0.4; however, version 22.1 is available. You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command." this error shows up. I have upgraded pip to the latest version. When I check version of pip , it shows 22.1. But when I run docker build command again, nothing changes. I have upgraded from this /usr/local/bin/python location. but still nothing changed. I am using Ubuntu 20.04, python version is 3.8. -
Django "SQLite 3.9.0 or later" error Cronjob
I'm trying to schedule a database import for Django with Crontab. The script looks as following: #!/usr/bin/python3 import csv import os from app.models import AppData path = "/home/ec2-user/PolisCheckV2/UpdateUploadCSV/VvAA/CSV/" os.chdir(path) with open('AppData.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: p = AppData(klantnummer=row['1'], huisnummer=row['2'], postcode=row['3'], polisnummer=row['4']) p.save() exit() When I run the script on its own, everything works perfectly. However, when I'm running it scheduled through Crontab, the following mail appears in /var/spool/mail: File "/home/ec2-user/project/manage.py", line 22, in <module> main() File "/home/ec2-user/project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, in …