Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Laravel vs Django [closed]
Please I am currently in between choosing a framework for a web project. Between Django and Laravel which one is best in terms of Efficiency, Memory Management and deployment?? Thank You. -
Why is the button not being shown in form?
I'm trying to develop a website for an online store and after I added my css files to the base.html file, everything is working fine,but an input button for update cart is not being shown properly although it was working fine before adding the css static file.What can I do? Can someone please help me with this? My cart.html: {% extends 'base.html' %} {% block content %} {% if empty %} <h1 class='text-center'>{{ empty_message }}</h1> {% else %} <div class="container text-black py-5 text-center"> <h1 class="display">MyShop Cart</h1> </div> <div class="container-md"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <script src="https://use.fontawesome.com/c560c025cf.js"></script> <div class="container"> <div class="card shopping-cart"> <div class="card-header bg-dark text-light"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Shipping cart <a href="{% url 'myshop-home' %}" class="btn btn-outline-info btn-sm pull-right">Continue shopping</a> <div class="clearfix"></div> </div> <!-- PRODUCT --> <div class="pb-5"> <div class="container"> <div class="row"> <div class="col-lg-12 p-5 bg-white rounded shadow-sm mb-5"> <!-- Shopping cart table --> <div class="table-responsive"> <table class="table"> <thead> <tr> <th scope="col" class="border-0 bg-light"> <div class="p-2 px-3 text-uppercase">Product</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Price</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Quantity</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Remove</div> </th> </tr> </thead> {% for … -
Django admin Add item button translation
I am struggling with the translation of an add button in django admin site. The one in the image below. Image How can i change its text? -
Django updating profile photo
Look I have a problem with displaying photos after updating. I have a function from my views.py def addHW(request): if request.user.is_authenticated: obj = Profile.objects.get(user=request.user.id) else: obj = '' profile = request.user.profile form = CustomerForm(instance=profile) template = 'HW/add.html' context = {'form': form, 'profile': obj} if request.method == 'POST': form = CustomerForm(request.POST, request.FILES, instance=profile) if form.is_valid(): Profile.objects.get(user=request.user.id).photo.delete() form.save() return render(request, template, context) and after deleting previous photo and saving of new photo, page must be reloaded. And page shows visual reloading, but HTML shows src of previous image. And after manual refreshing page displays new src of photo. How i can resolve it? -
Render shop items as grid or list in Django
I need to make some mechanism for users that allow switch between rendering items as grid or as list, how I can implement this? -
i am working on django forms with the password related
how i can set my own password at any login template in my django website without using django default login authentication. A sample of my website is given in screen shot of my project.I want to set a own password in that page.sample of my project -
How to pass data from Django Template to View
I have a template where customer details are displayed, along with a 'Create Lead' button at the bottom. This should take the user to the Lead creation form page where the customer field should be pre-selected. I'm new to django. Based on responses of previous similar questions, I came up with the below code. But when I click the 'Create Lead' button, the url changes from "http://127.0.0.1:8000/sales/customer/21" to "http://127.0.0.1:8000/sales/customer/21/?customer_id=21" but nothing happens on the page. I tried with POST method and csrf token also, but it gives HTTP ERROR 405. Could some please help here. Also, I've separate view for creating a Lead, which is sort of duplication of CreateView for Lead. And I believe that's not how it's supposed to be. What is the way to club them both in single view. Below are the code snippets. Models.py class Customer(models.Model): name = models.CharField(max_length=256) email = models.EmailField(unique=True) phone = models.PositiveIntegerField() class Lead(models.Model): customer = models.ForeignKey(Customer,related_name='Leads',on_delete=models.PROTECT) destinations = models.CharField(max_length=256) lead_source = models.CharField(max_length=256,choices=lead_source_choices,default='FNF') lead_source_id = models.CharField(max_length=25,blank=True) lead_status = models.CharField(max_length=25,choices=lead_status_choices,default='NEW') remarks = models.TextField(blank=True) trip_id = models.CharField(max_length=10,editable=False,unique=True,default="IN"+uuid.uuid1().hex[:5].upper()) creation_date = models.DateField(auto_now=True) Forms.py class LeadForm(forms.ModelForm): class Meta: model = Lead fields = ('customer','destinations','lead_source','lead_source_id','lead_status','remarks') class LeadFromCustomerForm(forms.ModelForm): class Meta: model = Lead fields = ('destinations','lead_source','lead_source_id','lead_status','remarks') Template <form method="GET"> … -
Render a dictionary with object list as values in django but template not showing values
I'm try to displaying dictionary values in my template that i render from my views file. but its not displaying any value. In my html template show my just blank or not any error. kindly guide me where i did a mistake. Thank you. views.py class BuyView(TemplateView): template_name = 'shop/buy.html' red_templateName = 'shop/receipt.html' def get(self, request, product_id): product = get_object_or_404(Product, pk=product_id) args = {'product':product} return render(request, self.template_name, args) def post(self, request, product_id): product = Product.objects.get(id=product_id) if request.POST['address'] and request.POST['quantity']: order = Order() order.or_proName = product.pro_name order.or_companyName = product.companyName order.or_quatity = request.POST['quantity'] order.or_quatity = int( order.or_quatity) orderPrice = order.or_quatity*product.Sale_Price order.or_bill = 100 + orderPrice order.pub_date = timezone.datetime.now() product.Quantity -= order.or_quatity product.save() order = order.save() args = {'order':order} return render(request, self.red_templateName, args) else: return render(request, self.template_name, {'error':'Please Fill the address field'}) template.py {% extends 'base.html' %} {% block content %} <div> <div class="container p-5" style="border:1px solid gray;"> <small class="lead" >Your Order Receipt: </small> {{ order.or_id }} {{order.or_proName}} {{order.or_companyName}} {{order.or_quatity}} {{order.pub_date}} Deliever Chargers=100 ----------------------- Total = {{or_bill}} </div> </div> {% endblock %} -
Django - Use model fields part in a create or update query
Given the following models in a Django 2.2 app: class ShelfPosition(models.Model): shelf_code = models.CharField(max_length=10) row = models.IntegerField() column = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint(fields=["shelf_number", "row", "column"], name="shelfpos_unique") ] class Item(models.Model): name = models.CharField(max_length=255) position = models.OneToOneField(to=ShelfPosition, on_delete=models.SET_NULL, primary_key=True) I rely on Django's lookup feature to filter on Item objects depending on some ShelfPosition fields: Item.objects.filter(position__shelf_code="BF4") Is there any way I could implement a similar lookup functionality such as described above when using get_or_create or update_or_create? item, created = Item.objects.get_or_create( position__shelf_code="BF6", position__row=88, position__column=1, defaults={……} ) -
open and close time in django rest framework
I have project in django rest framework that has some stores and I want, owner of stores enter open hour and close hour and days that they work in their profiles of website. what should I do ? -
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?