Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework and axios post dont work [closed]
I am trying to make a simple api where a user presses a button and then an axios post adds a new instance. I use django rest framework and react. views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) serializers.py from rest_framework import serializers from .models import * class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' App.js function handleSubmit(e) { axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post', { headers:{ 'content-type': 'application/json' }, data: { name: 'a', title: 'b', } }).then(res=>{ console.log(res) }).catch(error=>console.log(error)) } return ( <> <button onClick={handleSubmit}>OK</button> </> ); When I press the button I get `POST http://127.0.0.1:8000/post 500 (Internal Server Error) and Error: Request failed with status code 500 at e.exports (createError.js:16:15) at e.exports (settle.js:17:12) at XMLHttpRequest.S (xhr.js:66:7) What should I do? I dont have a problem with CORS. -
Gmail API OAuth 502
I have the following code that works perfectly on my local machine, but on the remote server, it doesn't redirect to Google OAuth and gives me a 502 error. Where could I have made a mistake? SCOPES = [ 'https://mail.google.com/', ] def get_gmail_service(): creds = None config_path = os.path.join(os.path.dirname(__file__), 'config') credentials_path = os.path.join(config_path, 'creds.json') token_path = os.path.join(config_path, 'token.json') if os.path.exists(token_path): creds = Credentials.from_authorized_user_file(token_path, SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( credentials_path, SCOPES) creds = flow.run_local_server(port=0) with open(token_path, 'w') as token: token.write(creds.to_json()) try: service = build('gmail', 'v1', credentials=creds) return service except HttpError as error: print(f'An error occurred: {error}') def get_emails(): service = get_gmail_service() .... I just need to authenticate with OAuth to access my Gmail account and retrieve emails from it. -
How to add extension to Test Database in django?
I'm using TrigramSimilarity in my project. but when i want to test my view in a testcase it seems that the test database doesn't have the extention. how do i add the extention in test database? def test_person_search(self): query = str(self.person.name) url = reverse("persons:person_search") + f"?q={query}" test_data = { "query": query, "results": [ { "name": "TestPerson", "picture": None, "roles": [{"role": "Test", "slug": "test"}], } ], } response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, test_data) Error: django.db.utils.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...."height_centimeter", "persons_person"."picture", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
Django not migrating CharField with choices properly
I have a model Car with a CharField color, that has the choices of white, black and blue. class Car(models.Model): WHITE = "White" BLACK = "Black" BLUE = "Blue" COLOR_CHOICES = ( (WHITE, "White"), (BLACK, "Black"), (BLUE, "Blue"), ) ... color = models.CharField(max_length=20, choices=COLOR_CHOICES, default=BLUE) I already have created Car objects with a color. Now when I introduce a change to the choices (e.g. change BLUE to RED in all occurences, as well as in the default) and run the migrations, the Car objects of color BLUE that already exist do not get migrated to RED. And that's where the weirdness begins: When I use the django shell to check the objects, they appear as Car.BLUE (the choice that no longer exists). When I inspect the objects in the Django Admin, they appear as Car.WHITE. When I create a new object, it works - it becomes Car.RED automatically (picks up the default). Questions: Are there any specific steps that I missed when migrating choices for the CharField? Why could this weird behavior be happening and how can I safely fix? Do I have to manually (or through a script) fix the data? I expect upon migration all existing Car.BLUE objects … -
How to assign an empty value to an object attribute in Django Admin Interface?
I'm designing an eBay-like website. My project has several models, one of which, namely "Listing", represents all existing products: class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=512) category = models.CharField(max_length=64) image_url = models.URLField() owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_listings") is_active = models.BooleanField(default=True) winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="won_listings", null=True) I need the winner attribute to be able to equal an empty value. But when I try to assign it an empty value in Django Admin Interface, I get an error: How can I solve this problem? Thank you in advance! -
how to download uploaded image
After uploading an image through drf, I want to automatically download it when the user clicks on the image. models.py views.py detailblog.html urls.py If i click the file name, it will be downloaded, but the current page, not the uploaded picture, will be saved in html format. How can i solve this problem? i want to download uploaded image -
Getting Id using Foreign Key in django
Hy Everyone... I have five models in django.. 1- Egg 2-SaleInvocie 3-SaleInvocieItem 4-PurchaseInvocie 5-PurchaseInvocieItem My Scenario is I am making a Sale Return where I am searching for a sale invoice id and select any one id when I select the id it automatically fills the data of that invoice which includes (sale invoice and sale invocie item data). But when I save this it only saves the Sale Return data(which is actually sale invocie data that we retrieves through searching its id) it is not saving the sale return item data (which is actually sale invoice item data), because it i snot getting the id of that hidden input that stores the itme id. and shows me this message in terminal saleReturnItemName [] and my models are this class SaleInvoice(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) searchCustomer=models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customersaleinvoice',null=True) PAYMENT_CHOICES = ( ('paid', 'Paid'), ('unpaid', 'Unpaid'), ) paymentType = models.CharField(max_length=15, choices=PAYMENT_CHOICES,default=None) SHIPMENT_CHOICES = ( ('1', 'Delivery'), ('2', 'Pick Up'), ) shipmentType=models.CharField(max_length=1, choices=SHIPMENT_CHOICES,default=None) searchVehicle=models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name='vehiclesaleinvoice',null=True) searchDriver=models.ForeignKey(Driver, on_delete=models.CASCADE, related_name='driversaleinvoice',null=True) selectNTNInInvoice=models.ForeignKey(NTN, on_delete=models.CASCADE, related_name='selectntn',null=True) invoiceDate=models.DateField(blank=True, null=True) totalSaleAmount=models.CharField(max_length=15,null=True) saleInvoiceAmount=models.CharField(max_length=15,null=True) saleInvoiceDiscount=models.CharField(max_length=15,null=True) STATUS_CHOICES = ( ('in_progress', 'In Progress'), ('delivered', 'Delivered'), ('not_delivered', 'Not Delivered'), ) shipmentStatus = models.CharField(max_length=20,choices=STATUS_CHOICES,default='in_progress',) class SaleReturn(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) … -
Django : stripping HTML after a search filter with dynamic parameters
Some of my database entries contains HTML, and I found here a way exclude HTML from the search so that a user who searches "strong" doesn't get any entry that contains a tag for example. The issue here is that my search contains a dynamic variable wordcontentfilter that looks into a Sense ForeignKey that is "linked" to Mot and that I don't know how to write the part of the if code if query not in strip_tags(i.wordcontentfilter) properly. The other conditions and gramGrp_pos not in strip_tags(i.gramGrp_pos) and gramGrp_gen not in strip_tags(i.gramGrp_gen) and query not in strip_tags(i.slug) works but I need to filter the dynamic part of the search. Any help please ? # We build the request. This request searches into wordcontentfilter = 'sense__' + wordcontent + '__' + search_type print("wordcontentfilter >>> ", wordcontentfilter) filterResult = Mot.objects.filter( Q(**{ wordcontentfilter: query }), Q(gramGrp_pos__icontains = gramGrp_pos), Q(gramGrp_gen__icontains = gramGrp_gen) | Q(slug__icontains = query) ).order_by("slug").distinct() # We strip HTML from results. If user searched a string which can be found in an HTML tag (ex: <strong>), this search result will be removed if filterResult: for j,i in enumerate(filterResult): if query not in strip_tags(i.wordcontentfilter) and gramGrp_pos not in strip_tags(i.gramGrp_pos) and gramGrp_gen not in strip_tags(i.gramGrp_gen) … -
I created a form to let me edit my user and email(using Python, Django, and Vue.js). When I press submit changes, nothing happens
So I am working on this time tracking app for myself, to learn Django and Vue.js, I found a tutorial from Code with Stein. I got stuck at editing the profile part from the tutorial. I get no errors, yet there are no changes made to my username or email(the changes don't even apply to my admin dashboard or database). The thing is that I get no error, which leaves me completely in the dust. Here is the code in edit_profile.html: {% extends 'core/base.html' %} {% block title %}Edit Profile | {% endblock %} {% block content %} <nav class="breadcrumb" aria-label="breadcrumbs"> <ul> <li><a href="#">Dashboard</a></li> <li><a href="{% url 'myaccount' %}">My Account</a></li> <li class="is-active"><a href="{% url 'edit_profile' %}" aria-current="page"></a>Edit Profile</li> </ul> </nav> <div class="columns"> <div class="column is-4"> <h1 class="title">Edit Profile</h1> <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="field"> <label>Username</label> <div class="control"> <input type="text" name="username" id="username" class="input"{% if request.user.username %} value="{{ request.user.username }}" {% endif %}> </div> </div> <div class="field"> <label>Email</label> <div class="control"> <input type="text" name="email" id="email" class="input"{% if request.user.email %} value="{{ request.user.email }}" {% endif %}> </div> </div> <div class="field"> <label>Password(You can change it if you want it.)</label> <div class="control"> <input type="password" name="password" id="password" class="input"{% if request.user.password %} value="{{ request.user.password }}" … -
How to integrate Django oAuth in flutter App
We are currently working on an app that uses Django auth-users and oauth2 as authorization. Now I was looking at the documentation and examples of the flutter-package oauth2, and the tutorial looks quite easy. But it doesn't really work. Does anybody already have a simple solution for oauth2 with django that he could share, or maybe a link to a github project that could help me? -
Django server side cursor is not working in test
with psycopg2.connect(conn_url) as conn: with conn.cursor(name=f"{uuid4()}") as cursor: cursor.itersize = batch_size cursor.execute(raw_sql, params) this is returning empty row in django test. But running correctly in shell_plus. Also I have set @override_settings(DISABLE_SERVER_SIDE_CURSORS=False) . But still getting the same result -
ClientError at /securelogin/products/product/add/ An error occurred (InvalidArgument) when calling the PutObject operation: None
I am trying to add products in django admin.why this error showing. i am uploading in aws s3 bucket.Is there any problem in boto3 or storages Is there anyone for solution.is there anyone who have ever faced this issue.Kindly Responde -
My Django form won't save now that I have styled it using Tailwindcss?
Since I have started using Tailwind CSS to style my form, it won't save. I was previously passing the form like this {{ form.as_p }} but wanted to style it. Now that I have styled the form, it does not correctly submit the data. I have been stuck on this for ages, and any help would be greatly appreciated. Here is all the relevant code. html template: {% load static %} <head> <link href="{% static 'src/output.css' %}" rel="stylesheet" /> <title>Surfer Creation Form</title> </head> <body class="bg-gradient-to-tr from-pink-500 via-purple-500 to-blue-500"> {% include 'include/messages.html' %} <form method="post" action="{% url 'roxy:UserCreate_Surfer' %}"> {% csrf_token %} <!-- User Creation Form --> <div class="flex justify-center items-center"> <div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 my-2"> <h2 class="mb-4">Start your surfing journey now!</h2> <!--Name fields --> <div class="-mx-3 md:flex mb-6"> <div class="md:w-1/2 px-3 mb-6 md:mb-0"> <label for="{{ user_form.first_name.id_for_label }}" class="block text-sm font-normal mb-2" >{{ user_form.first_name.label }}: </label> <input type="text" name="{{ user_form.first_name.html_name }}" id="{{ user_form.first_name.auto_id }}" class="border border-gray-300 rounded px-4 py-2 mb-4 input-field" required /> </div> <!-- Last name field --> <div class="md:w-1/2 px-3 mb-6 md:mb-0"> <label for="{{ user_form.last_name.id_for_label }}" class="block text-sm font-normal mb-2" >{{ user_form.last_name.label }}: </label> <input type="text" name="{{ user_form.last_name.html_name }}" id="{{ user_form.last_name.auto_id }}" class="border border-gray-300 rounded … -
Error while deploying my Django App in Vercel
So My Django app runs perfectly fine on the local server, i've been trying to upload it on vercel but it keeps giving me this error. ***Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-xx4e_y5y/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in setup.cfg*** I've tried locating the setup.cfg file, but i couldn't find any. This is my first deployment, and i don't know how to deploy it yet properly. Any help regarding what the error is and how to solve it, is greatly appreciated. Thanks -
Redirect database call to different db url based on type of query(Read, write, update) with Django
In an existing project how can i implement a method using which i can redirect it different database(Write, Update & read) without modifying existing django queries. If i have 2 queries: MyModel.objects.get(name = "abc") And MyModel.objects.create(name = "xyz") With database config as: DATABASES = { 'read_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'read_db', 'USER': 'read_db', 'PASSWORD': 'read_db', 'HOST': '', 'PORT': '', }, 'write_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'write_db', 'USER': 'write_db', 'PASSWORD': 'write_db', 'HOST': '', 'PORT': '', }, 'update_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'update_db', 'USER': 'update_db', 'PASSWORD': 'update_db', 'HOST': '', 'PORT': '', } } Want read_db to be called for query 1 & write_db for query 2 -
ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'
I want to get listings under a particular category. But when I select the category, I get this error: ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'. VIEWS.PY def index(request): listings = Listing.objects.filter(is_active=True) product_ca = Category.objects.all() return render(request, "auctions/index.html", { "data": listings, "categ": product_ca }) def categories_view(request): if request.method == "POST": c = request.POST["categorys"] cg = Listing.objects.filter(category=c) cg.category_id return render(request, "auctions/Categories_view.html", { "category": cg, }) MODELS.PY class Category(models.Model): type = models.CharField(max_length=100, null=True) def __str__(self): return self.type class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) price_bid = models.DecimalField(decimal_places=2, max_digits=6, default=False) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") Seems I'll have id get the id of c = request.POST["categorys"] in Listing but I don't really know how to go about it. Or maybe am still wrong. -
Jinja does not update properly
I have this code in python: @overviewBlueprint.route('/dashboard/words-cloud', methods=['GET', 'POST']) @login_required def textCloud(): filterParams = buildFilterParams() productScopeStr = request.args.get('product') if request.args.get('product') else 'myproducts' multiWord = request.args.get('multiword') reviewsQuerySet = filterQuerySet(customer_id=session["customer_id"]) wordsType = 'trending' if request.method == 'POST': wordsType = request.form['words-type'] if wordsType and wordsType == 'topics': popularWords = [] topics = topic.getSavedTopicsByQuerySet(reviewsQuerySet) topics = sorted(topics, key=lambda item: item['count'], reverse=True) for element in topics: item = { 'topic': element['topic'], 'driver': { 'totals': { 'reviewCount': element['count'] } } } popularWords.append(item) return render_template("text-cloud.html", filterParams=filterParams, wordsType=wordsType, currentProduct=productScopeStr, multiWord=multiWord, topics=topics, popularwords=popularWords) elif wordsType == 'trending': popularWords = topic.popularTopics(reviewsQuerySet=reviewsQuerySet) return render_template("text-cloud.html", filterParams=filterParams, wordsType=wordsType, currentProduct=productScopeStr, multiWord=multiWord, topics=[], popularwords=popularWords) In the jinja template, I have a select box that has 2 options: trending and topics. I added an onChange event for select elements which makes a post request with the updated value. But every time I change the select value it displays only the first table. As you can see in my template I have two tables : <i class="fa fa-info-circle" aria-hidden="true"></i> Talk About shows how many reviews talk about this subject {% if wordsType == 'trending' %} <table id="popular-words" class="table table-bordered tablesorter"> <thead> <tr> <th>Topic</th> <th>Talk About</th> <th>Sentiment</th> </tr> </thead> <tbody> {% for item in popularwords %} <tr> <td> … -
I have hosted a django application render on free server. It is working fine local machine but not working in render ,i have pushed all the code
I have fetched NSE data from nse api and displayed using chart js in django templates , everything fine in local machine , once i pushed the all code in render server it is showing like this . This page isn’t workingsuperlogo-final.onrender.com is currently unable to handle this request. HTTP ERROR 502. I have uploaded the images please check and help me figure out the problem -
How to send selected option with Django and Ajax?
i have a problem about send or save my selected option to database. I have tried all the ways I know to run this program, but always the selected option is not saved. I have removed the line of code I was trying to solve this problem so that you guys can come up with a solution in your own way. if you guys need more detailed code just let me know. hope you can understand what I'm saying my models.py: class Category(models.Model): category = models.CharField(max_length=200) slug = models.SlugField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(Category,blank=True) thumbnail = models.ImageField(upload_to='thumbnails') slug = models.SlugField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) my forms.py: class GalleryForm(forms.ModelForm): category = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.SelectMultiple, required=False ) class Meta: model = Gallery fields = ['title', 'description', 'category','thumbnail'] my views.py: def gallery_list_and_create(request): form = GalleryForm(request.POST or None, request.FILES or None) if(request.user.is_authenticated): user = User.objects.get(username=request.user.username) gallery_user = user.gallery_set.all() if(is_ajax(request=request)): if(form.is_valid()): instance = form.save(commit=False) instance.author = user instance.save() return JsonResponse({ 'id': instance.id, 'title': instance.title, 'description': instance.description, # 'category': [category.category for category in instance.category.all()], 'thumbnail': instance.thumbnail.url, 'slug': instance.slug, 'author': instance.author.username, 'since': … -
how can i bookmark songs in my django project
I've been trying to put the favorites feature for days with django rest framework and javascript api fetch in my lyrics project but without success all the methods I'm trying don't work please help me I'm a beginner in javascript, even in api with django too. here is what I tried, where did I mow apiviews.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,permissions from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework import generics from rest_framework.response import Response from rest_framework import viewsets, status from rest_framework.decorators import action from .serializers import SongSerializer from .models import Song, User from .models import Song, Favorite class FavoritesongView(APIView): serializer_class = SongSerializer queryset = Song.objects.all() @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def favorite(self, request, id): song = self.get_object() user = request.user if user not in song.favorited_by.all(): song.favorited_by.add(user) song.save() return Response({'status': 'favorited'}) @favorite.mapping.delete def unfavorite(self, request, id=None): song = self.get_object() user = request.user if user in song.favorited_by.all(): song.favorited_by.remove(user) song.save() return Response({'status': 'unfavorited'}) apiurls from django.contrib import admin from django.urls import path from favorites.apiViews import FavoritesongView urlpatterns = [ path('songs/<int:id>/favorite/', FavoritesongView.as_view()) ] js file function addToFavorites(songId) { fetch(`/api/songs/${songId}/favorite/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) .then(response … -
CSRF Failed: CSRF token missing. in Django Rest
I am really confused because I can't avoid this error. My previous projects were not engaged with this error. So anyways I hope you can find solution. here is my settings.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "accounts", "contents", ] 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 = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication" ] } WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' STATIC_ROOT = os.path.join("static") TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' and here is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path("contents/", include("contents.urls")), ] here is accounts.views: from rest_framework.response import Response from rest_framework.generics import CreateAPIView from rest_framework … -
How to configuring Apache as a Reverse Proxy for a Django App in a Docker Container: Serving Static Files
I have Django app that runs in docker container. I have a problem with serving static files with my Apache configuration. My django app works inside docker container and Apache correctly routes requests to it I made sure to set STATIC_URL = "/static/" and DEBUG = False settings properties I made sure to collect static to /var/www/my_app/static/ directory I made sure that directory /var/www/my_app has correct acccess rights for apache: drwxr-xr-x 3 www-data www-data 4,0K June 11 16:25 my_app This is my apache config: <VirtualHost 000.00.0.000:443> ServerName my_app.com SSLEngine on SSLProxyEngine on SSLCertificateFile /etc/apache2/certs/cert.pem SSLCertificateKeyFile /etc/apache2/certs/cert.key SSLCACertificateFile /etc/apache2/certs/DigiCertCA.crt CustomLog /var/log/apache2/my_app.log combined ErrorLog /var/log/apache2/my_app.log ProxyPass /static ! Alias /static/ /var/www/my_app/static/ <Directory /var/www/my_app/static/> Require all granted </Directory> <Location /> ProxyPass http://localhost:6000/ ProxyPassReverse http://localhost:6000/ ProxyPreserveHost on </Location> </VirtualHost> Could you help me please to resolve the issue? -
how to create a django form with names from the database
I have a sidebar with a drop-down menu that has categories and dishes. I want to create a checkbox for selection dishes models.py class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Dish(models.Model): category = models.ForeignKey(to=Category, related_name="children", on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=500) weight = models.IntegerField() cost = models.IntegerField() def __str__(self): return self.name in html format it looks like this: <div class="filter-content collapse show" id="collapse_1" style=""> <ul class="list-unstyled ps-0"> {% if category %} {% for cat in category %} <li class="mb-1"> <button class="btn btn-toggle d-inline-flex align-items-center rounded border-0 collapsed" data-bs-toggle="collapse" data-bs-target="#{{ cat.id }}" aria-expanded="false"> {{ cat.name }} </button> {% for dish in cat.children.all %} <div class="collapse" id="{{ cat.id }}" style=""> <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small"> <li> <div class="list-group list-group-checkable d-grid gap-2 border-0"> <input class="list-group-item-check pe-none" type="checkbox" name="listGroupCheckableRadios" id="{{dish.name}}" value=""> <label class="list-group-item rounded-3 py-3" for="{{dish.name}}"> {{dish.name}} </label> </div> </li> </ul> </div> {% endfor %} </li> {% endfor %} {% else %} <p>no values</p> {% endif %} </ul> </div> to handle clicking on the checkbox, I create a form: class DishForm(ModelForm): class Meta: model = Basket fields = ['dish'] widgets = {"dish": CheckboxInput(attrs={ 'class': 'list-group-item-check pe-none', 'type': 'checkbox', }) } and added this form to html <div class="filter-content collapse show" id="collapse_1" … -
How to host 2 server in one Azure App Service?
I'm having a web app which is based on ReactJS (Frontend) + Django (Backend), I've integrated ReactJS with Django and make it as single server based application. I have 1 more server which is based on Express JS separately. I'm trying to host my web application in Azure app service and publisher is Docker Container. So, I am hosting React + Django based web app in 1 app services it is successfully getting hosted along with the SSL certificates. Now, I am trying to host Express JS in same web app in which I hosted React + Django based web app since Django + React is running on port 80 . I am not able to host Express JS in same app service and if I am trying to host Express JS on separate app service, it is getting hosted but now domain is changed or there need to be some subdomain which I don't want. PROBLEM: I want to host both Django+React server and Express JS server in same app service in which my main web-app is hosted. Any help or any leads are highly appreciated -
While activating the user in django using the token and uid, there getting the following error, why? [closed]
File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'str' object has no attribute 'get' [12/Jun/2023 06:25:59] "GET /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ HTTP/1.1" 500 66953 and this is my page AttributeError at /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:7000/active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: /home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py, line 27, in process_response Raised during: user.views.active Python Executable: /home/cybermate/Desktop/NewProject/env/bin/python3 Python Version: 3.10.6 Python Path: ['/home/cybermate/Desktop/NewProject/eshopy', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages'] Server time: Mon, 12 Jun 2023 06:25:59 +0000 i tried a lot can you mension what should and why this happening. could you explain?