Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
urlpattern Regex is not working as expected
I have a Django website and for the times that pages are not ready I want to redirect any URL to a specific maintenance page. So in the urlpatterns of my website I added this regex expecting it to capture anything after / but it's not working. urlpatterns = [ path(r'/.*',maintenance_view,name='maintenance') ] -
django DateTimeField serializer return datetime into string format
I have a serializer that validates datetime fields. import rest_framework.serializers as serializer from django.conf import settings class ValueNestedSerializer(serializer.Serializer): lower = serializer.DateTimeField(format=settings.DEFAULT_DATETIME_FORMAT, input_formats=settings.DATETIME_INPUT_FORMATS, required=True) upper = serializer.DateTimeField(format=settings.DEFAULT_DATETIME_FORMAT, input_formats=settings.DATETIME_INPUT_FORMATS, required=True) class DateRangeSerializer(serializer.Serializer): attribute = serializer.CharField(default="UPLOAD_TIME", allow_null=True) operator = serializer.CharField(default="between_dates") value = ValueNestedSerializer(required=True) timezone = serializer.CharField(default="UTC") timezoneOffset = serializer.IntegerField(default=0) def validate_attribute(self, attribute): return 'device_time' if attribute and attribute.lower() == 'device_time' else 'date_range' The payload is in the format: "date_range": { "attribute": "date_range", "operator": "between_dates", "value": { "lower": "2023-01-06T00:00:00Z", "upper": "2023-02-06T23:59:59Z" } } I tried setting the format to '%Y-%m-%dT%H:%M:%SZ', but this still returns lower and upper values as datetime type. (datetime) 2023-02-06 23:59:59+00:00 How do I get these values as string? -
how to integrate django web login with snowflake 'users' table
i have a django application that carries authentication by requesting a token through MSAL. once i have that token, i will check if that username exists the the local django sqlite db and if it exists, he will be logged into the website. if the username doesnt exist, then the username will be recorded in the sqlite db and the user just need to enter his credentials for authentication and will be logged in. what i would like to do is to replace the sqlite db with a snowflake table, which should only have a username and email column. how can i go about doing it? i am thinking that i need to write a customer user class and specifying the correct table in the class meta, switch the database in settings.py to the correct snowflake database. is there anything else needed? -
How to access variable all over django project?
Hy there, I want to define variable that store queryset suchthat variable to be access all over django function and classes. for eg My project contain different app shop common cart users with in users model, i have from django.conf.settings import get_user_model User=get_user_model() class BlockUser(models.Model): blocked_by=models.ForeignKey(User,on_delete=models.CASCADE) get_blocked=models.ForeignKey(User,on_delete=models.CASCADE) while calling every views function i am checking given user is blocked or not, like in shop views class ShopViewset(viewset.ModelViewset): def get_queryset(self,request): queryset=Shop.objects.all() if request.user.is_authenticated: blocked_user=BlockUser.objects.filter(get_blocked=request.user).values_list('blocked_by', flat=True) queryset=queryset.exclude(user__in=blocked_user) return queryset I am calling blockuser queryset everytime with in common,cart and other views. I just want to access that blockuser queryset all over project by defining in one place with middleware or if possible then from context processor and other but not from common function. -
How to automatically fill all info in the 2nd payment but not 3rd or 4th payments in Stripe?
With the Django's code below, I'm testing payment_method_options.card.setup_future_usage in Stripe Checkout in test mode: # "views.py" def test(request): customer = stripe.Customer.search(query="email:'test@gmail.com'", limit=1) print(customer.has_more) checkout_session = stripe.checkout.Session.create( customer=customer["data"][0]["id"] if customer.has_more else None, line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", "description": "Good T-shirt", }, }, "quantity": 2, } ], payment_method_options={ # Here "card": { "setup_future_usage": "on_session", }, }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303) For the 1st payment with mytest@gmail.com, I need to manually fill all info as shown below: But, even for the 2st and 3rd payments with mytest@gmail.com, I still need to manually fill all info without automatically filled shown below: Finally, for the 4th payment with mytest@gmail.com, all info is automatically filled as shown below: So, how to automatically fill all info in the 2nd payment but not 3rd or 4th payments in test and live modes? -
How to add condition in django-widget-tweaks checkbox form (checked and disabled if attributes is existed)
I'm using django-widget-tweaks and dynamic-field to render my form. This form is use to crete a new Line. User need to select Department (one line has one department) and Process (one line has many process) forms.py class LineForm(DynamicFormMixin, forms.Form): def process_choices(form): department= form['department'].value() return Process.objects.filter(department=department) name = forms.CharField(label='Line Name', max_length=100) department = forms.ModelChoiceField( queryset = Department.objects.all(), initial = Department.objects.first() ) # process field process = DynamicField( forms.ModelMultipleChoiceField, queryset=process_choices, required=False, label="Process", widget=forms.CheckboxSelectMultiple(), models.py class Process(models.Model): process_id = models.AutoField(db_column='Line_ID', primary_key=True) name = models.CharField(db_column='Line_Name', max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) masterLine = models.ForeignKey(MasterLine, null=True, on_delete=models.SET_NULL) From the relationship in the model, how can I customized the checkbox by adding a condition: if process already have line associated with it, the process will checked and disabled -
How to update several product lines at the same time [closed]
Hello I would like some help I am a django beginner and I am making a stock management application I register the articles in a model and I manage the stock in and out my problem is that I want to update several articles at the same time select article 1 quantity article 2 quantity up to article n and save in base who to update the stock of each product. but I don't know how to do it. Currently I can do for one product. thank you for giving me directions -
Having trouble with notifications feature in Django
Created a notification feature in my django project. I've got all the functionality down and it works except for one thing. I want the template to display a different message depending on what action is committed. All it currently displays is 'The ticket has been updated' instead of 'A new ticket has been assigned to you.' How do I fix this? Here is what i have so far. template <div class="dropdown-content" id="myDropdown"> {% if notifications %} {% for notification in notifications %} {% if notification.notification_type == 'created' %} <a href="#">{{notification.ticket.name}}: A new ticket has been assigned to you.</a> {% else %} <a href="#">{{notification.ticket.name}}: The ticket has been updated.</a> {% endif %} {% endfor %} {% else %} <a href="#">No new notifications</a> {% endif %} </div> models.py for notification class Notification(models.Model): OPTIONS = ( ('created', 'created'), ('updated', 'updated'), ) recipient = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='notifications') ticket = models.ForeignKey(Ticket, on_delete=models.SET_NULL, null=True, related_name='notifications') message = models.TextField() notification_type = models.CharField(choices=OPTIONS, max_length=15, null=True) is_read = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) signals.py for notification @receiver(post_save, sender=Ticket) def create_notification(sender, instance, created, **kwargs): if created: notification_type = 'created' else: notification_type = 'updated' assignees = instance.assignee.all() for assignee in assignees: Notification.objects.create(recipient=assignee, notification_type=notification_type) this is createTicket function inside the views.py @login_required … -
Simple proxy service using Django
The idea of the service is that we can control the traffic and where it goes.The routing rules can be based on URI endpoint, HTTP headers or JSON-RPC fields. Each individual rule can be provided via JSON (or Jsonnet) and stored in Redis. I expected to have django app that can handle traffic and help me to solve a problems during migrations from monolit app to microservices. -
Why is my django function working when I test it in Postman but when I use my frontend its not?
I'm having an issue with creating a session in Django. The biggest issue is when debugging as the function works as expected when I run it in postman but not when I try to use my frontend which is built in React. I checked to make sure the data was being passed as expected and being received by the function in the backend and it is. But for some reason the session isn't working correctly. The code is outlined below. In the views.py of my login app, the session is created in this function to track the user_id so that I can update the MongoDB document later on. @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at … -
Django project gives me the following error AttributeError: 'SafeExceptionReporterFilter' object has no attribute 'get_safe_settings'
I'm currently creating a wep app using django with react and django toolbar. The same project worked a weeks ago, but now it gives me this error message. This is the first time I'm using django, i have no idea what's the problem. Exception ignored in thread started by: \<function check_errors.\<locals\>.wrapper at 0x0000018E6BC28310\> Traceback (most recent call last): File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\autoreload.py", line 225, in wrapper fn(\*args, \*\*kwargs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\commands\\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\base.py", line 376, in check all_issues = self.\_run_checks( File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\base.py", line 366, in _run_checks return checks.run_checks(\*\*kwargs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\urls.py", line 23, in check_resolver return check_method() File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\functional.py", line 37, in __get__ res = instance.__dict__\[self.name\] = self.func(instance) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\functional.py", line 37, in __get__ res = instance.__dict__\[self.name\] = self.func(instance) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\\Users\\nagyd\\AppData\\Local\\Programs\\Python\\Python39\\lib\\importlib_init_.py", line 127, in import_module return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1030, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 1007, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 986, in \_find_and_load_unlocked File "\<frozen importlib.\_bootstrap\>", … -
migrate postgresql database to sqlite3 in Django
There have been any suggestions for migrating sqlite3 database to postgresql in Django, but I cannot migrate postgresql to sqlite3. Your suggestion would be highly appreciated. -
Django logging does not work properly and logs are not saved to dedicated files
I'm trying to do logging in Django. I want the all_logs handler to write all logs to a common file. The error_file handler writes logs to the error file, warning_file to the warning file, and info_file to the informative message file. But as a result I see errors in the error_file and I see everything in the info_file: info, warnings and errors. And there is no warning_file at all. Only the handler for recording all_logs works well. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} | {threadName}({thread}) [{levelname}] {message} ({name} {module}:{lineno})', 'style': '{', }, 'simple': { 'format': '{asctime} [{levelname}] {message} ({name}:{lineno})', 'datefmt': '%H:%M:%S', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'all_logs': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': str(BASE_DIR.joinpath('log', 'all.log')), 'formatter': 'verbose', }, 'error_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'error.log')), 'formatter': 'verbose', }, 'warning_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'error.log')), 'formatter': 'verbose', }, 'info_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'info.log')), 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['all_logs', 'console', 'error_file', 'warning_file', 'info_file'], 'propagate': False, 'formatter': 'verbose' }, # my app 'applications': { 'handlers': ['all_logs', 'console', 'error_file', 'warning_file', 'info_file'], 'propagate': False, 'formatter': 'verbose' }, }, … -
Opinion! Creating Template filters to work with class instance in templates, this works, wondering the most "django" optimal way?
Accessing class methods in templates, this works but was wondering if their was a better way? someclass class Something(): somevar = None def __init__(self, somevar): self.somevar = somevar def set_somevar(self, newvar): self.somevar = newvar def set_weird_and_somevar(self, weird, somevar): self.weird = weird self.somevar = somevar def get_tag(self, tag): templateTag from django import template register = template.Library() @register.filter def class_get_method(value, method): f = method.split('.') method = f[0] del f[0] p = getattr(value, method) if f: return p(*f) else: return p() in template, lets say content is a class instance {{content|class_get_method:'set_weird_and_somevar.wenday_adams.nothervar'}} -
Can't get get product id in react-redux to call django api
I am building a full-stack e-commerce project with react, django and redux-react. I was not having this problem when I used const [product, useProduct] = useState([]) const {id} = useParams() but when I implemented redux reducers I changed my ProductScreen.js productScreen function and useEffect like this: import React, {useState, useEffect} from 'react' import { Link, useParams } from 'react-router-dom' import { Row, Col, Image, ListGroup, Button, Card } from 'react-bootstrap' import Rating from '../components/Rating' import { useDispatch, useSelector } from 'react-redux' import { listProductDetails } from '../actions/productActions' function ProductScreen() { const { id } = useParams(); const dispatch = useDispatch() const productDetails = useSelector(state => state.productDetails) const { loading, error, product } = productDetails useEffect(() => { dispatch(listProductDetails(id)) }, []) I have fail, success and loading components in a several file and as constants. this is my product detail reducer: export const productDetailsReducer = (state={product:[]}, action) =>{ switch (action.type) { case PRODUCT_DETAILS_REQUEST: return { loading: true, ...state } case PRODUCT_DETAILS_SUCCESS: return { loading: false, product: action.payload } case PRODUCT_DETAILS_FAIL: return { loading: false, error: action.payload} default: return state } } and lastly, this is my listProductDetails in productActions.js export const listProductDetails = (id) => async ( dispatch ) => { … -
using custom domain for a django page through traefik
i have my first custom domain (its through godaddy) ive hooked it up to cloudflare. i want to connect to it with traefik. i have a django webpage that works fine on port 8000, so i switched it over to 80 (because thats what i think i need to for traefik to see it) and no dice. trying to connect to my custom domain just hangs and the port gives me a 404 error. traefik dashboard looks fine and so do my records on cloudflare (as far as i can tell ive never done this) i was hoping someone could help me connect to my django page through my custom domain. is there anything ive done in the evidence provided below that looks wrong? is there anything else you would need to see? my docker-compose.yml is below version: "3.3" services: traefik: image: "traefik:v2.9" container_name: "traefik" command: #- "--log.level=DEBUG" - "--api.insecure=true" - "--providers.docker=true" - "--providers.docker.exposedbydefault=false" - "--entrypoints.web.address=:80" ports: - "80:80" - "8080:8080" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" frontend: build: frontend image: frontend container_name: frontend # ports: # - 8000:8000 labels: - "traefik.enable=true" - "traefik.http.routers.whoami.rule=Host(`tgmjack.com`)" - "traefik.http.routers.whoami.entrypoints=web" below is a collection of screenshots demonstrating each thing. -
Django: Why does this query get the pk numbers instead of the names when downloading an excel?
Beginner at django here: I have the following code for downloading an excel document from my homepage: class ExcelDownloadAllView(TemplateView): def get(self, request, *args, **kwargs): columns = ['Project Number', 'Assignee', 'Priority', 'Status', 'title','Summary', 'created_by'] rows = BugTracker.objects.all().values_list('project_number','assignee','priority','status', 'title', 'summary', 'author', ) filename ='All_Projects.xls' return create_sheet_response(filename, columns, rows) def create_sheet_response(filename, columns, rows): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={filename}' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('All Projects Data') # this will make a sheet named Projects Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response #models class Developer(models.Model): firstname = models.CharField(max_length=30, default="To be") lastname = models.CharField(max_length=30, default="Assigned") email = models.EmailField(blank=True) def __str__(self): return self.firstname + " " + self.lastname def get_absolute_url(self): return reverse("developer_list") class BugTracker(models.Model): project_number= models.IntegerField(primary_key=True) assignee= models.ForeignKey(Developer, on_delete=models.CASCADE, null=True) priority = models.CharField(max_length=10, choices=priority_choices) title = models.CharField(max_length=70) summary=models.TextField() status= models.CharField(max_length=20, choices=progress, default="Open") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created_at=models.DateTimeField(default=timezone.now) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.summary def get_absolute_url(self): return reverse("bug_list") It creates the excel file successfully, but it downloads … -
Django with Celery on Digital Ocean
The Objective I am trying to use Celery in combination with Django; The objective is to set up Celery on a Django web application (deployed test environment) to send scheduled emails. The web application already sends emails. However, the ultimate objective is to add functionality to send out emails at a user-selected date-time. However, before we get there the first step is to invoke the delay() function to prove that Celery is working. Tutorials and Documentation Used I am new to Celery and have been learning through the following resources: First Steps With Celery-Django documentation: https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#using-celery-with-django A YouTube video on sending email from Django through Celery via a Redis broker: https://www.youtube.com/watch?v=b-6mEAr1m-A The Redis/Celery droplet was configured per the following tutorial https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-redis-on-ubuntu-20-04 I have spent several days reviewing existing Stack Overflow questions on Django/Celery, and tried a number of suggestions. However, I have not found a question specifically describing this effect in the Django/Celery/Redis/Digital Ocean context. Below is described the current situation. What Is Currently Happening? The current outcome, as of this post, is that the web application times out, suggesting that the Django app is not successfully connecting with the Celery to send the email. Please note that towards the … -
How to create notification on a webpage
This question is related to backend development. I am an intermediate-knowledge university student working in this field. For my project, I am developing a website that alerts the user if something's missing from its place. For example, a valuable thing is placed under the scrutiny of CCTV. Then I detect the object using Image processing and as the thing is gone, I want to raise an alert. I have done Image processing and am able to detect the presence/absence of the object on my local machine. I want to deploy such a thing on the server for end-consumer usage. But then how to do this on the server because then two things need to be done at once, the video needs to be continuously processed, and when there is an alert, a notification should be kept in the notification feed (just like any social media platform), while also continuously monitoring the video. I am familiar with Django. In a nutshell, I want to understand how social media websites, also sometimes show notifications while we are scrolling the feed. How two things are managed at one time? Thank you for the help. Regards. -
React: Invariant failed: You should not use <Route> outside a <Router> after installing latest react router dom?
I installed the latest version of react-router-dom which is 6.0.2 then i started getting these error, what could be the problem. This is my App.js where i am implementing the routing functionalities import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; <Router> <div className="flex flex-col min-h-screen overflow-hidden"> <AuthProvider> <Navbar /> <Switch> <PrivateRoute component={ProtectedPage} path="/protected" exact /> </Switch> </AuthProvider> <Footer /> </div> </Router> -
Django Query number list and return selected rows
I am creating scoreboard view for button counts. The model is simply user id and count. API must return "id", "count" and "position" on leaderboard. If no id provided, it simply returns top three. But if there is id, aditionaly to top three, I must provide the position of id on leaderboard. The problem is, when I use Window( RowNumber() ), and then attempt to select by id, the whole query runs on that one selected item. So the "position" is always 1. I found dirty solution to practically take raw query after Window, and then selecting by id. In that case, proper "position" remains. But I feel there is a better way to do it. I would really appreciate any suggestions Using: sql, params = queryset.query.sql_with_params() queryset = queryset.raw(f"SELECT ...", params) -
Celery. RuntimeError: can't start new thread
I use Celery (Redis as brocker) to send telegram messages (using Telegram Bot API). My VPS has 4 shared CPUs. I divide the list of recipients into groups of 5 people; every 1-3 seconds, the bot sends messages to these groups. The problem is that when testing (~2000 receivers) at a certain point, my tasks fail due to a RuntimeError: can't start new thread error (while the CPU load does not exceed 15% and when using ulimit -u I get 7795 (which is more than the number of users for which the task is being created)). Please tell me what the problem is and how it can be solved. models.py class Post(models.Model): text = models.TextField(max_length=4096, blank=True, null=True, default=None, verbose_name="Text") @receiver(post_save, sender=Post) def instance_created(sender, instance, created, **kwargs): if created: pre_send_tg.apply_async((instance.id,), countdown=5) tasks.py def chunks(lst, n): res = [] for i in range(0, len(lst), n): res.append(lst[i:i + n]) return res @celery_app.task(ignore_result=True) def pre_send_tg(post_id): try: Post = apps.get_model('news.post') TelegramUser = apps.get_model('tools.telegramuser') post = Post.objects.get(id=post_id) users = [x.tg_id for x in TelegramUser.objects.all()] _start = datetime.datetime.now() + datetime.timedelta(seconds=5) count = 0 for i in chunks(users, 5): for tg_id in i: send_message.apply_async((tg_id, post.text), eta=_start) if count % 100 == 0: _start += datetime.timedelta(seconds=random.randint(50, 60)) else: _start … -
How can I write files in input tag?
In this code, I display images from storage. {% for car_img in car_src_images %} The problem is there can be changes (delete, add) new images and input nothing known about it. For example, 2 images are rendered, input is empty. If add a new image it will write only added image (not rendered). So how can I trigger or write in FormData or input rendered images? <div class="upload__box"> <div class="upload__btn-box"> <label class="upload__btn"> <p>Upload images</p> <input type="file" multiple="" id="images" name="id_images" data-max_length="20" class="upload__inputfile"> </label> </div> <div class="upload__img-wrap"> {% for car_img in car_src_images %} <div class="upload__img-box"> <div style="{{ car_img.img_data }}" data-number="0" data-file="{{ car_img.img_filename }}" class="img-bg"><div class='upload__img-close'></div></div> </div> {% endfor %} </div> </div> -
Uploading video gets stuck between 40 - 45 % Gunicorn + Nginx + Django
Video is 385mb here is my nginx conf server { listen 85; send_timeout 120; http2_max_field_size 64k; http2_max_header_size 64k; client_max_body_size 1000M; client_body_buffer_size 4096M; client_body_timeout 350; client_body_temp_path /home/mrlonely/lumendjango/media; location = /favicon.ico { access_log off; log_not_found off; } location /static { autoindex on; alias /home/mrlonely/lumendjango/staticfiles; } location /media { client_max_body_size 1000m; autoindex on; alias /home/mrlonely/lumendjango/media; } location / { include proxy_params; proxy_pass http://unix:/home/mrlonely/lumendjango/lumen.sock; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header Host $host; proxy_redirect off; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; proxy_read_timeout 1200; } } It give me : net::ERR_CONNECTION_CLOSED Ive tried different things as you can see above, but i dont think the problem is with Nginx or Gunicorn, can't find anything good online. Can someone help me? If you need to see additional info please tell me, I dont know what else to put here. -
How to filter one-to-many relationship with django rest api?
I have a one-to-many relationship like: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length= 000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name class Animal(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='animals') date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length=1000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "animal" verbose_name_plural = "animals" def __str__(self): return self.name and serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id','category_id','name', 'description'] class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] and urls: from . import views urlpatterns = [ path('', CategoryViewSet.ApiOverview, name='home'), path('all/', views.view_items, name='view_items'), path('all/<int:id>/', views.detail_item ), ] views.py: @api_view(['GET']) def view_items(request): queryset = Category.objects.all() serializer = CategorySerializer(queryset, many=True) # checking for the parameters from the URL if request.query_params: items = Category.objects.filter(**request.query_params.dict()) serializer = CategorySerializer(items , many=True) else: items= Category.objects.all() serializer = CategorySerializer(items , many=True) # if there is something in items …