Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refreshing a Div every x second in django
I want to refresh a div which contains a table in Django every x second. I've tried every code on stack overflow and whole net with the similar question but surprisingly none of them works. some of the links that I've used are : Refresh div using JQuery in Django while using the template system Django dynamic HTML table refresh with AJAX my table in the index html: <div id="table" class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="data-table-list"> <div class="basic-tb-hd"> <h1 class="basic_table"> جدول گزارش تردد<span class="breadcomb-report"> <button data-toggle="tooltip" data-placement="left" title="دانلود گزارش" class="btn"><i class="notika-icon notika-sent"></i></button> </span></h1> </div> <div class="table-responsive"> <table id="data-table-basic" class="table table-striped"> <thead> <tr> <th>پلاک</th> <th>مجوز عبور </th> <th>ساعت عبور</th> <th>تاریخ عبور</th> </tr> </thead> <tbody> {% for data in Taradod_list %} <tr style="cursor: pointer;" onclick="window.location='{{ data.get_absolute_url }}';"> <td class="persianTable">{{ data.plate }}</td> {% if data.approved == True %} <td> <button class="disabled button-icon-btn btn btn-success success-icon-notika btn-reco-mg "><i class="notika-icon notika-checked"></i></button> <p class="hidden">True</p></td> {% endif%} {% if data.approved == False %} <td><button class="disabled button-icon-btn btn btn-danger danger-icon-notika btn-reco-mg"><i class="notika-icon notika-close"></i></button> <p class="hidden">False</p></td> {% endif %} <td class="persianTable">{{data.seen.hour}}:{{ data.seen.minute }}:{{ data.seen.second }}</td> <td class="persianTable">{{data.seen.date}}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> </tr> </tfoot> </table> </div> </div> </div> url: path('', views.index, name='index') index view: def index(request): Taradod_list … -
How do i output data from python django to html
I am scraping the ncdc website and i want to output the result in my html file The html file is rendering only the last value in the list here is my web scraper code In my views.py i have this function def feed(request): URL = 'https://ncdc.gov.ng/news/press' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') results = soup.find(id='example') news_elems = results.find_all('div', class_='col-sm-10') for news_elem in news_elems: title_elem = news_elem.find('h3') date_elem = news_elem.find('h4') # sub_elem = news_elem.find(id='text') link_elem = news_elem.find('a', class_='white-text') if None in (title_elem, date_elem, link_elem): continue title = print(title_elem.text.strip()) date = print(date_elem.text.strip()) link = print(link_elem.get('href')) space = print() title = title_elem.text.strip(), date = date_elem.text.strip(), link = link_elem.get('href') context = {'title': title, 'date': date, 'link': link, 'space': space} return render(request, 'feed.html', context) this is my feed.html code <div class="card card-primary card-outline"> <div class="card-header"> <h5 class="card-title m-0">News Feed</h5> </div> <div class="card-body"> <h6 class="card-title">{{title}}</h6> <p class="card-text">{{date}}</p> <a href="https://ncdc.gov.ng{{link}}" class="btn btn-primary">Read More</a> </div> </div> The output is only returning the last value in the list of tuples. I want it to return the title, date and link for each item in the list -
I have a 404 error in my console when i click a function button
I have a simple add and remove button for a cart, but whenever i click on the button, i get an error in the console, please bear in mind, i a newbie: cart.js:25 POST http://127.0.0.1:8000/update_item/ 404 (Not Found) updateUserOrder @ cart.js:25 (anonymous) @ cart.js:14 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 And this is the error i get in my terminal: Not Found: /update_item/ This is the code in cart.js: function updateOrder (ticketId, action){ console.log('User is logged in, sending data..') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'ticketId': ticketId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } This is my views.py code: def updateItem(request): data = json.loads(request.body) ticketId = data['ticketId'] action = data['action'] print('Action:', action) print('ticketId:', ticketId) customer = request.user.customer ticket = Ticket.objects.get(id=ticketId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, ticket=ticket) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) -
Django Unit Testing A Button (Not Form)
Im writing unit tests for a Django package (Django-Notifications) and want to unit test that a notification is deleted when the 'delete' button is pressed. I know how to test forms: response = self.client.post( reverse('webpage'), data={ 'question': 'some question'}, HTTP_REFERER=referer, follow=True ) And I know how to mock users and sign them in, but have no idea how to unit test non-form buttons =. More specifically, I dont know how to: Create the mock notification Test that the button successfully removes the notification (Perhaps this is something that should only be functional tested?) This is all I have so far: def test_delete_button_removes_notification(self): user = User.objects.create_superuser('username') self.client.force_login(user) # create notification # simulate button press # assert notification count == 0 Thank you. -
render() got an unexpected keyword argument 'renderer'
I'm trying to use django-messages to enable user to user messaging on my website. when I'm setting it up, I encountered this error when I'm trying to access the compose page. TypeError at /messages/compose/ render() got an unexpected keyword argument 'renderer' Upon checking the logs, it points to the package's render function in one of the files. the code is return render(request, template_name, {'form': form}) I checked on this answer also here on SO: Django TypeError: render() got an unexpected keyword argument 'renderer'. I tried adding the other parameters but it seems the additional parameters are not being recognized as well. it is saying that attrs and renderer are unrecognized parameters. I'm also using django 2.2 version so I'm thinking it's not with the backwards compatibility issue. The weird thing is, I have another file the uses the render function the same way, and it works alright. also, as suggested from the link I referenced, is to check the widgets.py file which I did, and here's how it looks def render(self, name, value, attrs=None, renderer=None): print('I got called yo') """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) It just got me more … -
How to pass a pk of an object to a template form
the scenario is as follows: objects: race, racers, registration I am trying to use a form to offer users the possibility to register to race. forms: class RegisterRace(forms.ModelForm): class Meta: model = registration fields = ("race_id", "racer_id"") url: path('register-race/', views.race_register, name='race_register'), views: def race_register(request): if request.method == "POST": c = request.POST.get('race') # this line is ONLY for debugging race = Race.objects.get(pk=request.POST.get('race')) form = RegisterRace(request.POST) if form.is_valid(): form.save() return redirect('races') else: form = RegisterRace() return render(request, 'race_registration.html', {'form': form, 'rc': race}) race_detail template contain the following link : <form action="/register-race/" method="POST">{% csrf_token %} <input type="hidden" name="race" value="{{event.pk}}"> # where event is the current race <input type="submit" value="REGISTRATION" class="btn btn-large btn-primary"> </form> race_registration.html template contain: <form action="/register-race/" method="POST" enctype="multipart/form-data" class="form-horizontal">{% csrf_token %} <input type = "hidden" name = "race_id" value="{{rc.pk}}"> # for debugging purpose here I have also tried with value="{{c}}" <input type = "hidden" name = "racer_id" value="{{request.user.pk}}"> <button type="submit" class="btn btn-primary">REGISTER MYSELF</button> </form> When I hit the Registration button the following error occurs: DoesNotExist at /register-race/ Race matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/register-race/ Django Version: 3.0.2 Exception Type: DoesNotExist Exception Value: Race matching query does not exist. Exception Location: C:\Users-----\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py in get, line 415 Traceback: … -
How to filter parents set with Many to Many through model with additional fields in Django REST
I have two models with through model with additional field: class User(models.Model): mobile_phone_number = models.CharField(max_length=25, null=False) full_name = models.CharField(max_length=250, null=True) user_gadget_token = models.CharField(max_length=500, null=True) class Device(models.Model): label = models.CharField(max_length=250) address = models.CharField(max_length=500, null=True) ip = models.CharField(max_length=50) users = models.ManyToManyField(User, through='DeviceUsers') class DeviceUsers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) device_label_custom = models.CharField(max_length=250, null=True) Viewsets (with NestedViewSetMixin from DRF-extentions): class UserViewSet(NestedViewSetMixin, viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(NestedViewSetMixin, viewsets.ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer Serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'full_name', 'mobile_phone_number', 'user_gadget_token' ] class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = [ 'id', 'label', 'deviceusers_set', 'address', 'ip' ] and urls: from rest_framework_extensions.routers import ExtendedSimpleRouter nested_router = ExtendedSimpleRouter() nested_router.register(r'users', views.UserViewSet)\ .register(r'devices', views.DeviceViewSet, basename='users-devices', parents_query_lookups=['users__user_gadget_token']) urlpatterns = [ url(r'^', include(nested_router.urls)) ] So when I request url: http://127.0.0.1:8000/api/v1/users/ugt1/devices/ I've got result: "results": [ { "id": 1, "label": "device #1", "deviceusers_set": [ 1, 2 ], "address": "some street", "ip": "10.0.0.1" }, And my question is how can I get "device_label_custom" with relation to selected user (in url path) instead of: "deviceusers_set": [ 1, 2 ], The result should be like: "results": [ { "id": 1, "label": "device #1", "device_label_custom": "Device named by user … -
don't apply css styles in django
Yesterday i was working on a Django-project: added css rules and all worked, but today all stay ass yesterday, but css rules don't apply=( Everything was fine yesterday, but nothing is applied this morning. Today all stay as yesterday, but css styles do not apply HTML code: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <link rel="stylesheet" href="{% static 'Css/style.css' %}"> <meta charset="utf-8"> <title>Main page</title> </head> <body> <header style=" background-image: url({% static 'Img/1.jpg' %})"> <div class="intro"> <h1><span class="wel">Wel</span><span class="come">come</span></h1> <h3><em class="a">to the best site in the World!</em></h3> </div> </header> <main> </main> <footer> </footer> </body> </html> and the css code: * { font-family: arial, helvetica } header { width: 100%; height: 400px; } .intro { # This i want to change width: 100%; height: 200px; padding-left: 300px; font-size: 30px; padding-top: 100px; } .wel { color: #8495E1 } .come { color: #C886A5 } .a { font-size: 20px; color: #0F1D37; } -
Mail service isn't working using Django, Docker and UFW
everyone! Can't make mail ports working with Docker, UFW and Django Project. I got the following error [Errno 99] Cannot assign requested address. When UFW is off everything works fine. I tried to open ports in Docker (25, 53, 587 etc., see below) but it doesn't resolve the problem. I have the following settings: Django's .env EMAIL_HOST=smtp.yandex.ru EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST_USER=test@example.com EMAIL_HOST_PASSWORD=secret Docker Compose YML version: '3.7' services: web: image: django_image:latest restart: unless-stopped command: gunicorn project_name.wsgi:application --bind 0.0.0.0:8000 --workers=2 --timeout=1200 volumes: - ./:/usr/src/app/ expose: - 8000 # ports: # - "25:25" # - 587:587 # - 143:143 # - 993:993 # - 995:995 # - 465:465 # - 110:110 networks: - app-network env_file: - ./.env nginx: image: nginx_image:latest restart: unless-stopped volumes: - ./:/usr/src/app/ - /etc/letsencrypt/:/etc/letsencrypt/ ports: - 80:80 - 443:443 networks: - app-network depends_on: - some_django_image networks: app-network: driver: bridge So that Docker doesn't change iptables I have added the /etc/docker/daemon.json containing {"iptables": false} UFW settings Status: active To Action From -- ------ ---- [ 1] 22/tcp ALLOW IN Anywhere [ 2] 80/tcp ALLOW IN Anywhere [ 3] 443/tcp ALLOW IN Anywhere [ 4] 21/tcp ALLOW IN Anywhere [ 5] 25 ALLOW IN Anywhere [ 6] 53 ALLOW IN Anywhere [ … -
Django template issue loading
i downloaded a template and loaded in django, I formatted all the href to django format but it will only load when I open in browser nothing will open <!-- CSS here --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/ticker-style.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/slicknav.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/animate.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/fontawesome-all.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/themify-icons.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/slick.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/nice-select.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> -
How to handle exception in django context_processor?
Here I am writing some codes to create and display notification objects. But when I logout then it throws below error. How can I handle this ? File "D:\..\venv\lib\site-packages\django\template\base.py", line 169, in render with context.bind_template(self): File "C:\..\AppData\Local\Programs\Python\Python37-32\lib\contextlib.py", line 112, in __enter__ return next(self.gen) File "D:\..\venv\lib\site-packages\django\template\context.py", line 246, in bind_template updates.update(processor(self.request)) Exception Type: TypeError at /users/login Exception Value: 'NoneType' object is not iterable context_processors.py def list_notifications(request): try: notifications = Notification.objects.filter(is_read=False, user=request.user).order_by('-created') return {'notifications': notifications} except Exception as e: print(e) def create_notification(request): try: completed_tasks = Task.objects.filter(status=2) for task in completed_tasks: Notification.objects.get_or_create(user=task.created_by, task=task) except Exception as e: print(e) return {'none': 'none'} -
How do I handle django media in my local network?
I have a problem with loading Django media files in my local network. Here is my settings.py INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py class Video(models.Model): video_file = models.FileField(upload_to='video/') description = models.CharField(max_length=500, blank=True) Media accessing example: <video height="300px" controls> <source src="{{ video.video_file.url }}" type="video/mp4"> </video> After running: python manage.py runserver 0.0.0.0:15000 I go to my website from the same PC I run Django, I'm able to see my media files such as video but if I go to my website from another PC, the website is working, static files are loaded but media files are not. Is there any way to access media files from other PCs? -
django bootstrap navbar dropdown elements not coming on other url while using same base.html
I am new to django and creating one app. I have create two mode on is master and other is details. While using a bootstrap nav bar drop down on a single base.html i am able to get master records in drop down while i switch to different page when clicked any drop down element i didn't get drop down element. I am extending base.html in both the master as well as detail page. Please help with any option base.html index.html details.html models.py views.py and url.py -
Django Model Serializers
I'm learning how to use Django Rest Framework and I came out with a question that I can't get to answer. I understood that the concept of nested serializer but I think there should be a way to get a specific field in an "upper level" instead of "digging" trough levels. Let me better explain what I mean. I have Users which then are classified into 2 categories Customers (which are the default User category) and Drivers. All the Users have a Profile with their picture so I would like to obtain the name and the image in an API. The only solution I've been managing to find is the following class OrderProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ("id", "image") class OrderUserSerializer(serializers.ModelSerializer): profile = OrderProfileSerializer() class Meta: model = User fields = ("id", "profile") class OrderCustomerSerializer(serializers.ModelSerializer): name = serializers.ReadOnlyField(source="get_full_name") profile = OrderProfileSerializer() class Meta: model = User fields = ("id", "name", "profile") class OrderDriverSerializer(serializers.ModelSerializer): name = serializers.ReadOnlyField(source="user.get_full_name") user = OrderUserSerializer() class Meta: model = Driver fields = ("id", "name", "user") This is the JSON response { "shipping": { "id": 25, "customer": { "id": 14, "name": "Test Customer", "profile": { "id": 10, "image": "/media/profile_pics/default.jpg" } }, "driver": { "id": … -
UnboundLocalError: local variable 'pin' referenced before assignment
I have been working on making a website just like Pinterest and I am now working on Searching functionality with 'login_required' decorator. The view is not yet finished since I build this as I check whether the request goes through smoothly with Postman. However, the request doesn't even get to the first line of code in the view because I keep getting this error. Below is what I see when I test it with python debugger. -> return func(self, request, *args, **kwargs) (Pdb) n UnboundLocalError: local variable 'pin' referenced before assignment > /Users/woohyunan/projects/Wecode/pinterrorist-backend/pin/views.py(38)wrapper() Below is the SearchView part of the whole views.py: class SearchView(View): @login_required def post(self, request, *args, **kwargs): body = json.loads(request.body) user = kwargs['user'] user_id = kwargs['user_id'] search_term = request.POST.get('search', None) return JsonResponse({'search_term': search_term}) and below is the decorator: def login_required(func): def wrapper(self, request, *args, **kwargs): import pdb; pdb.set_trace() header_token = request.META.get('HTTP_AUTHORIZATION') decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['id'] user = User.objects.get(id=decoded_token) user_id = user.id kwargs['user'] = user kwargs['user_id'] = user_id try: if User.objects.filter(id=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "THE USER DOES NOT EXIST"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except KeyError: return JsonResponse({"message": "KEY ERROR"}, status=405) except User.objects.filter(email=decoded_token).DoesNotExist: return JsonResponse({"message": "USER NOT FOUND"}, status=406) return wrapper … -
Ensure at least one checkbox is selected - Django Forms
I'm using Django's forms functionality to create a signup page. I've three checkboxes (BooleanField's) and I want to implement validations to ensure that the user enters at least one option. This is the registration template <div class="form-check form-check-inline"> {{form.is_student}} <label class="form-check-label" for="inlineRadio1"> &nbsp{{form.is_student.label}}&nbsp</label> {{form.is_teacher}} <label class="form-check-label" for="inlineRadio2"> &nbsp{{form.is_teacher.label}}&nbsp</label> {{form.is_parent}} <label class="form-check-label" for="inlineRadio3"> &nbsp{{form.is_parent.label}}&nbsp</label> </div> This is form.py class SignUp_Form(forms.ModelForm): is_student = forms.BooleanField(label='Student', required=False, ) is_teacher = forms.BooleanField(label='Teacher', required=False) is_parent = forms.BooleanField(label='Parent', required=False) -
I can't connect view.py and url.py to html files
I have been learning Django and now working on the topic so-called "template tagging". It's the process to connect views.py file to HTML using "url" function. But I've gotten the message from Anaconda prompt when I tried to run the code, "AttributeError: 'list' object has no attribute 'endswith'". How can I make this program work? The code is below. ・app_file/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request,"My_app/index.html") def second(request): return render(request,"My_appp/second.html") def third(request): return render(request,"My_app/third.html") ・project_file/urls.py: from django.contrib import admin from django.urls import path,include from My_app import views from django.conf.urls import url urlpatterns = [ url('admin/', admin.site.urls), url("lp",views.index,name="lp"), url("My_app/",include("My_app.urls")) ] ・my_app/urls.py: from django.contrib import admin from django.urls import path from My_app import views from django.conf.urls import url app_name = "My_app" urlpatterns =[ url("second/",views.second,name="second"), url("third/",views.third,name="third") ] ・template/app_file/index.html: <!DOCTYPE html> {% load statics %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>My Django Practice</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="container">`enter code here` <div class="jambotron"> <h1>PAGE FOR INDEX</h1> <a href="{% url 'My_app:second' %}">LINK TO SECOND.HTML</a> </div> </div> </body> </html> ・template/app_file/second.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="jambotron"> <a … -
Foreign-key automatically fill in the form
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card how I can create an order form so that the customer in order is the instance and the shop in order is that shop which is selected to show the products and every card of the product have a field to fill the remaining detail and submit -
Phone number is not getting inside the if loop it is directly entering the else section can anyone
def post(self, request, *args, **kwargs): phone_number = request.data.get('phone') if phone_number: phone = str(phone_number) user = User.objects.filter(phone__iexact = phone) if user.exists(): return Response({ 'status': False, 'detail': 'Phone number already exists' }) else: key = send_otp(phone) print(key) if key: PhoneOTP.objects.create( phone=phone, otp=key, ) return Response({ 'status': True, 'detail': 'OTP Send Successfull' }) else: return Response({ 'status': False, 'detail': 'Sending otp error' }) else: return Response({ 'status': False, 'detail': 'Phone number is not given' }) def send_otp(phone): if phone: key = random.randint(999, 9999) return key else: return False -
404 error when serving MEDIA files in production
I have a website based on cookiecutter-django, Wagtail and Docker. I use default setup of cookiecutter with Django, Traefik, Postgres and Redis containers. Media files should serve directly, but after deployment I see this "Failed to load resource: the server responded with a status of 404 ()" - . The same happens in Wagtailadmin. Files upload works correctly (as it seems to me) to "app/media/images" in Django container. These are my Media settings: ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent MEDIA_ROOT = os.path.join(ROOT_DIR, 'media') MEDIA_URL = '/media/' This is Django Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 RUN apt-get update \ # dependencies for building Python packages && apt-get install -y build-essential \ # psycopg2 dependencies && apt-get install -y libpq-dev \ # Translations dependencies && apt-get install -y gettext \ # cleaning up unused files && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* RUN addgroup --system django \ && adduser --system --ingroup django django # Requirements are installed here to ensure they will be cached. COPY ./requirements /requirements RUN pip install --no-cache-dir -r /requirements/production.txt \ && rm -rf /requirements COPY ./compose/production/django/entrypoint /entrypoint RUN sed -i 's/\r$//g' /entrypoint RUN chmod +x /entrypoint RUN chown django /entrypoint COPY ./compose/production/django/start /start RUN sed … -
How do we make use of multiple user types in Django
I'm trying to create a web application which has 2 types of users i.e. students and universities. I want to have a different login page and different views after logging in for each of them. They need to have different permissions. I want the university to be able to list itself. The student needs to be able to view the list of all universities. Which is the best way to do this? I read other answers but I couldn't find a suitable solution to help me with this. As of now, I have managed to make use of the inbuilt User model to do the authentication but I read that it is not advised to do that. urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] Is there any website which explains how to use multiple user models as I searched for it and didn't find it. I am still new to Django so kindly help me out. Any site to help me learn this would be highly appreciated. -
edit images online but don't know how?
I want to create a website where user can upload a image and then choose functionality which to work on that image (I know it sounds like an online image editor but believe me it isn't like that), I am newbie in web development but know how to code in Python. The functionality which I spoke earlier is made of Python Function. So, I want to know how anyone can upload image and then by clicking at function the image gets edited accordingly. -
How to implement common info such as user id in django logger?
With modern applications using react and django, each request has information that I wanna use to persist and log. I wanna ask if there is a good implementation for the django logger. Here is an example. React -> API -> Django -> calls a function like create an user -> calls other functions and wanna do something like logger.info(f"user_id: {user_id} does this") but I don't wanna keep passing the user_id down. Is there something similar to a singleton or using metaclass to achieve this? Happy to hear other implementations as well or if there is something that I misunderstand here. Thank you! -
nginx server : cannot connect 128.0.0.1:8888
My error Unable to connect Firefox can’t establish a connection to the server at 127.0.0.1:8888. ls -l /etc/fdfs/ total 84 -rw-r--r-- 1 root root 1469 六月 14 10:10 client.conf -rw-r--r-- 1 root root 1461 六月 14 09:44 client.conf.sample -rw-r--r-- 1 root root 955 六月 14 14:31 http.conf -rw-r--r-- 1 root root 31172 六月 14 14:31 mime.types -rw-r--r-- 1 root root 3725 六月 14 14:22 mod_fastdfs.conf -rw-r--r-- 1 root root 7938 六月 14 10:02 storage.conf -rw-r--r-- 1 root root 7927 六月 14 09:44 storage.conf.sample -rw-r--r-- 1 root root 105 六月 14 09:44 storage_ids.conf.sample -rw-r--r-- 1 root root 7394 六月 14 10:25 tracker.conf -rw-r--r-- 1 root root 7389 六月 14 09:44 tracker.conf.sample my server ps aux |grep nginx root 29867 0.0 0.0 38152 616 ? Ss 14:41 0:00 nginx: master process ./nginx coco 30010 0.0 0.0 21532 1084 pts/2 S+ 14:55 0:00 grep --color=auto nginx /usr/local/nginx/conf http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 8888; server_name localhost; location ~/group[0-9]/ { ngx_fastdfs_module; } error_page 500 502 503 504 /50x.html; location = /50x.html { … -
How to show more content in django application?
I have developed template for viewing the group list in my django application. What I came to know is that, after more groups, the page is scrolling down. I am unable to see all the names of the groups. And also I want to view only 4 group names on the starting and then after clicking load more button, next 4 groups have to be shown. I am unable to do this. <div class="container"> {% for comment in comments %} <div id="com_div" class="comments-list"> <div class="media"> <img style="max-width: 30px" class="rounded-circle mr-2 mt-1" src="{{ comment.user.profile.image.url }}"> <div class="media-body"> <small class="media-heading user_name my_style">{{ comment.user.username }}</small> <small class="bg-light rounded text-dark">{{ comment.date|naturaltime }}</small><br> <small style="font-size: 14px">{{ comment.content }}</small> <p> <small style="font-size: 13px"> <a data-toggle="collapse" href="#ReplyBox{{ comment.id }}" role="button" aria- expanded="false" aria-controls="ReplyBox{{ comment.id }}"> Reply</a>{% if comment.user == user %} - <a href="{% url 'del_comment' post.slug comment.id %}">Delete</a>{% endif %} </small> </p>