Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add or Edit if already exists
I'm working on a web application that has a number of forms that allow the user to submit data to the database. The data is linked to a project, and from the project page, I have a drop-down list that allows you to select what information you want to add to the project. At the moment I have two views linked to two dropdown lists. One to add new data and one to update, but ideally, I'd like the button to either take you to the update or add a new page depending on data already being added to the database. So is there a way to have a single button that automatically takes you to the correct view? I imagine i'll need some kind of logic within the view to handle this. But im not sure what this would be? Views.py @login_required def AddFundamentals(request,project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = AddFundamentalsForm(request.POST) if form.is_valid(): form.instance.project = project form.save() return redirect('http://127.0.0.1:8000/') else: form = AddFundamentalsForm() return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form}) @login_required def UpdateFundamentals(request,project_id): project= Project.objects.get(pk=project_id) form = AddFundamentalsForm(request.POST or None, instance=project) if form.is_valid(): form.save() return redirect('dahsboard.html') return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form}) HTML <div … -
create custom domain email and receive email in python
I want to receive an email on this abcd@myemail.com. I want to use python(django) in the backend, for achieve this task which libraries and steps do I have to take. -
Error trying to host my Django project on Heroku
I was creating a Django project trying to upload it to Github. When I was doing git push Heroku main it pushed most of them. Before finishing pushing all of them, this error popped up: ![remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs I followed my steps on this site: https://realpython.com/django-hosting-on-heroku/#make-an-app-release -
matching query does not exist django V3.2.9
I am trying to retrieve the ID from a POST request which throws matching query does not exist when i am certain that specific ID for that customer exists because all it's information is displayed at the template table also using {{customer.id}} in the template gives an (ID) to make sure that it actually exists My views.py from .models import Customer,FilterMaintenance def index(request): if request.method == "POST": filtermaintenance_id = FilterMaintenance.objects.get(pk=request.POST.get('{{customer.id}}', False)) x = filtermaintenance_id.filter_last_due_date f = FilterMaintenance.objects.all() return render(request,'maintenance/index.html',{ "customers_maintenance":f, "test":x }) my models.py class Filter(models.Model): filter_brand= models.CharField(max_length=64) filter_interval = models.IntegerField() def __str__(self): return f"{self.id} , {self.filter_brand}" class Customer(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone_number = models.IntegerField(blank=True) home_address = models.CharField(max_length=64,blank=True) email = models.EmailField(blank=True) notes = models.TextField(blank=True) def __str__(self): return f"{self.id}, {self.first_name}, {self.last_name}" class FilterMaintenance(models.Model): customer_info = models.ForeignKey(Customer,related_name="customer_set",on_delete = models.CASCADE) customer_filter = models.ForeignKey(Filter,related_name="filter_set",on_delete = models.CASCADE) filter_last_due_date = models.DateField() def __str__(self): return f"{self.id}, {self.customer_info}, {self.customer_filter},{self.filter_last_due_date} " my index.html {% extends "maintenance/layout.html" %} {% block body %} <div class="maintenance-container"> <h1>Section for customers ...</h1> <table class="maintenance-table"><thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone number</th> <th>Home address</th> <th>Filter brand</th> <th>Last filter change</th> <th>Next filter due date</th> <th>Filter done</th> </tr> </thead> <tbody> {% for customer in customers_maintenance %} <tr> <td>{{customer.customer_info.first_name}}</td> <td>{{customer.customer_info.last_name}}</td> <td>{{customer.customer_info.phone_number }}</td> <td>{{customer.customer_info.home_address}}</td> <td>{{customer.customer_filter.filter_brand}}</td> <td>{{customer.filter_last_due_date}}</td> … -
get current logged in user info in Django
i try to get logged in user info inside a form class in Django. class PayForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PayForm, self).__init__(*args, **kwargs) self.fields['username_id'].initial = ? #current_logged_in_user_id() -
Using Ajax call for sending sort criteria from template to a Django view
I wish to send a sort criteria from a Django template to the associated view and update the template without reloading the page. Understand that an Ajax call is the way to go, but how would I implement this? store.html {% extends 'ecomsite/main.html' %} {% load static %} {% block content %} <select class="form-control" id="sort"> <option value="default" selected="selected">Default</option> <option value="price-low">Price(lowest first)</option> <option value="product-name">Product Name</option> </select> <br> <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbail" src="{{product.imageURL}}"> <div class="box-element-product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-primary add-btn update-cart">Add to Cart</button> <a href="{% url 'detail' product.id %}" class="btn btn-outline-info">View</a> <h5 style="display: inline-block; float: right"><strong>€{{product.price|floatformat:2}}</strong></h5> </div> <br> </div> {% endfor %} </div> {% endblock %} views.py def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'ecomsite/store.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.store,name='store'), path('cart/',views.cart,name='cart'), path('checkout/',views.checkout,name='checkout'), path('update_item/',views.updateItem,name='update_item'), path('process_order/',views.processOrder,name='process_order'), path('getting_started/',views.HowtoView.as_view(),name='howto'), path('myorders/',views.order_list,name='list'), path('signup/',views.Signup.as_view(),name='signup'), path('thankyou/',views.thank_you,name='thank_you'), path('products/<int:id>/',views.product_detail,name='detail') ] -
Django: How to ensure a parent class only has one child instance
This a theoretical question which I want to reapply to my own study. However, say I have three models: class Person(models.Model) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Teacher(Person) teacher_id = models.IntegerField() class Student(Person) student_id = models.IntegerField() What database/model restrictions can I put in place to ensure that an instance from both children cannot be created with the same Person id. Note: Obviously I could put a small check when saving but was hoping for something more "Pythonic" -
How to send script's return value to view using html href
I'm using django I want to send what I clicked as a parameter to my view getneworder. So I made a script which tells me what I clicked. It succeed but, I coudn't find a way to send the get_mall()'s return value to view using onclick. I kept googling but coudn't find an answer. How do I send the return value of get_mall() to view using onclick? thank you <li class="nav-item"><a class="nav-link" onclick="change_mall('esm');" href="{% url mallboard:esm' %}">ESM</a> var mall = "null" function change_mall(new_mall) { {#alert('change_mall to :'+new_mall)#} mall = new_mall } function get_mall() { {#alert(mall)#} return mall } @login_required(login_url='common:login') def getneworder(request, mall_name): if (mall_name =="coupang"): print("couapng") return HttpResponse("coupang") elif (mall_name=="interpark"): print("interpark") return HttpResponse("interpark") else: print("err") return HttpResponse("err") -
avoid sending same field with same value in body in django rest framework
I am trying to create objects in bulk but during the creation I have to send the same data of class = 2 in every objects which I think will make the code inefficient as well as the app. How to send that particular field just once? For eg: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all().order_by('-created_at') serializer_class = AttendanceSerializer def create(self, request, *args, **kwargs): data = request.data serializer_class = self.get_serializer_class() serializer = serializer_class(data=data,many=True) if serializer.is_valid(): serializer.save() return Response({ "message": "Data posted successfully.", "data":serializer.data, return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) My serializer: class AttendanceListSerializer(serializers.ListSerializer): def create(self, validated_data): attendance = Attendance.objects.bulk_create([Attendance(**datas) for datas in validated_data]) return attendance class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields ='__all__' list_serializer_class = AttendanceListSerializer The data are sent like this from frontend: [ { "class":2, "student":16, "status":"a" }, { "class":2, "student":15, "status":"p" }, { "class":2, "student":17, "status":"p" } ] Here we can see that class 2 is repeated all the times which is inefficient. Can we send this just once and not repeatedly? Also there might be other fields that might be repeated as well. I know we can send it into url but sending id while creating in the url endpoint doesnt look nice and there might be several other fields which … -
How to use django PWA on android
I created a django PWA but I do not know how to get in on the phone. When I created the PWA with my laptop following instructions here https://www.geeksforgeeks.org/make-pwa-of-a-django-project/, it just converted my laptop dev tools look to be a phone but I cannot find on the internet how to actually jam the app on the phone. I tried heroku also but could not get the database to populate with loaddata. -
Dajango FK constraint complaint, but object is there. What do I miss?
I am at my first Django app, please bear with me... It's based on some legacy scripts with an existing PostgreSQL database. Hence, the naming of some of the tables doesn't follow the Django naming schema. Currently I am in the middle of remodeling my data to follow sane data modeling principles. The migration doing one of the steps gives me an foreign key exception I do not understand: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() psycopg2.errors.ForeignKeyViolation: insert or update on table "design_shopify_category" violates foreign key constraint "design_shopify_categ_shopifycollection_id_9f310876_fk_designs_s" DETAIL: Key (shopifycollection_id)=([<ShopifyCollection: ShopifyCollection object (gid://shopify/Collection/263596736569)>]) is not present in table "designs_shopifycollection". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/__main__.py", line 45, in <module> cli.main() File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 444, in main run() File "/root/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 285, in run_file runpy.run_path(target_as_str, run_name=compat.force_str("__main__")) File "/usr/local/lib/python3.9/runpy.py", line 268, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/local/lib/python3.9/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/local/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/workspace/src/otaya_tool/manage.py", line 23, in <module> main() File "/workspace/src/otaya_tool/manage.py", line 19, … -
User verification for desktop application
I've developed a python desktop application using Kivy with intent to sell it for a monthly fee like a subscription. I'm planning to develop a simple website(probably using Django) where user can create an account, pay for the subscription/cancel it... . Once the user downloads the app he will have to login by entering his username and password he used to create an account on that website to verify if he has paid for the subscription or not. However I don't know what's the best way to do this verification process. I was thinking some API that will be integrated in the website and it will just query the database to check if user paid for the subscription. But I don't know if its possible with Django and Python. I know there are probably other ways to handling this problem that's why I'm asking the more experienced. Thanks for any suggestions :) -
Unsupported config option for services: 'account-database'
I am trying to create image and container with docker-compose up --build -d and this docker-compose.yml : services: account: build: context: . dockerfile: Dockerfile.dev env_file: - ./envs/development.env volumes: - ./:/app ports: - 8000:8000 command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env networks: default: name: mizban and docker-compose-production.yml : services: account: build: context: . env_file: - ./envs/development.env ports: - 8000:8000 volumes: # - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env volumes: account-media: account-static: networks: default: name: mizban but i got this error : ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services: 'account-database' Unsupported config option for networks: 'default' i have googled and it seems the problem is about indentation but i cant find out where the issue is -
Cannot get NGINX auth_request working with UWSGI + Django REST backend
I have a working NGINX > UWSGI > Django REST application where large-file uploads are sent to NGINX directly. After the upload has finished, Django gets notified that the upload is complete, and further update its database. As soon as I add an auth_request sub-request to the NGINX config, however, I'm getting upstream 502 errors. I have tried many different things based on info I found (in SO but also in other places). None of the examples that I saw specifically used UWSGI. Most of the auth_request examples simply refer to some auth-server that is connected but no further details. Below you can find some of the config file I'm using. The nginx.conf works without issues without the 'auth_request /auth' statement. Eveything is running in Docker containers on the yoda_default network. My Django backend container is called yoda_web and running on port 8001, so that's what you see in the nginx.conf (uwsgi_pass yoda_web:8001). NGINX itself is running on port 8002. At the bottom, there's the pytest script I used to test everything. Without the 'auth_request' statement in nginx.conf it works fine (see output below) yoda_nginx | 172.31.0.1 - - [28/Nov/2021:08:59:17 +0000] "POST /tokens HTTP/1.1" 200 52 "-" "python-requests/2.7.0 CPython/3.9.9 Darwin/20.6.0" … -
not able to run python manage.py migrate while I have some environment variables in the settings file
Am using 2 separate files for settings in my Django project one for production and the other for debugging,, here is how they look : base.py """ Django settings for arkb_eh project. For more information on this file, see https://docs.djangoproject.com/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['secret_key'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [os.environ['allowed_host']] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # <-- Here 'location_field.apps.DefaultConfig', 'colorfield', 'auth_system', 'stations', 'lines', 'trips', 'chat', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'arkb_eh.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'arkb_eh.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['database_name'], 'USER': os.environ['database_user'], 'PASSWORD': os.environ['database_pass'], 'HOST': 'localhost', 'PORT': '3306', } } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # <-- And here ], } # Password validation … -
add subitems for the suit menu subitems(3 level tree) in django-suit
Is it Possible to structure a 3 level tree with django-suit menu? If yes how can I do this or if there is another way to customize in the menu. what i need is something like that: Main Menu| |- SubItem1 |- SubItem2 |- SubItem2-1 |- SubItem2-2 |- SubItem3 -
How to handle recipe ingredients in database
Hi I'm new to programming and I am building a recipe website to learn, what I am struggling with though is how to handle recipe ingredients? I would like to do the following: Have global recipe ingredients i.e. common ingredients, chicken, beef etc. Allow users to create their own ingredients (for that user only) i.e. big tomato Attach ingredients to a recipe regardless of if they are global or user created Allow users to add ingredients to their pantry and how much of the ingredient they have in stock What I think the models would like is below, but I'm not sure if this is correct or the best method, any advice appreciated. recipe/models.py User = settings.AUTH_USER_MODEL class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) recipeName = models.CharField(max_length=220) # grilled chicken pasta userRecipeIngredients = models.ManyToManyField(UserCreatedIngredient, blank=True, Null=True, through='IngredientToRecipe') globalRecipeIngredients = models.ManyToManyField(GlobalIngredient, blank=True, Null=True, through='IngredientToRecipe') class UserCreatedIngredient(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken class GlobalIngredient(models.Model): name = models.CharField(max_length=220) # chicken class IngredientToRecipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) userIngredient = models.ForeignKey(UserCreatedIngredient, on_delete=models.SET_NULL) globalIngredient = models.ForeignKey(GlobalIngredient, on_delete=models.SET_NULL) quantity = models.CharField(max_length=50, blank=True, null=True) # 400 unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc instructions = models.TextField(blank=True, null=True) # chopped, diced … -
Django channels chat async app not working on heroku but working fine in local environment and encounter no error in log files of heroku
I'm new to channels and I tried every possible solution to make it work but my chat app is not working on heroku, but is working fine in local environment. My other blog and story apps are working fine in local as well as on heroku, I'm facing this issue with just chat app. Here's the settings.py file ASGI_APPLICATION = 'core.routing.application' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", # "CONFIG": { # "hosts": [('127.0.0.1', 6379)] # } } } routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE','core.settings') application = get_asgi_application() consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) pass and my Procfile web: gunicorn core.wsgi:application --log-file - --log-level debug web: daphne core.asgi:application … -
django rest framework dosent even show the option to upload image. I do have imageField in models
django rest framework dosent even show the option to upload image. I do have imageField in models. I also get GET http://127.0.0.1:8000/api/person-create/ 405 (Method Not Allowed) in console when i go to the api url to create new item. TLDR I am trying to upload images using django rest framework i can do it from admin but not with DRF or frontend any help is appreciated Thanks. view.py @api_view(['POST']) def create_person(request): serializer = PersonSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) serializer.py class PersonSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=True) class Meta(): model = Person fields = 'name', 'about', 'created_at', 'email', 'image' urls.py urlpatterns = [ path('', views.apiOverview, name='apiOverview'), path('persons/', views.all_persons, name='all_persons'), path('person/<str:pk>', views.person, name='person'), path('person-create/', views.create_person, name='create'), path('person-update/<str:pk>', views.update_person, name='update_person'), path('person-delete/<str:pk>', views.delete_person, name='delete_person'), ] models.py class Person(models.Model): name = models.CharField(max_length=50) about = models.CharField(max_length=10000) created_at = models.DateTimeField(auto_now_add=True) email = models.EmailField(unique=True) image = models.ImageField(blank=True, null=True, upload_to='media/', default='default.png') Heres the frontend part create.js const Create = () => { let history = useHistory(); let [person, setPerson] = useState({ name:"", about:"", email:"", image:"", }) let createPerson = async (e) => { e.preventDefault() fetch(`/api/person-create/`, { method: "POST", headers: { "content-type": 'application/json' }, body: JSON.stringify(person) }) .then(setPerson({ name:"", about:"", email:"", image:"", })) } let handleChange = (e) … -
The 'video' attribute has no file associated with it. while uploading events videos and image in django
i tried to upload events videos and images but it does not work after when i leave one filed blank but also there is null=True , blank=True , default=None, in both ImageField and FileField can anyone help me to point out error ?? models.py class Events(models.Model): date = models.DateField(("Date"), default=date.today ,help_text='events date') Image = models.ImageField(upload_to = 'static/img/eventimg',null=True,blank=True default=None) video = models.FileField(upload_to='static/img/video' , default=None,null=True,blank=True , verbose_name = 'Video'') views.py def event_view(request): ev=Events.objects.all() return render(request,'event.html' , {'ev':ev } event.html {% for s in ev %} {% if s.Image %} <img style='max-height:20rem;' src="{{s.Image.url}}" > {% else %} <span>-</span> {% endif %} {% if s.video %} <video class='embed-responsive embed-responsive-16by9' controls="controls" controls > <source class="embed-responsive-item" src="{{s.video.url}}" name='video' type="video/mp4"></video> {% else %} {% else %} <span>-</span> It work when i just add single time but after more it show the error The 'video' attribute has no file associated with it. -
Open WebSocket stream(s) based on content of Django page
First off, I'm very open to hearing design decision fixes if I'm just doing this wrong. Setup: Django-based stock market app with Celery using a redis broker. I'm pulling live data from alpaca.markets API. I also have a Python-based background service running that kicks off asynchronous tasks based on various events. Overall dream: I want to open a websocket stream of live data for each symbol that shows up on a page. I want to have my background service kick off that live feed so it can return it to the page but also compare it to algorithms on the backend. Current (failing) design: When a page loads, Django will successfully kick off a Celery task that returns what stocks show up on that page. I can look at the data in Admin under django_celery_results/taskresult/ and in the DB under result of the django_celery_results_taskresult table. I can't get my service to see the new task and the corresponding symbols returned. Other information: I have ASGI with daphne set up and working I have successfully displayed live data on a page My background service is asynchronous I can see the raw data when I follow the accepted answer here: How can … -
django.template.exceptions.TemplateDoesNotExist: customer/base.html
My customers urls.py ''' urlpatterns = [ path('', views.base ,name= 'customer-base'), path('Hall/', views.Hall ,name= 'customer-Hall'), path('Food_item/', views.Food_item ,name= 'customer-food'), path('About_us/', views.About_us ,name= 'customer-about'), ] ''' My Web_project urls.py ''' urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' My views.py ''' def base(request): return render(request, "customer/base.html", {"title":"base"}) def Hall(request): return render(request, "customer/Hall.html", {"title":"Hall"}) def Food_item(request): return render(request, "customer/Food_item.html", {"title":"Food"}) def About_us(request): return render(request, "customer/About_us.html", {"title":"About"}) ''' I have tried everything but did not work for me. -
Remote host forcibly terminated existing connection
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command, python -m smtpd -n -c DebuggingServer localhost:1025 in order to test it. It intercepts with no problem, but I don't see anything in my inbox. My email provider works with SSL, so I turned it to True and enabled 'access to the mailbox using mail clients' in my mail settings. Here is the settings.py file: EMAIL_HOST = '178.68.164.41' # My current ip address EMAIL_PORT = '465' # Port of the email host EMAIL_HOST_USER = 's...6@rambler.ru' # Here is my actual email EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login EMAIL_USE_TLS = False EMAIL_USE_SSL = True Here is the views.py file: from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm def contact(request): form = ContactForm if request.method == 'POST': message_name = request.POST.get('name') message_email = request.POST.get('email') message = request.POST.get('message') send_mail(message_name, message, message_email, ['s****6@rambler.ru']) return render(request, 'contact.html', {'form': form}) Here's the exception: Internal Server Error: /contact/ Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
do the same thing with diffrent urls
I'm totally new in Django. I want to do the same thing when the user type "student/" or "student/en" or "student/ttttttttttttt" in the URL. I want to handle if the user type "student/en" the whole page translate to English or if it was "student/de" it translated to german. if it was "student/" it translate to dutch(default). just it is important for me to get "en" or "de" or none from the end of its URL. thanks for helping -
I am having problems in displaying images in django project
I am trying to display an uploaded image on my Django website, but it seems I am unable to display it. Can anyone tell me what I am doing wrong? in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' image is stored in project/core/media/images/image_name.jpg And the url i am getting after opening image in new tab is: http://127.0.0.1:8000/media/images/Bill_JcVkQAX.jpg DEBUG is true (if that helps somehow) Any help will be greatly appreciated. settings.py in urls.py and image link