Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does these two line of codes are not working? [closed]
i am done with the other static css like {% static "css/style.css" %} but, the below two line is not working. How can i done this? But the css link which contans direct sheet from internet is not working. -
Django: Why we need to create a users for our web application
I want to know what is the benefit of creating users for my web application.what actually users do with our web application. -
django rest framework with aws s3
i'm saving my files in an aws s3 when i make a get request i get these information : { "id": 5, "imageName": "testImage2", "url": "https://smartsight-storage.s3.amazonaws.com/image/testImage2-Picture1.png?AWSAccessKeyId=asd&Signature=ads } it should not share these information => AWSAccessKeyId=asd&Signature=ads how do i remove them thankx -
Django check if a session is expired
In my django project i have to check, before run an ajax call in my views.py check if my session is expire (maybe i use django db session) and redirect to lgin page in case. If i reload the page this appen automatically using django behaviour but if i call my function, if session is expired nothing appen, i would to check this and if expired redirect to login. I search for this but i don't understand a simple way to do this. Anyone have an idea about? so many thanks in advance -
What is the best way to check writers blog before making them publicly available with Django?
Recently, I have been practicing Django with creating a newspaper project. I wanted to create an environment where an author writes a blog, a superuser or somebody superior checks that block and approves it before publicly publishing them on the website. What are the ways to achieve it? Should I create a separate app for it or maybe a separate page that will only be available for superusers -
Django says TemplateNotFound even if the template is there
Can someone help me in figuring out where I went wrong? Project URLs from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('trips/',include('trips.urls')), path('customers/',include('customers.urls')), path('drivers/',include('drivers.urls')), path('vehicles/',include('vehicles.urls')), path('admin/', admin.site.urls), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) App URLs from django.urls import path from . import views urlpatterns = [ path('',views.customers, name='customers'), path('<int:pk>/', views.customer_details, name='customer_details'), ] App View from django.shortcuts import render, get_object_or_404 from .models import * # Create your views here. def customers(request): customers = Customer.objects.all().order_by('id') return render(request, "customers.html", {'customers': customers, 'custactive': "active"}) def customer_details(request, pk): customer = get_object_or_404(Customer, pk=pk) return render(request, "/customer_details.html", {'customer': customer}) How I'm calling the page <td><a href="{% url 'customer_details' pk=customer.pk %}">{{customer.name}}</a></td> I'm hoping to render the template at localhost/customers/id Help is really appreciated. -
Accept Unix timestamp as integer and convert to DateTimeField for saving in django
I have a model Travel need to accept Unix value from the outside like postman then convert to DateTimeField for saving the data class MyModel: class Meta: abstract = True def ToDateTime(self,timestamp): date=datetime.fromtimestamp(timestamp) return date Travel(MyModel): departure_at = models.DateTimeField() arrival_at = models.DateTimeField() Serializer class TravelSerializer(serializers.ModelSerializer): departure_at=serializers.DateTimeField(write_only= True) arrival_at=serializers.DateTimeField(write_only= True) class Meta: model=Travel fields = ('departure_at','arrival_at') def validate(self, attrs): attrs = self.add_departure_at(attrs) attrs = self.add_arrival_at(attrs) return attrs def add_departure_at(self,attrs): departure_at=attrs['departure_at'] obj=BaseModel() todate=obj.ToDateTime(int(arrival_at)) return todate Postman data { "departure_at": "1585750708", "arrival_at" : "1585664308", } but here I getting this error { "departure_at": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." ], "arrival_at": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." ] } How to solve this error? -
how can i resolve this problem is due to the project or is a django problem?
I'm starting with an existing project in Django. when i try to run the project for the first time: '''python manage.py runserver''' i had this error: ''' lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not PosixPath ''' -
Django: Allow User To Set Default TimeZone For Accurate DateTimeInput
I'm working on an app that's revolved heavily around users entering data based on very specific date and time inputs. By default my settings.py is: TIME_ZONE = 'UTC' USE_L10N = True USE_TZ = True As you probably already know.. this means all data will be set to timezone UTC in the database which in my PostgreSQL shows as such 2020-03-26 15:22:45+00 which is all good and gravy except that a user not in UTC+00 is still setting all their DateTime inputs too it. Resulting in inaccurate data. It seems the best measure would be to allow users to force a default timezone in their account settings page. I see less room for server, traveling, proxies, VPN, etc. issues going this route. An alternative route would be for the app to determine the timezone and then input it with the proper localization. I'm not totally sure the best approach but I still am leaning towards a fixed default time. Simplicity in development/maintenance is also a key factor I'm ruling in here. My question is what would be the best solution that would allow users to input their data knowing that they are entering it for the right timezone? Also, what is … -
How we get u.is_authenticated in login_required decorater in django
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator How we get u inside login_required method def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator Can anyone helps me to explain it's step by step execution as I'm using login_required in my urls as:- path( "affiliater/registers/", login_required(views.RegistersView.as_view(), login_url='/affiliater/login/'), name="registers" ) -
docker_entrypoint.sh can't access manage.py file when spinning up container from image - Jenkins,Django,Docker
I have containerized a Django app, and made it to work well on my local machine. But the same is not working on the Jenkins CI/CD pipeline Here is the Dockerfile FROM python:3.7.3 RUN apt-get update RUN apt-get install -y libldap2-dev libsasl2-dev libssl-dev RUN pip3 install pipenv ADD Pipfile Pipfile.lock /app/ WORKDIR /app RUN pipenv install ADD docker-entrypoint.sh /app/ ADD docker-entrypoint.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/docker-entrypoint.sh ...... ...... docker-entrypoint.sh #!/usr/bin/env bash echo "Apply database migrations...." python manage.py migrate echo "Starting server via manage.py...." python manage.py runserver 0.0.0.0:8000 ....... ...... docker-compose.yml django-server: build: context: ./local_app/ dockerfile: Dockerfile args: PIPENV_EXTRA: "--dev" restart: always command: docker-entrypoint.sh ports: - "8000:8000" stdin_open: true tty: true container_name: django-server When i executed the docker-compose file locally using docker-compose up It ran successfully without any error, and can access the django server in browser at http://localhost:8000 Project Structure local_app |-- docker-entrypoint.sh # We added the executable entry script here |-- Dockerfile # And the Dockerfile here `-- hello_django |-- hello | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- manage.py `-- requirements.txt But when I ran the same command in Jenkins pipeline as below timestamps { node () { stage ('1-pull-git-code - Checkout - … -
Docker can't find installed modules by pipenv in Django project
So I'm trying to build and run a docker image with pipfiles as the package handler. But even after a seemingly successful build, it cannot find the 'django' module. I am on Windows 10 by the way. Here is my pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django-jquery = "*" anyconfig = "*" asgiref = "*" crispy-forms-materialize = "*" django-crispy-forms = "*" django-ranged-response = "*" pytz = "*" six = "*" sqlparse = "*" Django = "*" Pillow = "*" [requires] python_version = "3.8" My Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN pip install pipenv RUN pipenv install COPY . /code/ CMD pipenv run python manage.py runserver And docker-compose.yml file version: '3' services: web: build: . command: pipenv run python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" Here is the docker build log $ docker-compose build --pull Building web Step 1/8 : FROM python:3.8 3.8: Pulling from library/python Digest: sha256:e02bda1a92a0dd360a976ec3ce6ebd76f6de18b57b885c0556d5af4035e1767d Status: Image is up to date for python:3.8 ---> d47898c6f4b0 Step 2/8 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 5330d9208341 Step 3/8 : RUN mkdir /code ---> Using cache ---> 57420ad117b3 Step 4/8 : WORKDIR /code ---> Using cache … -
Automatic monthly updation of data in django
I have been designing a daily expense website where user can enter the data and it displays it along with the total expense of the user. I want to change the total expense to monthly expense so that it shows zero at the starting of each month. Here is my html file for displaying that part: <h3 class='center'>Expenditure of this month: <span style="color:green;">{{ budget|floatformat:"-2" }}</span> dollars</h3> I have tried datetime library of python in views to change it: def app_view(request): bal_qs = [int(obj.cost) for obj in BudgetInfo.objects.filter(user=request.user)] now = [i.lstrip("0") for i in datetime.now().strftime("%d")] budget=0 if now[0]!='1': for obj in range(len(bal_qs)): budget=budget+bal_qs[obj] uzer_qs = BudgetInfo.objects.filter(user=request.user).order_by('-date_added') return render(request,'tasks_notes/index.html',{'budget':budget,'uzer':uzer_qs[0:5]}) But it's not changing the budget value monthly. How can I achieve it? -
How to register using subdomain field in django?
I want to register company details using subdomain so that the user can login using subdomain. I created models.forms and views but i am facing problem with rendering the form models.py class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=2000) sub_domain = models.CharField(max_length=30) user_limit = models.IntegerField(default=5) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Company fields = ['name', 'address', 'sub_domain', 'country'] def __init__(self, *args, **kwargs): self.request_user = kwargs.pop('request_user', None) super(RegistrationForm, self).__init__(*args, **kwargs) views.py class RegistrationView(AdminRequiredMixin, CreateView): model = Company form_class = RegistrationForm template_name = "company_register.html" def is_valid(self, form): company = Company.objects.create_company(form.cleaned_data['name'], form.cleaned_data['address'], form.cleaned_data['sub_domain'], form.cleaned_data['country']) company.save() return super(RegistrationView, self).form_valid(form) urls path('register/', RegistrationView.as_view(), name='register'), reg.html {% extends 'base.html' %} {% block content %} <h1>Registration</h1> <form method="POST" class="user-form"> {{ form.as_p }} <button class="btn btn-primary" type="submit">Submit</button> </form> {% endblock %} Where i have done mistake as i am a newbie can someone help me?Thanks -
How to tell django where to look for css fies?
I;m trying to build a website for an online store and when I ran my html files, I found that my css files are having no effect on my pages. How do I inform django where to look for it? Can anyone help me? -
Django, tried to add a field to exsting model raises error
I Have a Django rest framework API which contained the following model: class Points(models.Model): mission_name = models.CharField(name='MissionName', unique=True, max_length=255, blank=False, help_text="Enter the mission's name" ) latitude = models.FloatField(name="GDT1Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="GDT1Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) Iv'e added a User field, When trying to makemigrations and migrate it I get the following error: django.db.utils.ProgrammingError: column find_second_gdt_points.user does not exist LINE 1: SELECT "find_second_gdt_points"."id", "find_second_gdt_point... Which I don't get, of course, this column does not exist. This is what migartions are for, no? -
django charField accepting only numbers
I have this django charField and i want it to accept only numbers .How can we achieve this in django ? class Xyz(models.Model): total_employees = models.CharField(max_length=100) I want total_employees to accept only numbers and not strings from my client .I want to put a check on api end too . -
has_add_permission function throwing 403 Forbidden in Django admin
@admin.register(Book) class BookAdmin(NestedModelAdmin): list_per_page = 50 list_display = ('name', 'author', 'course_name', 'created_at', 'updated_at') inlines = [BookSectionInline] def has_add_permission(self, request): return False -
How can i share session between a java and a python-django app?
I have two web apps(one in java and one in python(django)), I want to share session between these two apps. Is it possible? If yes, how can i do that. Please share. Problem Statement: I am displaying some information related to a machine learning problem on java app page and upon clicking that info i am redirecting to the django-python webapp apge. I want my login in the java webapp to persist throught the django webapp page, so that i do not have to login again in the django app. This may sound like an overcomplicated situation to some but unfortunately that's how the client wants it. Any help is appreciated. Thanks in Advance. -
How do I use request.user in template
I am trying display different text to user on an empty tag. I was able to implement this correctly in other template, but I do not clearly understand why it is not displaying correctly in another template. For example, if user A login, I want only user A to see 'Find people to follow' , while other users to see 'No users'. def following_view(request, username): p = FriendRequest.objects.filter(from_user__username=username) all_profile_user=[] button_status_list=[] for user_obj in p: u = user_obj.to_user all_profile_user.append(u) friend = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status = 'not_friend' if len(FriendRequest.objects.filter(from_user=request.user).filter(to_user=u)) == 1: button_status = 'cancel_request_sent' button_status_list.append(button_status) context={'profile_and_button_status':zip(p, button_status_list), 'u':all_profile_user, 'following':p,} {% for data in profile_and_button_status %} #Button codes here {% empty %} #why this doesn't display {% for data.user != request.user %} No users {% endfor %} {% for data.user == request.user %} Find people to follow {% endfor %} {% endfor %} -
Django - Using TimeField() as a foreign key
I have a Meeting model which has meeting_hour getting its value from MeetingHour model. But I'm getting an error as follows after submitting form: Cannot assign "datetime.time(14, 0)": "Meeting.meeting_hour" must be a "MeetingHour" instance. I know its because of I'm not using MeetingHour as a foreign key correctly, but don't know how can I fix it. Here are my codes: models.py class MeetingHour(models.Model): hour = models.TimeField() def __str__(self): return self.hour class Meeting(models.Model): participant_name = models.CharField(max_length=50) participant_email = models.EmailField(max_length=50) meeting_date = models.DateField() meeting_hour = models.ForeignKey(MeetingHour, on_delete = models.CASCADE) is_scheduled = models.BooleanField(default=False) def __str__(self): return self.participant_name views.py def index(request): context = { 'schedules': Meeting.objects.all() } if request.method == "POST": participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = str(request.POST.get('date')) meeting_hour = str(request.POST.get('hour')) converted_meeting_date = datetime.strptime(request.POST.get('date'), "%Y-%m-%d").date() if meeting_date else None converted_meeting_hour = datetime.strptime(request.POST.get('hour'), "%H:%M").time() if meeting_hour else None subject = 'Meeting' message = f'Hi, {participant_name} ! \nYour meeting date: {meeting_date}, hour: {meeting_hour}' from_email = settings.SERVER_EMAIL recipient_list = [participant_email] send_mail(subject, message, from_email, recipient_list) if request.POST.get('email'): Meeting.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = converted_meeting_date, meeting_hour = converted_meeting_hour, is_scheduled = True ) return render(request, 'index.html', context) -
What Server provider is best for a Django-MySQL back end?
I just finished my 4 month project to create a mobile app. I built my own backend API (only returns JSON) in Django to fetch data from my MySQL database and I have completed the front end user interface in Swift. Up to this point, both my Django API and my database have been running locally on my Mac. I am ready to deploy my mobile app and I understand this requires pushing my backend API/database onto a server. Which server provider is best for my needs? Thank you. -
TypeError at /items/ join() argument must be str, bytes, or os.PathLike object, not 'dict'
Please help, I tried tracing back my code by removing some part of it and putting it back in to see which one raised the error and this one was the one that raised the above error. context = { 'items': 'Item.objects.all()' } This is from my django-views from django.shortcuts import render from .models import Item def vendors(request): return render(request, 'pages/vendors.html', {'title': 'Vendors'}) def items(request): context = { 'items': Item.objects.all() } return render(request, context, 'pages/items.html', {'title': 'Items'}) def request(request): return render(request, 'pages/request.html', {'title': 'Request'}) This is the items page I was trying to access. {% extends "pages/base.html" %} {% load humanize %} {% block content %} {% for item in items %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ item.requester }}</a> <small class="text-muted">{{ item.date_requesteded|naturaltime }}</small> </div> <h2><a class="article-title" href="#">{{ item.name }}</a></h2> <p class="article-content">{{ item.description }}</p> </div> </article> {% endfor %} {% endblock content %} The other html page worked fine. -
Python - How do i make this code look good
Is there simpler way to write this code and Refactor the code and write some very simple sanity checks to show that the refactored version is equivalent to the ugly version? for i in range(len(colours)-1,-1,-1): print(colours[i]) -
How to use Javascript function on input elements in a for loop. Django
I'm working on a Django form that can calculate values in real time. I would like the javascript function to work for all rows which consists of 3 input fields each. I tried assigning each input field with an id followed by a forloop counter. I also looped through the function hoping that it will work for all the ids, a1,a2,a3... b1,b2,b3... c1,c2,c3... However, the function only worked for the last row. Here's the javascript I used: <script type="text/javascript"> for (i = 0; i < {{ total_rows|safe }}; i++) { $('input').keyup(function(){ var firstValue = Number($('#a'+i).val()); var secondValue = Number($('#b'+i).val()); document.getElementById('c'+i).value = firstValue * secondValue; }); } </script> Here's my template: <form> {% csrf_token %} <table> <thead> <tr> <th>Quantity</th> <th>Unit Price</th> <th>Amount</th> </tr> </thead> <tbody> {% for item, amount in loop_list %} <tr> <td> <input id="a{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="quantity1" value="{{ item.quantity }}"> </td> <td> <input id="b{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="unit_price1" value="{{ item.product.unit_price }}"> </td> <td> <input id="c{{ forloop.counter }}" type="text" class="form-control" placeholder="{{ amount }}" readonly> </td> </tr> {% endfor %} </tbody> </table> </form>