Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error in creating an order by the customer while checking out
"Environment: Request Method: POST Request URL: http://127.0.0.1:8000/makeOrder/9/ Django Version: 3.0.5 Python Version: 3.6.8 " Traceback (most recent call last): File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\HARSHA\Documents\sdp-2\website\views.py", line 232, in makeOrder 'fuel' :fuel, Exception Type: UnboundLocalError at /makeOrder/9/ Exception Value: local variable 'fuel' referenced before assignment -
Notify admin in django REST API
while uploading files i need to notify admin.How can i do this models.py class File(models.Model): file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) Serializers.py class FileSerializer(serializers.ModelSerializer): class Meta(): model = File fields = ('file', 'remark', 'timestamp') Views.py class FilesViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = (permissions.IsAuthenticated,) -
Date and File name are not showing while Updating the Data in Django
I have Tried some patterns which are suggested by some Stackoverflow users. They are like : date:'jS M Y' & date:'c' But not working in my case. Also referred this article : django update view not showing date input (previous) values Models.py from tkinter import CASCADE from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Ticket2(models.Model): ticketholder = models.ForeignKey(User, on_delete=models.CASCADE, default=None) ticket_id = models.CharField(max_length=8, default='NS000001') server_details = models.CharField(max_length=100) send_date = models.DateTimeField(default=timezone.now) license_no = models.CharField(max_length=25) file = models.FileField(upload_to='documents/%Y%m%d/') def __str__(self): return self.ticket_id edit.html {% extends 'base.html' %} {% block content %} <h3 class="row justify-content-around">Edit Form</h3> <div class="row justify-content-around" class="modal-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Ticket ID</label> <input type="text" value="{{ticketdata.ticket_id}}" name="ticket_id" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Server Details</label> <input type="text" value="{{ticketdata.server_details}}" name="server_details" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Send Date</label> <input type="datetime-local" value="{{ ticketdata.send_date.value|date:'jS M Y' }}" name="send_date" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">License No</label> <input type="text" value="{{ticketdata.license_no}}" name="license_no" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Files</label> <input type="file" value="{{ticketdata.file}}" name="file" class="form-control" id="exampleInputPassword1" required> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> {% endblock %} views.py … -
Django uwsgi nginx cloudpanel.io
I'm using ubuntu server 22 with cloudpanel.io. Error from nginx error logs: connect() failed (111: Connection refused) while connecting to upstream, client: 123.123.123.123, server: django.secretdomain.com, request: "GET / HTTP/2.0", upstream: "uwsgi://127.0.0.1:8080", host: "django.secretdomain.com" vhost file: (nginx file) server { listen 80; listen [::]:80; listen 443 ssl http2; listen [::]:443 ssl http2; {{ssl_certificate_key}} {{ssl_certificate}} server_name django.secretdomain.com; {{root}} {{nginx_access_log}} {{nginx_error_log}} if ($scheme != "https") { rewrite ^ https://$host$uri permanent; } location ~ /.well-known { auth_basic off; allow all; } {{settings}} index index.html; location / { include uwsgi_params; uwsgi_read_timeout 3600; uwsgi_pass 127.0.0.1:8080; } if (-f $request_filename) { break; } } The domain.uwsgi.ini [uwsgi] plugins = python3 master = true protocol = uwsgi socket = 127.0.0.1:8080 wsgi-file = /home/admin/htdocs/django.secretdomain.com/django5/Django5/mysite/mysite/wsgi.py virtualenv = /home/admin/htdocs/django.secretdomain.com/django5/Django5/venv buffer-size = 8192 reload-on-rss = 250 processes = 4 threads = 2 enable-threads = true close-on-exec = true umask = 0022 uid = admin gid = admin ignore-sigpipe = true ignore-write-errors = true disable-write-exception = true On the frontpage i get a simnple 'internal server error'. A simple python test file works but django doesn't. What I'm supposed to do? -
Django Celery Beat did not send message to SQS broker (Django, SQS, DatabaseScheduler)
I have 2 t2 instances on AWS, one for beat, one for worker. Beat (t2.micro): celery -A iso_backend beat -l info --scheduler django Worker (t2.small): celery -A iso_backend worker -l info --scheduler django I'm using djang_celery_beat_clockedschedule's table for scheduling a lot of long-running job. A lot of clocked has_many jobs, so example: at 08:20:00am, Beat must call 100 messages to SQS queue at the same time, the issue is, it call only a fews, sometimes 1/2, sometimes 1/3 number of the jobs Scheduler: Sending due task... Actually, this issue is really hard and I cannot figure out the root cause. Anybody met this before and has any solutions help me? Thank a lot! -
How to by pass login required url authen by any mean in website?
Hope you are doing good. i am new to Django so basically i want an idea of how we can access page that required login but i want one time login not every time.or just by pass this authentication by any mean i don't know? i-e: i have chat bot i want to give that page specific url to some client and that client add that url in his website so his clients just use my chatbot by click my chatbot url that are present in my client website.but i want that by clicking that url does not require to login first but i want the secure access only that client domain only access my url . not other domain or from chrome brower. if you give any idea it will be very kindness of you thanks alot. my-sloution: i used django-cors but i dont know that using cors will restrict access to other domain accept the allowed one? i experence from cors-test websites i just send post request but cannot access my site when i allowed that domain in cors then they can get post response . so basically when i search that url from chrome on same LAN … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
I am trying to save a user with its respective group but it gives me an error error: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. I also don't know if I make a correct call of the group column models.py @login_required #@allowed_users(allowed_roles=['Administrador']) def crearusuario(request): data = { 'empleado': CrearEmpleadoForm() } if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=make_password(request.POST.get('contrasena')) usersave.activo=request.POST.get('activo') usersave.cargo_empleado=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) usersave.id_empresa=Empresa.objects.get(pk=(request.POST.get('id_empresa'))) usersave.id_unida=UnidadInterna.objects.get(pk=(request.POST.get('id_unida'))) if request.method == 'POST': formulario = CrearEmpleadoForm(data=request.POST) if formulario.is_valid(): username=request.POST.get('rut') password=request.POST.get('rut') first_name=request.POST.get('nombres') last_name=request.POST.get('apellidos') email=request.POST.get('correo_electronico') groups=Group.objects.get(pk=(request.POST.get('group'))) cargo=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) activo=request.POST.get('activo') user=get_user_model().objects.create( username=username, password=make_password(password), first_name=first_name, last_name=last_name, email=email, cargo_empleado=cargo, is_active=True, groups=groups ) cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+str(usersave.cargo_empleado.id)+"', '"+str(usersave.id_empresa.id)+"', '"+str(usersave.id_unida.id)+"')") messages.success(request, "El empleado "+usersave.nombres+" se guardo correctamente ") return render(request, 'app/crearusuario.html', data) else: return render(request, "app/crearusuario.html", {'empleado':formulario}) else: return render(request, 'app/crearusuario.html', data) help me please -
subdomain is not redirecting to main domain but different virtual host
I am hosting multiple domains from the same server. Each domain is having multiple subdomains. Let's say I have the following domains: example1.com, and example2.com. Also, example1.com have subdomain1.example1.com. I redirect http to https with SSL certificate on exmaple1.com and *.example1.com and example2.com. My example1.com and example2.com redirected fine but subdomain1.exmaple1.com is not redirecting and it is trying to get the certificate from example2.com. My application is Django and I am using mod-wsgi for deployment. Thanks in advanced -
How to launch a Postgresql database container alongside an Ubuntu Docker image?
How do you use docker-compose to launch PostgreSQL in one container, and allow it to be accessed by an Ubuntu 22 container? My docker-compose.yml looks like: version: "3.6" services: db: image: postgres:14-alpine environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=test - POSTGRES_DB=test command: -c fsync=off -c synchronous_commit=off -c full_page_writes=off --max-connections=200 --shared-buffers=4GB --work-mem=20MB tmpfs: - /var/lib/postgresql app_test: build: context: .. dockerfile: Dockerfile shm_size: '2gb' volumes: - /dev/shm:/dev/shm My Dockerfile just runs a Django unittest suite that connects to the PostgreSQL database using the same credentials. However, it looks like the database periodically crashes or stops and starts, breaking connection with the tests. When I run: docker-compose -f docker-compose.yml -p myproject up --build --exit-code-from myproject_app I get output like: Successfully built 45c74650b75f Successfully tagged myproject_app:latest Creating myproject_app_test_1 ... done Creating myproject_db_1 ... done Attaching to myproject_app_test_1, myproject_db_1 db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page … -
Can not use Django-rest-auth in Django4.0 ; ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
For now I am building the Django Rest Framework in Django4.0 and Django-rest-auth. I knew the django4.0 does not support the ugettext_lazy. it support the gettext_lazy instead of. I installed the django-rest-auth==0.9.5 in my app. and then it raised the issue. ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' Here is my settings: THIRD_PARTY_APPS = [ 'escapejson', 'corsheaders', 'rest_framework_swagger', 'rest_framework', 'rest_auth', 'drf_yasg', 'django_jsonfield_backport', 'allauth', 'allauth.account', 'allauth.socialaccount', ] INSTALLED_APPS = LOCAL_APPS + DJANGO_APPS + THIRD_PARTY_APPS In Django4.0, Can not I use the django-rest-auth? -
Field 'id' expected a number but got <>ManyRelatedManager object
I am trying to remove a field in a many to many relationship but I came across this error and I dont know how to solve/fix it. Here is what I am trying to do: 1: Before the below views I get a valid POST from user identifing data.log_order 2: I search if there are previous logs in ActiveSession. If there is search for matching logs with the same received data.log_order and delete the existing one and add the new received data. 3: If there is no matching data.log_order in log or previous logs to add the new received data. As simple as the logic as difficult as I am struggling to get my errors fixed. class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. Here is the views: if active_session.log.values(): print(active_session.log.values()) for i in active_session.log.values(): if i['log_order']==int(data.log_order): log_order = data.log_order log=Log.objects.filter(log_order=log_order) print(log) active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id,log__in=log) print(active_session) active_session.log.remove(active_session.log) active_session.log.add(data) print(active_session.log.values()) else: active_session.log.add(data) print(active_session.log.values()) print('Existing Log with different order_no') else: active_session.log.add(data) print('Log added to Session') print(active_session.log.values()) return HttpResponseRedirect(url) Here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1774, i n get_prep_value return int(value) TypeError: int() argument must … -
How do I get a Django multiple select form to pass through selected items as a list?
I have a Django application where I use multi-select with dynamic choices as related to the logged-in user, but when I try to submit the form, I keep getting the following error message: "TypeError at /masstext.html Field 'id' expected a number but got <QueryDict: {'customers': [''], 'textmessage': ['test'], 'csrfmiddlewaretoken': ['FNawscd4CXqtDWIUrq0Kolq3x6R699lStaykXwxDbtqciJortBm0pTfPWSvvjW7L']}>" I'd like to have it where, when the user submits the form, a new model instance is created with the selected customers and the message typed out as fields. I don't understand why I'm not getting a list of selected customers from the multi-select returned in the list, but rather an empty list. Code below: Model: class Masstext(models.Model): profile = models.ForeignKey(Profile, on_delete = models.CASCADE) message = models.CharField(max_length = 500, null = True) customers = models.CharField(max_length = 1000, null = True) Form: class Textform(ModelForm): def __init__(self, user, *args, **kwargs): super(Textform, self).__init__(*args, **kwargs) self.fields['customers'] = forms.ModelChoiceField( queryset = Customers.objects.filter(facility__profile__email = user)) class Meta: model = Masstext fields = ['customers','message'] View: @login_required(login_url="login/") def load_customers(request, *args, **kwargs): msg = '' if request.method == 'POST': user = request.user form = Textform(request.POST) if form.is_valid(): form.save() else: msg = "Fields are not valid" else: form = Textform(request.user) context = {'form': form} return render(request,'home/masstext.html',context) Template: <form action="masstext.html" method="POST"> … -
DJango Redirect Not Refreshing the Page
I'm having an issue where "return redirect('/main')" is working but have to refresh the browser manually to see the change. From the main.html template, button onclick calls JS jpButton(), which does a work, then returns to DJango function that updates session value, then redirect to main page that will display the value in the session. But the value does not change on page until I manually refresh the browser. Please help. // jsbutton.js - called from onlick button in main template async function jpButton() { ... $.ajax({ type: "POST", url: 'http://localhost:8080/main/jpConnect', headers: { "X-CSRFToken": csrftoken }, data: { onlinestatus: "Online" }, .... ### views.py ### # This redirect works fine def jpDisconnect(request): request.session['onlinestatus'] = None return redirect('/main') # This is called from JS jpButton(), and the browse have to be manually refreshed afterwards def jpConnect(request): if request.headers.get('x-requested-with') == 'XMLHttpRequest': request.session['onlinestatus'] = request.POST.get('onlinestatus', None) return redirect('/main') <!-- main.html --> ... {% csrf_token %} {% if request.session.onlinestatus %} <a href="{% url 'jpDisconnect' %}"> <button class="button" type="button" > {{ request.session.onlinestatus }} </button></a> {% else %} <button class="button" type="button" onclick="jpButton()"> Offline </button></a> {% endif %} ... Strangely, the jpDisconnect() refreshes and changes the value on the page, but the jpConnect() does not (I have … -
How to get this Django REST query to display all fields, including fields from related one-to-one table
This is my Django models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model. from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model class CustomUser(AbstractUser): email = models.EmailField(unique=True) post_code = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.username class UserComputedInfo(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) copy_input = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.copy_input I am trying to create a REST API to display all the fields in the 2 tables. I am using Django REST framework. This is my serializers.py from rest_framework import serializers from users.models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: fields = ("email", "post_code") model = CustomUser This is my views.py from rest_framework import generics from django.contrib.auth import get_user_model from .serializers import CustomUserSerializer class PostCodeAPIView(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = CustomUserSerializer The API will display all the fields in CustomUser table. However, I want to display all the fields in the related one-to-one UserComputedInfo table as well. I am using Django v4, python v3.9, Django REST framework on Windows 10. -
Render form dynamically on AJAX Request with Django
Introduction I think I'm mistaking something how (pure) AJAX and Django should be used while I try to implement the following: A view is displaying a list of all model's objects with buttons to change an existing object or to create a new one. Clicking on such a button opens a modal and fires an AJAX request to render the form A Django view is processing the request and is rendering the template for the requested form with Django's render_to_string Rendered string is returned as context with Django's JsonResponse Returned JSON is used for displaying form via JavaScript (modal.innerHTML) Form is filled by user and send with AJAX to a Django view where form data will be processed Response is given by view with JsonResponse and shows success or errors Since implementing step 5, I was wondering if I'm on the right track. Using render_to_string and JsonResponse leads to some extra space ahead of the form. This is caused by a BOM. To be specific, \ufeff is prepending the HTML containing string whereby the BOM is rendered (but not shown) by browser and causing the unwanted extra line. I did not found any other solution than using replace multiple times … -
Nginx, gunicorn, django not passing real IPV6 address
I am currently trying to set up a simple ip website, miip.co with the purpose of just showing your your ip address when you open the site. When I test https://ready.chair6.net/?url=https://miip.co it shows yes to all but ipv4 literals with only a warning. My nginx location looks like so location / { proxy_pass http://unix:/home/www/miip/app.sock; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header REMOTE_ADDR $remote_addr; proxy_read_timeout 1000; # this } And my django ip function looks like so def get_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip Yet despite this, it always return a ipv4. My system is also on ipv6. I think it has to do with nginx proxy pass but unsure. -
Django add select2
i try to add the Select2 in my django app but i can't use it. What i do wrong ? Anyone have a solution ? page.html <!----Select2-----> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!----Select2-----> <script> $(document).ready(function() { $('#id_employe').select2(); }); </script> Filter from the form -
How to extract values from Queryset Django
When an output is received in the below form after running the query <QuerySet [<key: value object (ad5bb6b4-8035)>]> I want to get ad5bb6b4-8035 string only for further operations. So I tried course_qs = <QuerySet [<key: value object (ad5bb6b4-8035)>]> for course in course_qs: print(course) which returned value object (ad5bb6b4-8035) How to get only ad5bb6b4-8035.? getting values of QuerySet in django How to extract numerical value from Django queryset? Extracting message from django queryset -
Image not saving to django models when trying to upload from react-native
I am writing my first react-native app with a django backend. In order for my app to function properly, I need to send an image from the react-native to django models. I am trying to send an image and then save it to the model, but when I check the django-admin the image field is empty. heres my code- react-native: const [ sentI, setSentI ] = useState(null) const sendI = async (image) => { const formData = new FormData() image_data = { uri : image.uri, name : "profileImage", type : 'image/jpg' } if (image != null){ await formData.append( 'image', image.uri,) await formData.append( 'name', usern,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const image = () => { fetch(`http://192.168.5.234:8000/home/imagetest/`, { method: 'POST', body: { sentI }, }) .then( res => res.json()) .then( res … -
Django: self.model_set not accesible in custom save() function
I'm trying to make a custom save function that calculates some values and will store them in another Model to which a ManyToMany relationship exists. From what I can understand from the documentation, I should have a field_set way of accessing all the related objects. However, when I save here, I get the error 'Game' object has no attribute 'heat_set' I don't see what I'm doing wrong here: class Game(models.Model) heat = models.ManyToManyField(Heat) [...] def save(self, *args, **kwargs): super().save(*args, **kwargs) for heat in self.heat_set.all(): [...] -
Django Rest Framework value id is being sent, but is being received as null
Having an issue where I am trying to set the interest_category. Here is my current code. Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project read_only_fields = ( 'created_by', 'created_at', 'updated_at', ), fields = ( 'project_title', 'project_description', 'interest_category', ) Model class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ForeignKey(Interests, on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) Views class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectsSerializer queryset = Project.objects.order_by('-created_at') def perform_create(self, serializer): serializer.save(created_by=self.request.user) Here is the data being sent { "project_title": "Test", "project_description": "Test1", "interest_category": 2 } Here is the data being received (35, Test, Test1, 2022-09-22 02:11:54.342202+00, 2022-09-22 02:11:54.342202+00, 1, null). I can send the data without a null error when I am NOT using the interest_category = serializers.StringRelatedField() in the serializer. Any ideas why the interest_category is showing null and why it is not being sent and/or received correctly when using the serializers.StringRelatedField()? And if it is because of the StringRelatedField is there a better way to get the name while posting the ID? In frontend, I am passing the ID as a value. -
best way to store celery results
I am using celery for my async tasks, however, I am using Redis as backend broker. My current plan is to filter and manipulate data inside the backend and store it into django-db for viewing etc. Is this the recommended way? Or I should use Django DB as backend results db and store all the raw data then filter and manipulate it into different tables? -
Django ORM query for filtering product price between two number is not working properly
class Product(models.Model): product_name = models.CharField(max_length=255,unique=True) slug = models.SlugField(max_length=255) brand = models.CharField(max_length=255) price = models.CharField(max_length=255) product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False) product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False) product_description = models.TextField() category_id = models.ForeignKey(Categories,on_delete=models.CASCADE) subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE) stock = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug, self.slug ]) '''view''' val=request.POST.get('value') val = re.findall("\d+", val) # code to get all inigers from string min_price = int(val[0]) max_price = int(val[1]) print(min_price) print(max_price) ***product = Product.objects.filter(category_id = categories,is_active = True,price__gte = min_price, price__lte = max_price)*** when i give value greater than max_value product object returns null object I want all objects between the two min_value and max_value -
Django is not serving my image asset, using rest framework
I am uploading an image file from Flutter to Django, the image is getting saved properly in my backends directory under assets/images, and when I query the database with a get I get the proper path of the file. But when I go to the URL in the browser the image does not appear and I get an error. I am using rest-framework for my app. Model: class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) name = models.CharField(max_length=200) quantity = models.IntegerField(default=0) barcode = models.CharField(max_length=200) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0.0) image = models.ImageField(upload_to='images/', null=True) Settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/pm/assets/' Urls.py: urlpatterns = [ path('', include(router.urls)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Serializer: class SuppliersSerializer(serializers.ModelSerializer): product_set = ProductsSerializer(read_only=True, many=True) class Meta: model = Supplier fields = ['pk','user','name','email','phone','product_set'] class ProductsSerializer(serializers.ModelSerializer): transactions_set = TransactionsSerializer(read_only=True, many=True) class Meta: model = Product fields = ['pk','name','quantity','barcode','cost_price','image', 'selling_price', 'transactions_set'] JSON response: { "pk": 13, "name": "pi3", "quantity": 3, "barcode": "11111", "cost_price": 10.0, "image": "/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg", "selling_price": 20.0, "transactions_set": [] }, But when visiting: http://localhost:8000/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg I get this error: -
Is there any way with django tables2 to only show data based off any given information
I have looked all over not sure if I am searching to broadly. I want to essentially only show data to a user if that user is linked to the data. Currently it shows all data. Example of similar function. {% for group in request.user.groups.all %} {% if group.name == 'General User' %} {% for project in project_card_list %} {% for u in project.assigned_users.all %} {% if u == user %} This is just a quick example of what I want, I was able to display the data this way but was wanting to clean it up and have it show in a django table2 table instead. Table code: class ProjectTable(tables.Table): class Meta: model = Project template_name = "django_tables2/bootstrap.html" fields = ("name", "project_lead", "start_date", "end_date", "description") exclude = ("project_id", "assigned_users",) View: @login_required(login_url='login_register') def projects_page(request): table = ProjectTable(Project.objects.all()) return render(request, 'projects.html', {'table': table})