Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Reverse Proxy Django to a subdomain
I'm trying to use Nginx to reverse proxy some applications to different subdomain, the problem is when I try to do this with a Django application it doesn't work well, I get the message that the path does not exist or 404 Page not found. this is a pice of my docker-compose.yaml version: "3.9" services: ww4api: build: . hostname: ww4api command: gunicorn --bind 0.0.0.0:8000 authApi.wsgi --workers=4 depends_on: - db - orion restart: always container_name: ww4api environment: - WW4API_ALLOWED_HOSTS=ww4,ww4api,localhost ports: - 8000:8000 volumes: - .:/app pgadmin: container_name: pgadmin image: dpage/pgadmin4 hostname: pgadmin restart: always depends_on: - timescale environment: - PGADMIN_LISTEN_PORT=5050 nginx: hostname: nginx build: settings/nginx restart: always ports: - 80:80 - 434:434 tty: true volumes: - ./data-models/context:/srv/ww4/context - ./syncthingFolder/Sync:/srv/ww4/projects - ./:/srv/ww4 networks: - default and this is part of my nginx.config worker_processes auto; events { worker_connections 1024; } http { include /etc/nginx/mime.types; server_tokens off; upstream ww4api { server ww4api:8000; } upstream mintaka { server mintaka:8080; } server { listen 80; root /srv/ww4; index index.html; keepalive_timeout 1s; keepalive_requests 5000; location / { try_files $uri $uri/ =404; } location /pgadmin4/ { resolver 127.0.0.11 ipv6=off; proxy_pass http://pgadmin:5050/; proxy_set_header X-Script-Name /pgadmin4; proxy_set_header X-Scheme $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; … -
Django "AND" query: Reverse ForeignKey or ManyToMany giving an unexpected result
I found a different result on an "AND" query depending if it was a reverse of forward query. In a FORWARD query you can do this: Model.objects.filter(x=1) & Model.objects.filter(y=2) Model.objects.filter(x=1, y=2) Model.objects.filter(Q(x=1) & Q(y=2)) All give the same result: a QuerySet that satisfies both conditions (x=1 and y=2). But If I have a REVERSE FOREIGNKEY or MANY TO MANY “AND” query something different happens. This is what I did and expect. I have these models: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() authors = models.ManyToManyField(Author) And let's say I have this data: Headline Pub Date Year Authors Blog Pop 1 2023 Juan Pop Pop 2 2023 Emma Pop Pop 3 2010 Juan, Walmer Pop Other 2023 John Beatles I want to make an “AND” query to get the authors that satisfy both the headline that contains the word “Pop” and Pub Date Year equal to 2023. Expected result: Juan and Emma. Headline Pub Date Year Authors Blog Pop 1 2023 Juan Pop Pop 2 2023 Emma Pop We can use the following methods: Multiple Arguments … -
The media folder is not created after saving the file in the database Django
I`m writing a site on Django and I faced a problem. I have a cv field in the database, in which users can store their resume, I did everything as stated in the documentation. Namely: Create FileField model in models.py class JobseekerProfileInfo(models.Model): jobseeker = models.OneToOneField(JobseekerRegisterInfo, on_delete=models.CASCADE) photo = models.ImageField(upload_to='avatars/%Y/%m/%d', default='static/personal_profile/images/default_avatar.png') expected_job = models.CharField(max_length=400, blank=True) telegram = models.CharField(max_length=150, blank=True) linkedin = models.URLField(blank=True) git_hub = models.URLField(blank=True) cv = models.FileField(upload_to='cvs/%Y/%m/%d') active_search = models.BooleanField(default=True) def __str__(self): return self.expected_job Notice the FileField, I specified the upload_to argument Created a MEDIA_ROOT and MEDIA_URL variables in settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Added static() to urlpatterns list in urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings import debug_toolbar urlpatterns = [ path('admin/', admin.site.urls), path('', include('main_page.urls')), path('jobseeker', include('jobseeker.urls')), path('profile', include('personal_profile.urls')), path('__debug__/', include('debug_toolbar.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ path('captcha/', include('captcha.urls')) ] But when I added file to db, media root doesn`t create Help me please -
Accessing Continuous Data from Websockets in Django Channels
Improved Question: In the file "apisGo.py", I have two methods that retrieve data from servers through websockets. This data is updated continuously, meaning the function never ends. The issue is that I need to receive the contents of the "msg" variable from both "apiA" and "apiB" in my "WSConsumer" class, so I can send it to the frontend. What is the correct way to do this? file apisGo.py async def apiA(): async with websockets.connect('wss://ws-api...)) as ws: msg = {"id": "%s" % (uuid), "type": "", "topic": "", "response": True} msg = json.dumps(msg) await ws.send(msg) while True: msg = await ws.recv() async def apiB(): async with websockets.connect('wss://ws-api...)) as ws: msg = {"id": "%s" % (uuid), "type": "", "topic": "", "response": True} msg = json.dumps(msg) await ws.send(msg) while True: msg = await ws.recv() async def main(): task1 = asyncio.create_task(apiA()) task2 = asyncio.create_task(apiB()) await asyncio.gather(task1, task2) if __name__ == "__main__": asyncio.run(main()) file "consumers.py": import apisGo class WSConsumer(WebsocketConsumer): def connect(self): self.accept() asyncio.run(apisGo.main()) I considered using global variables in the "apisGo.py" file and using the "import multiprocessing" in "consumers.py" to create two routines: one to initiate the requests "asyncio.run(apisGo.main())" and another to access the global variables. But I am not sure if this is the correct … -
Django ORM dublicate objects in queryset after order_by by foreignkey field
I have encountered some unexpected sorting behaviour with objects. As soon as I sort by the related model field, I get duplicates. A short description of the model fields models.py class GoogleCreativeSpend(models.Model): creative = models.ForeignKey( 'GoogleCreative', on_delete=models.CASCADE, ) spend = models.DecimalField() class GoogleCreative(CreamCreative): ..... Create some objects: >>> creative = GoogleCreative.objects.get(name='gs_video1031v1') >>> spend = GoogleCreativeSpend(creative=creative, spend=100,) >>> spend.save() >>> spend = GoogleCreativeSpend(creative=creative, spend=1100,) >>> spend.save() >>> spend = GoogleCreativeSpend(creative=creative, spend=1,) >>> spend.save() views.py queryset = GoogleCreative.objects.all() queryset.order_by('googlecreativespend__spend') for i in queryset: if i.name == 'gs_video1031v1': print(i.name) | gs_video1031v1 | gs_video1031v1 | gs_video1031v1 I.e. by creating 3 googlespend objects I get 3 duplicates for googlecreative after sorting. According to How to sort queryset based on foreign key with no duplicates I tryied queryset.distinct() and queryset.distinct('googlecreativespend__spend') But it doesn't work How to fix it ? -
Wagtail 4.1, 'NoneType' object has no attribute '_inc_path'
I am trying to integrate wagtail into an existing django project, but I am getting the above error when I add a child page. In my settings I have followed the instructions so: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'whitenoise.runserver_nostatic', 'home', 'news', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail', 'modelcluster', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django_permissions_policy.PermissionsPolicyMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] my project urls: from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from django.urls import reverse from wagtail.admin import urls as wagtailadmin_urls from wagtail import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls urlpatterns = [ path('', include('home.urls')), path('news/', include('news.urls')), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('news/', include(wagtail_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my news urls: from django.urls import path from .views import news_article_detail urlpatterns = [ path('news/<int:pk>/', news_article_detail, name='news_article_detail'), ] in my news view: from django.shortcuts import render from .models import NewsArticlePage #import pdb; pdb.set_trace() def news_article_detail(request, pk): news_article = NewsArticlePage.objects.get(pk=pk) return render(request, 'news/news_page.html', {'news_article': news_article}) and my model: from django.db import models from wagtail.core.models import Page from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.fields import RichTextField class NewsArticlePage(Page): article_body = RichTextField(blank=True) content_panels = Page.content_panels + … -
Django field should not be shown in form but added by middleware at POST request
Let's say I've the following model: from django.db import models class MyModel(models.Model): foo = models.CharField() bar = models.CharField() The field "foo" should not be shown in the create form. Therefore the form is: from django.forms import ModelForm class MyForm(ModelForm): fields = ('bar',) The field is NOT shown in the form. Excellent! Now when POSTing the form, a middleware adds the 'foo' field to the POST vars. But when saving I get an "NOT NULL constraint failed: foo" error. There seems to be some magic code aligning the POST vars (with "foo") to the form fields (w/o "foo"). I already played with the "editable=False" setting, but no success, same behaviour. Any idea how to resolve this? -
Django execute previous action on refresh
I have tried to add a book in to the database using an HTML form. After the submission, the page redirect to a page where all the books are listed .Then whenever I refresh the page , the data is became duplicated. How do i resolve this problem? This is my URLS.py from django.urls import path from . import views app_name='library' urlpatterns =[ path('', views.home, name='home'), path('book/',views.book,name='book'), path('book_details/<int:book_id>',views.book_details,name='book_details'), path('book_edit/<int:book_id>',views.book_edit,name='book_edit'), path('book_delete/<int:book_id>',views.book_delete,name='book_delete'), path('update/<int:book_id>',views.update,name='update'), path('author/',views.author_view,name='author_view'), path('addbook/',views.add_book,name='add_book'), path('books/',views.add_submit,name='add_submit'), ] This is my VIEWS.py def add_submit(request): if request.method =='POST': title=request.POST.get('t_title') print(title) author_name=request.POST.get('a_author') author, created=Author.objects.get_or_create(Name=author_name) summary=request.POST.get('s_summary') date=request.POST.get('d_date') book=Book(Title=title,Author=author,Summary=summary,Published_date=date) book.save() books=Book.objects.all() return render(request,'books.html',{'books':books}) #This is my FORM <form action="{% url 'library:add_submit' %}" method="POST"> {% csrf_token %} <div class="form-outline mb-4"> <input type="text" id="bname" name="t_title" class="form-control" /> <label class="form-label" for="bname">Title</label> </div> <div class="form-outline mb-4"> <input type="text" id="bauthor" name="a_author" class="form-control" /> <label class="form-label" for="bauthor">Author</label> </div> <div class="form-outline mb-4"> <textarea rows="5" cols="33" id="bsummary" name="s_summary" class="form-control"></textarea> <label class="form-label" for="bsummary">Summary</label> </div> <div class="form-outline mb-4"> <input type="date" placeholder="" id="pdate" name="d_date" class="form-control" /> <label class="form-label" for="pdate">Published_Date</label> </div> <!-- Submit button --> <button type="submit" class="btn btn-primary btn-block">SUBMIT</button> </form> -
AttributeError: 'tuple' object has no attribute 'model'. How to fix this error?
I'm new to Django. Please help me to solve this error. I'm not getting any solution. I tried many stackoverflow solutions and GitHub solutions but I'm not getting where the error is coming from. urls.py # from django.contrib import admin from django.urls import path, include from rest_framework import routers from user_profile.views import UserProfileViewSet, CoursesViewSet router = routers.DefaultRouter() router.register(r'user', UserProfileViewSet) router.register(r'courses', CoursesViewSet) urlpatterns = [ path('', include(router.urls)) ] models.py from django.db import models # Creating user profile model. class Courses(models.Model): courses = models.CharField(max_length= 100, blank=True) def __unicode__(self): return self.courses class UserProfile(models.Model): user_id = models.AutoField(primary_key = True) imgUrl = models.CharField() user_name = models.CharField(max_length=100) user_description = models.TextField() university_college = models.CharField(max_length=100) course = models.ForeignKey(Courses, blank=True, null=True, on_delete=models.CASCADE) views.py from django.shortcuts import render from rest_framework import viewsets from user_profile.models import Courses, UserProfile from user_profile.serializers import UserProfileSerializer, CoursesSerializer # Use these two when you'll create url of one class inside another class # from rest_framework.decorators import action # from rest_framework.response import Response class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all(), serializer_class = UserProfileSerializer class CoursesViewSet(viewsets.ModelViewSet): queryset = Courses.objects.all(), serializer_class = CoursesSerializer serializers.py from rest_framework import serializers from user_profile.models import Courses, UserProfile class UserProfileSerializer(serializers.HyperlinkedModelSerializer): user_id = serializers.ReadOnlyField() class Meta: model = UserProfile fields = '__all__' class CoursesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model … -
MultiValueDictKeyError(key) [closed]
Hola estoy aprendiendo Django y creando un formulario pero cuando lo envio me aparece lo si mi vista mis modelos mi html espero me pueda alguien ayudar :( -
npx rollup -c [!] SyntaxError: Invalid or unexpected token
While using rollup, if I use following configuration file export default { input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs' } }; I am getting this error npx rollup -c [!] SyntaxError: Invalid or unexpected token rollup.config.js (1:0) 1: ��{ ^ I don't understand why it is not comprehending es6 syntax, this is the reason we use rollup. -
Django Model formset is partially working
I have normally just a simple question but I can't get it working. I have a view where customers can add, delete or edit their addresses. view.py: ... customer_addresses = CustomerAddresses.objects.filter(CustomerID=customer) AddressFormSet = modelformset_factory(CustomerAddresses, form=CustomerAddressesForm, extra=0) formset = AddressFormSet(queryset=customer_addresses, form_kwargs={'user': User.ID}) if request.method == 'POST': if 'add_address' in request.POST: add_address_form = CustomerAddressesForm(User.ID, request.POST) if add_address_form.is_valid(): add_address_form.save() if 'edit_address' in request.POST: address_id = request.POST.get('id_Address') address_data = CustomerAddresses.objects.get(pk=address_id) edit_address_form = AddressFormSet(request.POST, queryset=customer_addresses, form_kwargs={'user': User.ID}) print('ERROR', edit_address_form.errors) messages.error(request, 'ERROR') if edit_address_form.is_valid(): instances = edit_address_form.save(commit=False) for instance in instances: instance.save() return redirect('addresses') if 'delete_customer_address_id' in request.POST: delete_customer_address_id = request.POST.get('delete_customer_address_id') request.session['delete_customer_address_id'] = delete_customer_address_id return redirect('delete-customer-address') if 'register_customer' in request.POST: register_form = CustomerAddressesForm(user=user_id) if register_form.is_valid(): customer = register_form.save(commit=False) customer.UserID = user_id customer.save() # You can redirect to a success page or login the user directly redirect(request.META.get('HTTP_REFERER')) else: add_address_form = CustomerAddressesForm(user=User.ID) and my form: class CustomerAddressesForm(forms.ModelForm): Title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'autofocus': True}), required=False) Address_Firstname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Address_Lastname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Zip = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'form-control', 'maxlength': '5', 'data-toggle': 'maxlength'}), label='Postnummer') City = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Address_Company = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), required=False) Street = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), required=False) Country = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-select'}), queryset=CountryList.objects.values_list('countryname', flat=True).order_by( 'code'), initial='Denmark', to_field_name='countryname') Is_Default_Shipping_address = … -
How can I add the currently logged in username to the access log of django.server?
I'm trying to add the currently logged in username, if any, to the access log of a Django app: INFO [django.server:161] "GET / HTTP/1.1" 200 116181 ^ username should go here My main problem is how do I share the user/username between the middleware and the filter, since in the filter I don't have access to the request object? I've got a working solution using thread-local for storage, but this doesn't seem like a good idea. Especially since I can't cleanup the value in process_request as it is then cleared too early, before the log line is printed. Solution with threading.local() log.py import logging import threading local = threading.local() class LoggedInUsernameFilter(logging.Filter): def filter(self, record): user = getattr(local, 'user', None) if user and user.username: record.username = user.username else: record.username = '-' return True class LoggedInUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) return self.get_response(request) def process_request(self, request): from django.contrib.auth import get_user user = get_user(request) setattr(local, 'user', user) django settings MIDDLEWARE = ( ... 'commons.log.LoggedInUserMiddleware', ... ) ... LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { ... 'verbose_with_username': { 'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(username)s %(message)s' } }, 'filters': { 'logged_in_username': { '()': 'commons.log.LoggedInUsernameFilter', } }, 'handlers': { 'console_with_username': … -
Why is a single product page not loading in Django project
I am trying to make an ecommerce project and I already set up products page, but It should load a product description page after goint to api/products/2 page, example(2 is a product id). views.py: @api_view(['GET']) def getProduct(request, pk): product = None for i in products: if i['_id'] == pk: product = i break return Response(product) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('products/', views.getProducts, name="products"), path('prodcucts/<str:pk>/', views.getProduct, name="product"), ] I already tried int:pk instead of str:pk -
Django model relations and dividing models into few tables in larger project
I have few problems with Django models (relations mostly), but I'll start from code than make desciption and put questions... Django models and relations in short (very simplified) version: # Shorten version of services SERVICES = [ ("TC", "Tires Cleaning"), ("EC", "Exterior Cleaning"), ("IC", "Interior Cleaning"), ("CW", "Cleaning & Washing - full service"), ("WX", "Application of wax"), ] class Client(models.Model): name = models.CharField(max_length=35) surname = models.CharField(max_length=35) car = models.CharField(max_length=25) class SingleService(models.Model): service_name = models.CharField(max_length=35) service_type = models.CharField(max_length=1, choices=SERVICES, default="CW") price = models.IntegerField() class SetOfServices(models.Model): set_of_services = ???? price_of_set = ??? class Purchase(models.Model): client = OneToOneField(client) order = models.ForeignKey(SetOfServices, on_delete=models.CASCADE, blank=True, null=True) price = ??? I want to make small project (Car Wash) with 8+ django models. Client is coming to car wash and I want to store its name/ surname and car make/model/type etc in DB for future refference (clients coming back will get discount and free coffee). Then I have SingleService model with about 20-30 services - they have different name and price because of diferernt tasks / time to make and options / extra features. SetOfServices model must consist of few single services (custom, but customized from Django admin panel, probably only once, at setup / configuration time). … -
Django: matching query does not exist. Error: 500
I'm trying to find a bug - already a second day. The goal was to create a button to save in-session a piece of information about a particular page that would be "read later". I'm trying to find out why I can't find a match in my query. The id that should be generated in POST is 8, but from what I understand from logs, it's 0. I'm looking for suggestions on how to find out where the problem is. I exchausted all ideas that I had. Additionally, I wonder if is it a good or bad idea that in my views.py I defined called model EssayCls in two functions where I define it with different names. In def get as selected_essay = EssayCls.objects.get(slug=slug), but in def post as post = EssayCls.objects.get(slug=slug). My views.py: class MyEssaysView(View): def is_stored_essay(self, request, post_id): stored_essays = request.session.get("stored_essays") if stored_essays is not None: is_saved_for_later = post_id in stored_essays else: is_saved_for_later = False return is_saved_for_later def get(self, request, slug): # print("GET: slug:", slug) # test user_agent = get_user_agent(request) selected_essay = EssayCls.objects.get(slug=slug) user_feedback = UserFeedback() context = { 'essay_found': True, 'essay_all': selected_essay, 'post_tags': selected_essay.tags.all(), 'form': user_feedback, 'comment_form': CommentForm(), 'comments': selected_essay.comments.all().order_by("-id"), 'saved_for_later': self.is_stored_essay(request, selected_essay.id) } if request.method == … -
Reusing a database record created by means of Celery task
There is a task which creates database record {R) when it runs for the first time. When task is started second time it should read database record, perform some calculations and call external API. First and second start happens in a loop In case of single start of the task there are no problems, but in the case of loops (at each loop's iteration the new task is created and starts at certain time) there is a problem. In the task queue (for it we use a flower) we have crashed task on every second iteration. If we add, at the and of the loop time.sleep(1) sometimes the tasks work properly, but sometimes - not. How to avoid this problem? We afraid that task for different combination of two users started at the same time also will be crashed. Is there some problem with running tasks in Celery simultaneously? Or something we should consider, tasks are for scheduled payments so they have to work rock solid -
How do I apply higher permissions to child pages in Wagtail?
I am building an intranet site for my organization with Wagtail and we are in the process of adding a knowledge base. The entire site needs to be restricted to logged-in users, but certain pages need to only be accessible to users in certain groups. For instance, only members of the IT group should be able to access the pages underneath the IT Knowledge Base page. Currently if I set the top-level page to be accessible only by logged-in users, that permission is applied to every page on the site, and I am barred from setting more specific permissions on any child page. It is imperative that I be able to set more specific permissions on child pages. I was able to find Wagtail Bug #4277 which seems to indicate that the logic for more specific permissions is implemented but not exposed in the admin UI. I am not familiar with the inner workings of Wagtail yet, especially how Wagtail permissions intersect with Django permissions. How can I add more specific permissions to child pages? -
How to disable TLS Renegotation in EB AWS for Linux AMI?
It is a security best practice to disable TLS Renegotiation in production. What is the best way to do this in an Apache2-based Elastic Beanstalk Deployment (Python/Django)? -
The system cannot find the file specified (django)
Hi I'm creating pdf file but I face an error [WinError 2] The system cannot find the file specified but I don't know where is the error if os.path.exists(pdf_file_output): with open(pdf_file_output, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(pdf_file_output) return response -
AJAX not working on Django and returning 500 Error
I'm trying to send an AJAX request from my template that takes you to a url and runs the view function. However, I'm getting a 500 Error in my console. My view is also using a custom decorator, all required code is below: Decorator def user_has_delete(func, redirect_url="Home:Deny"): def wrapper(request, *args, **kwargs): if request.user.is_anonymous: return redirect(redirect_url) if request.user.is_authenticated: if not request.user.is_denier: return redirect(redirect_url) else: return func(request, *args, **kwargs) return wrapper URL Pattern path('Vet/DenyAppointment/<int:appointment_id>', views.delete_appointment) View @user_has_delete @never_cache def delete_appointment(request, appointment_id): appointment = get_object_or_404(Appointments, pk=appointment_id) appointment.delete() return redirect('Dashboard') Template Portion {% for appointment in appointments %} <div class="col-sm-12 col-lg-8 AppointmentDiv offset-sm-0 offset-lg-2 Space-b-sm"> <h2>{{ appointment.fullDate }}</h2> <ul> <li>{{ appointment.title }}</li> <li>{{ appointment.day }}</li> </ul> <button type="submit" class="theme" id='{{ appointment.id }}' onclick="deleteAppointment({{ appointment.id }})">Delete Appointment</button> </div> {% endfor %} AJAX <script> function deleteAppointment(appointmentId) { $.ajax({ url: '/Vet/DenyAppointment/' + appointmentId, type: 'GET', success: function(response) { window.location.href = "/Dashboard"; } }); } </script> -
I want to connect mssql server in django rather than default database please suggest me code
I want to connect mssql server in django rather than default database please suggest me the code which, I've to write in "settings.py" file only " settings.py" file code what i've to write in the file -
phyton JSONDecodeError Extra data
Why can such an error occur? Traceback At some point, users going to the site catch a 500 error, the backend accepts json from another application -
React and nginx: refused to connect to localhost
I have my React (frontend) and Django REST (backend) running on a remote Ubuntu server with nginx. I also have a simple reverse proxy defined in conf.d/bookmarks.conf to manage all of that: server { listen 80; listen [::]:80; location /api/ { # Backend proxy_pass http://127.0.0.1:1337/api/; } location / { # Frontend root /var/www/bookmarks/html/; index index.html; try_files $uri $uri/ /index.html; } } I run my Django app with runserver python manage.py runserver 127.0.0.1:1337, and React static files are stored in the folder described above I try to connect to API with React: const generateOpendIdLink = async () => { const generateOpendIdLinkEndpoint = 'http://127.0.0.1/api/opendid-link-generator/'; const requestOptions = { method: 'GET', headers: {'Content-Type': 'application/json'}, }; try { const response = await fetch(generateOpendIdLinkEndpoint, requestOptions); if (response.status == 200) { ... }; } catch (error) { console.log(error); }; }; And get an error GET http://127.0.0.1/api/opendid-link-generator/ net::ERR_CONNECTION_REFUSED This is quite odd, because I could connect to API from the web no problem: running the same GET on the server IP address http://XX.XXX.XX.XX/api/opendid-link-generator/ from Postman works as expected. This is also true when I change 127.0.0.1 for the server IP in the React code, it all starts to work. I also set ALLOWED_HOSTS = ['*'] for test … -
copy a model instance and update a filed in new copy
this is my model. I want to make a copy from my model with copy function. and update the created_time to this time and eventually return the post id from django.db import models from django.utils import timezone class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def copy(self): blog = BlogPost.objects.get(pk=self.pk) comments = blog.comment_set.all() blog.pk = None blog.save() for comment in comments: comment.pk = None comment.blog_post = blog comment.save() return blog.id class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.CharField(max_length=500) I also want copy function makes a copy from post and comments, would you help me to correct my code and update the time in my function. thank you.